问:
PL SQL cursor for/while loop procedures
Hi need some help regarding some works I've got assigned with having a little trouble figuring it out.

```<code>CREATE TABLE "DET_CAM"
    ("EQUIPMENT_ID" NVARCHAR2(100),
    "EQUIPMENT_TYPE_ID" NUMBER(6),
    "LINK_ID" NUMBER(9),
    "NODE_FR_ID" NUMBER(9),
    "NODE_TO_ID" NUMBER(9),
    "ROAD_NAME" NVARCHAR2(64),
    "DIRECTION" NUMBER(1)
    );
</code>```

Insert Data file

Created a for loop to cycle through Main Equipment/Links. With use of another 2 loops with parameter how can I find out what's the next or previous blocks that come before and after the main block.

Link flow how the logic should work

```<code>Declare
    -- Cursors --
    Cursor c_MainLink
    is
        Select equipment_id, link_id, node_fr_id, node_to_id, road_name, direction
        From DET_CAM
        where 1=1 and equipment_type_id = 113;

    -- Downstream Cursor with parameter --
    Cursor c_downlink (p_dn_node_to_id NUMBER, p_dn_direction NUMBER)
    is
        Select a.node_to_id, a.direction, a.equipment_id, a.link_id, a.road_name, a.location_id
        From DET_CAM a
        where 1=1 and equipment_type_id = 113 and a.node_to_id = p_dn_node_to_id and a.direction = p_dn_direction
        Order by road_name asc, direction asc;

    -- Upstream Cursor with parameter --
    Cursor c_uplink (p_up_node_fr_id NUMBER, p_up_direction NUMBER)
    is
        Select a.node_fr_id, a.direction, a.equipment_id, a.link_id, a.road_name, a.location_id
        From DET_CAM a
        where 1=1 and equipment_type_id = 113 and a.node_fr_id = p_up_node_fr_id and a.direction = p_up_direction
        Order by road_name asc, direction asc;

Begin
    for m_equip in c_MainLink loop
            for ds_equip in c_downlink(m_equip.node_fr_id, m_equip.direction) loop
                for up_equip in c_uplink(m_equip.node_to_id, m_equip.direction) loop
                    dbms_output.put_line('Downstream (equip_ID, Link_ID, RN): '||ds_equip.equipment_id||' | '||ds_equip.link_id||' | '||ds_equip.road_name||
                                         ' | Main (equip_ID, Link_ID, RN): '||ds_equip.equipment_id||' | '||ds_equip.link_id||' | '||ds_equip.road_name||
                                         ' | Upstream (equip_ID, Link_ID, RN): '||up_equip.equipment_id||' | '||up_equip.link_id||' | '||up_equip.road_name
                                         );
                end loop;
            end loop;
    end loop;
End;

/* Actual Result:*/
Downstream (equip_ID, Link_ID, RN): DET_516323 | 34854 | BISHAN FLYOVER | Main (equip_ID, Link_ID, RN): DET_516323 | 34854 | BISHAN FLYOVER | Upstream (equip_ID, Link_ID, RN): DET_516325 | 34637 | BISHAN FLYOVER
Downstream (equip_ID, Link_ID, RN): DET_566338 | 167815 | TUAS VIADUCT | Main (equip_ID, Link_ID, RN): DET_566338 | 167815 | TUAS VIADUCT | Upstream (equip_ID, Link_ID, RN): DET_566336 | 167817 | TUAS VIADUCT
</code>```

/* Expected Result:*/

SQL Combine table

Img Example: Display both Downstream & Upstream links of an associated equipment that has been selected along with both the equipment details and road name of those links

Both up and downlink block should be identical to one another just one is the reverse to the other, at least from my understanding of the ask.
What's happening now is that its show the blocks that are directly connected to each other however if there is a hole between 2 blocks it will not show the Next/Previous block after the missing block (which is what I need).

*Note that the links and node ids are not in sequence.... and I think this is one of the main reason why I'm finding it difficult to get it to work.

答:
```<code> DECLARE
  CURSOR c_product
  IS
    SELECT
        product_name, list_price
    FROM
       products
    ORDER BY
    list_price DESC;
BEGIN
  FOR r_product IN c_product
  LOOP
   dbms_output.put_line( r_product.product_name || ': $' ||  r_product.list_price);
 END LOOP;
END;
</code>```

Title: PL SQL cursor for/while loop procedures

Body:
Hi need some help regarding some works I've got assigned with having a little trouble figuring it out.

CREATE TABLE "DET_CAM"
    ("EQUIPMENT_ID" NVARCHAR2(100),
    "EQUIPMENT_TYPE_ID" NUMBER(6),
    "LINK_ID" NUMBER(9),
    "NODE_FR_ID" NUMBER(9),
    "NODE_TO_ID" NUMBER(9),
    "ROAD_NAME" NVARCHAR2(64),
    "DIRECTION" NUMBER(1)
    );

Insert Data file

Created a for loop to cycle through Main Equipment/Links. With use of another 2 loops with parameter how can I find out what's the next or previous blocks that come before and after the main block.

Link flow how the logic should work

Declare
    -- Cursors --
    Cursor c_MainLink
    is
        Select equipment_id, link_id, node_fr_id, node_to_id, road_name, direction
        From DET_CAM
        where 1=1 and equipment_type_id = 113;

    -- Downstream Cursor with parameter --
    Cursor c_downlink (p_dn_node_to_id NUMBER, p_dn_direction NUMBER)
    is
        Select a.node_to_id, a.direction, a.equipment_id, a.link_id, a.road_name, a.location_id
        From DET_CAM a
        where 1=1 and equipment_type_id = 113 and a.node_to_id = p_dn_node_to_id and a.direction = p_dn_direction
        Order by road_name asc, direction asc;

    -- Upstream Cursor with parameter --
    Cursor c_uplink (p_up_node_fr_id NUMBER, p_up_direction NUMBER)
    is
        Select a.node_fr_id, a.direction, a.equipment_id, a.link_id, a.road_name, a.location_id
        From DET_CAM a
        where 1=1 and equipment_type_id = 113 and a.node_fr_id = p_up_node_fr_id and a.direction = p_up_direction
        Order by road_name asc, direction asc;

Begin
    for m_equip in c_MainLink loop
            for ds_equip in c_downlink(m_equip.node_fr_id, m_equip.direction) loop
                for up_equip in c_uplink(m_equip.node_to_id, m_equip.direction) loop
                    dbms_output.put_line('Downstream (equip_ID, Link_ID, RN): '||ds_equip.equipment_id||' | '||ds_equip.link_id||' | '||ds_equip.road_name||
                                         ' | Main (equip_ID, Link_ID, RN): '||ds_equip.equipment_id||' | '||ds_equip.link_id||' | '||ds_equip.road_name||
                                         ' | Upstream (equip_ID, Link_ID, RN): '||up_equip.equipment_id||' | '||up_equip.link_id||' | '||up_equip.road_name
                                         );
                end loop;
            end loop;
    end loop;
End;

/* Actual Result:*/
Downstream (equip_ID, Link_ID, RN): DET_516323 | 34854 | BISHAN FLYOVER | Main (equip_ID, Link_ID, RN): DET_516323 | 34854 | BISHAN FLYOVER | Upstream (equip_ID, Link_ID, RN): DET_516325 | 34637 | BISHAN FLYOVER
Downstream (equip_ID, Link_ID, RN): DET_566338 | 167815 | TUAS VIADUCT | Main (equip_ID, Link_ID, RN): DET_566338 | 167815 | TUAS VIADUCT | Upstream (equip_ID, Link_ID, RN): DET_566336 | 167817 | TUAS VIADUCT

/* Expected Result:*/

SQL Combine table

Img Example: Display both Downstream & Upstream links of an associated equipment that has been selected along with both the equipment details and road name of those links

Both up and downlink block should be identical to one another just one is the reverse to the other, at least from my understanding of the ask.
What's happening now is that its show the blocks that are directly connected to each other however if there is a hole between 2 blocks it will not show the Next/Previous block after the missing block (which is what I need).

*Note that the links and node ids are not in sequence.... and I think this is one of the main reason why I'm finding it difficult to get it to work.


来源: stackexchange

问:
c# - cast generic class to its base non-generic class
I have following classes:

```<code>public abstract class CustomerBase
{
    public long CustomerNumber { get; set; }
    public string Name { get; set; }
}

public abstract class CustomerWithChildern<T> : CustomerBase
    where T: CustomerBase
{
    public IList<T> Childern { get; private set; }

    public CustomerWithChildern()
    {
        Childern = new List<T>();
    }
}

public class SalesOffice : CustomerWithChildern<NationalNegotiation>
{
}
</code>```

The SalesOffice is just one of few classes which represent different levels of customer hierarchy. Now I need to walk through this hierarchy from some point (CustomerBase). I can't figure out how to implement without using reflection. I'd like to implement something like:

```<code>    public void WalkHierarchy(CustomerBase start)
    {
        Print(start.CustomerNumber);
        if (start is CustomerWithChildern<>)
        {
            foreach(ch in start.Childern)
            {
                WalkHierarchy(ch);
            }
        }
    }
</code>```

Is there any chance I could get something like this working?

The solution based on suggested has-childern interface I implemented:

```<code>public interface ICustomerWithChildern
{
    IEnumerable ChildernEnum { get; }
}

public abstract class CustomerWithChildern<T> : CustomerBase, ICustomerWithChildern
    where T: CustomerBase
{
    public IEnumerable ChildernEnum { get { return Childern; } }

    public IList<T> Childern { get; private set; }

    public CustomerWithChildern()
    {
        Childern = new List<T>();
    }
}

    public void WalkHierarchy(CustomerBase start)
    {
        var x = start.CustomerNumber;
        var c = start as ICustomerWithChildern;
        if (c != null)
        {
            foreach(var ch in c.ChildernEnum)
            {
                WalkHierarchy((CustomerBase)ch);
            }
        }
    }
</code>```

答:
I believe that you want to make the lookup for the determination of doing to the walk an interface.

So maybe add an "IWalkable" interface that exposes the information needed to do the walk, then you can create your method checking to see if the passed object implements the interface.

OwnerDisplayName: Buthrakaur

ContentLicense: CC BY-SA 2.5

Body:
I have following classes:

public abstract class CustomerBase
{
    public long CustomerNumber { get; set; }
    public string Name { get; set; }
}

public abstract class CustomerWithChildern<T> : CustomerBase
    where T: CustomerBase
{
    public IList<T> Childern { get; private set; }

    public CustomerWithChildern()
    {
        Childern = new List<T>();
    }
}

public class SalesOffice : CustomerWithChildern<NationalNegotiation>
{
}

The SalesOffice is just one of few classes which represent different levels of customer hierarchy. Now I need to walk through this hierarchy from some point (CustomerBase). I can't figure out how to implement without using reflection. I'd like to implement something like:

    public void WalkHierarchy(CustomerBase start)
    {
        Print(start.CustomerNumber);
        if (start is CustomerWithChildern<>)
        {
            foreach(ch in start.Childern)
            {
                WalkHierarchy(ch);
            }
        }
    }

Is there any chance I could get something like this working?

The solution based on suggested has-childern interface I implemented:

public interface ICustomerWithChildern
{
    IEnumerable ChildernEnum { get; }
}

public abstract class CustomerWithChildern<T> : CustomerBase, ICustomerWithChildern
    where T: CustomerBase
{
    public IEnumerable ChildernEnum { get { return Childern; } }

    public IList<T> Childern { get; private set; }

    public CustomerWithChildern()
    {
        Childern = new List<T>();
    }
}

    public void WalkHierarchy(CustomerBase start)
    {
        var x = start.CustomerNumber;
        var c = start as ICustomerWithChildern;
        if (c != null)
        {
            foreach(var ch in c.ChildernEnum)
            {
                WalkHierarchy((CustomerBase)ch);
            }
        }
    }

LastEditorDisplayName: Buthrakaur

OwnerDisplayName: Mitchel Sellers


问:
Where to place ||
I know that this is a really simple question, but where should I place the || below if I want to check for both CAF and AAC? Thanks!</p>

```<code>if ([[file pathExtension] isEqualToString:@"caf"])
</code>```

答:
You have to test it twice:

```<code>if ([[file pathExtension] isEqualToString:@"caf"] ||
    [[file pathExtension] isEqualToString:@"aac"])
</code>```

Or, avoid some repetition by doing it like:

```<code>NSString *ext = [file pathExtension];
if ([ext isEqualToString:@"caf"] ||
    [ext isEqualToString:@"aac"])
</code>```

ContentLicense: CC BY-SA 3.0

Title: Where to place ||

Body:
I know that this is a really simple question, but where should I place the || below if I want to check for both CAF and AAC? Thanks!

if ([[file pathExtension] isEqualToString:@"caf"])

Body:
You have to test it twice:

if ([[file pathExtension] isEqualToString:@"caf"] ||
    [[file pathExtension] isEqualToString:@"aac"])

Or, avoid some repetition by doing it like:

NSString *ext = [file pathExtension];
if ([ext isEqualToString:@"caf"] ||
    [ext isEqualToString:@"aac"])


问:
Az query to list all subscriptions, resource groups and resources in it
I am trying to iterate over all azure subscriptions, resource groups and resources</p>

答:
You can use the below PowerShell script to pull the list of all subscriptions & their resource groups & resources in it.

```<code>Connect-AzAccount
$subs=Get-AzSubscription
foreach($sub in $subs){

  Set-AzContext -Subscription $sub.id -Force
  $resourcegroups= Get-AzResourceGroup
  Write-Host "Currently connected  to subscription"$sub.id -ForegroundColor red -BackgroundColor white

  foreach($rg in $resourcegroups){

    Write-Host "Current resourcegroup"$rg.ResourceGroupName -ForegroundColor Yellow -BackgroundColor Black
    Write-Host "Here are list of resources present in this resource group:" -ForegroundColor Cyan
    $resource=Get-AzResource -ResourceGroupName $rg.ResourceGroupName
    Write-Output $resource.ResourceName

  }
}
</code>```

Here is the sample Output for reference:

ContentLicense: CC BY-SA 4.0

Body:
You can use the below PowerShell script to pull the list of all subscriptions & their resource groups & resources in it.

Connect-AzAccount
$subs=Get-AzSubscription
foreach($sub in $subs){

  Set-AzContext -Subscription $sub.id -Force
  $resourcegroups= Get-AzResourceGroup
  Write-Host "Currently connected  to subscription"$sub.id -ForegroundColor red -BackgroundColor white

  foreach($rg in $resourcegroups){

    Write-Host "Current resourcegroup"$rg.ResourceGroupName -ForegroundColor Yellow -BackgroundColor Black
    Write-Host "Here are list of resources present in this resource group:" -ForegroundColor Cyan
    $resource=Get-AzResource -ResourceGroupName $rg.ResourceGroupName
    Write-Output $resource.ResourceName

  }
}

Here is the sample Output for reference:


问:
EditText Inputs don't work when stored as a string,or passed in a Bundle
I am Making a Basic form to take user input send it to different Activity and display it there ,When I use edittext to take a input store it in String variable and then send it  A blank string gets send,There seems to be no error or warnig in code can someone help,Also while testing the string using a toast  if I pass fullname(see code) as Editable and then convert is to String using toString() it works,but if I declare it as a string beforehand and then pass to toast again a blank output
This is my FormActivity

```<code>package com.example.formapp

import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.textservice.TextInfo
import android.widget.Button
import android.widget.EditText
import android.widget.Toast
import com.google.android.material.textfield.TextInputEditText
import java.util.regex.Pattern

class FormActivity : AppCompatActivity() {
    private lateinit var named:EditText
    private lateinit var emailadd : EditText
    private lateinit var branch : EditText
    private  lateinit var desc : TextInputEditText

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_form)
         named =findViewById(R.id.name)
        emailadd  =findViewById(R.id.editTextTextEmailAddress)
         branch=findViewById(R.id.branch)
        desc  =findViewById(R.id.bio)
        val fullName = named.text.toString()
        val email= emailadd.text
        val branchName = branch.text
        val biot= desc.text.toString()
        val bundle = Bundle()
        bundle.putString("key1", named.text.toString())
        bundle.putString("email", email.toString())
        bundle.putString("branch",branchName.toString())
        val intent  = Intent(this,DataPoint::class.java)
        intent.putExtras(bundle)

        val bSumit : Button =findViewById(R.id.submit)

        bSumit.setOnClickListener {
            val isAllinfoCorrect = Checkinfo();
            if(isAllinfoCorrect)
            {

                startActivity(intent)
                Toast.makeText(this,fullName,Toast.LENGTH_LONG).show()
            }
            else
            {
                Toast.makeText(applicationContext,"Please Enter the required fields",Toast.LENGTH_LONG).show()
            }
        }

    }

    private fun Checkinfo(): Boolean {
        var text = named.text.toString()
        if(text.isEmpty())
        {
            named.setError("Field Required")
            return false
        }
        else
        {
            named.setError(null)
        }

        text = emailadd.text.toString()
        val chekmail = "[a-zA-Z0-9._-]+@[a-z]+\\.[a-z]+"
        val expression = "^[\\w.-]+@([\\w\\-]+\\.)+[A-Z]{2,4}$"
        val pattern = Pattern.compile(expression, Pattern.CASE_INSENSITIVE)
        val matcher = pattern.matcher(text)
        if(!matcher.matches() || text.isEmpty())
        {
            emailadd.setError("Please Enter a Valid Email")
            return false

        }
        else
        {
            emailadd.setError(null)
        }
        text=branch.text.toString()
        if(text.isEmpty())
        {
            branch.setError(" Field Required")
            return false
        }
        else
        {
            branch.setError(null)
        }
        return true

    }
}
</code>```

This Is my second activity where I am using bundle

```<code>package com.example.formapp

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.TextView

class DataPoint : AppCompatActivity() {
    private lateinit var name : TextView
    private lateinit var email : TextView
    private lateinit var Branch : TextView
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_data_point)

      val bundle = intent.extras
        val nmaseString= "TEST STRING"

        name=findViewById(R.id.username)
        email=findViewById(R.id.emailAddress)
        Branch = findViewById(R.id.branchname)
        name.setText(bundle?.getString("key1","THIS IS A DEFAULT VALUE"))
        if (bundle != null) {
            email.setText(bundle.getString("email","Default"))
            Branch.setText(bundle.getString("branch","Default"))
        }

    }
}
</code>```

this is the output

xml for datapoint

```<code><?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".DataPoint">

    <androidx.cardview.widget.CardView
        android:id="@+id/card_view"
        android:layout_width="350dp"

        android:layout_height="300dp"
        android:layout_gravity="center"
        android:elevation="5dp"
        android:outlineAmbientShadowColor="@color/black"
        app:cardCornerRadius="10dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.262"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"

        app:layout_constraintVertical_bias="0.436">

        <TextView
            android:id="@+id/username"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginLeft="0dp"
            android:text="NAME"
            android:textAlignment="center"
            android:textSize="25sp"

            android:translationY="50dp"
            tools:visibility="visible"></TextView>

        <TextView
            android:id="@+id/emailAddress"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginStart="0dp"
            android:textAlignment="center"

            android:translationY="100dp" />

        <TextView
            android:id="@+id/branchname"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginStart="0dp"
            android:textAlignment="center"

            android:translationY="150dp" />

    </androidx.cardview.widget.CardView>

</androidx.constraintlayout.widget.ConstraintLayout>
</code>```

答:
It appears you are creating the Bundle and Intent ahead of time.
In onCreate the EditText values are still empty.

Instead, create the Intent & populate the Bundle just before calling the startActivity method.

```<code>override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_form)
    named =findViewById(R.id.name)
    emailadd  =findViewById(R.id.editTextTextEmailAddress)
    branch=findViewById(R.id.branch)
    desc  =findViewById(R.id.bio)
    val bSumit : Button =findViewById(R.id.submit)

    bSumit.setOnClickListener {
        val isAllinfoCorrect = Checkinfo();
        if(isAllinfoCorrect)
        {

            val email= emailadd.text
            val branchName = branch.text
            val biot= desc.text.toString()
            val fullName = named.text.toString()

            val bundle = Bundle()
            bundle.putString("key1", named.text.toString())
            bundle.putString("email", email.toString())
            bundle.putString("branch",branchName.toString())

            val intent  = Intent(this,DataPoint::class.java)
            intent.putExtras(bundle)

            startActivity(intent)
            Toast.makeText(this,fullName,Toast.LENGTH_LONG).show()
        }
        else
        {
            Toast.makeText(applicationContext,"Please Enter the required fields",Toast.LENGTH_LONG).show()
        }
    }

}
</code>```

Body:
I am Making a Basic form to take user input send it to different Activity and display it there ,When I use edittext to take a input store it in String variable and then send it  A blank string gets send,There seems to be no error or warnig in code can someone help,Also while testing the string using a toast  if I pass fullname(see code) as Editable and then convert is to String using toString() it works,but if I declare it as a string beforehand and then pass to toast again a blank output
This is my FormActivity

package com.example.formapp

import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.textservice.TextInfo
import android.widget.Button
import android.widget.EditText
import android.widget.Toast
import com.google.android.material.textfield.TextInputEditText
import java.util.regex.Pattern

class FormActivity : AppCompatActivity() {
    private lateinit var named:EditText
    private lateinit var emailadd : EditText
    private lateinit var branch : EditText
    private  lateinit var desc : TextInputEditText

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_form)
         named =findViewById(R.id.name)
        emailadd  =findViewById(R.id.editTextTextEmailAddress)
         branch=findViewById(R.id.branch)
        desc  =findViewById(R.id.bio)
        val fullName = named.text.toString()
        val email= emailadd.text
        val branchName = branch.text
        val biot= desc.text.toString()
        val bundle = Bundle()
        bundle.putString("key1", named.text.toString())
        bundle.putString("email", email.toString())
        bundle.putString("branch",branchName.toString())
        val intent  = Intent(this,DataPoint::class.java)
        intent.putExtras(bundle)

        val bSumit : Button =findViewById(R.id.submit)

        bSumit.setOnClickListener {
            val isAllinfoCorrect = Checkinfo();
            if(isAllinfoCorrect)
            {

                startActivity(intent)
                Toast.makeText(this,fullName,Toast.LENGTH_LONG).show()
            }
            else
            {
                Toast.makeText(applicationContext,"Please Enter the required fields",Toast.LENGTH_LONG).show()
            }
        }

    }

    private fun Checkinfo(): Boolean {
        var text = named.text.toString()
        if(text.isEmpty())
        {
            named.setError("Field Required")
            return false
        }
        else
        {
            named.setError(null)
        }

        text = emailadd.text.toString()
        val chekmail = "[a-zA-Z0-9._-]+@[a-z]+\\.[a-z]+"
        val expression = "^[\\w.-]+@([\\w\\-]+\\.)+[A-Z]{2,4}$"
        val pattern = Pattern.compile(expression, Pattern.CASE_INSENSITIVE)
        val matcher = pattern.matcher(text)
        if(!matcher.matches() || text.isEmpty())
        {
            emailadd.setError("Please Enter a Valid Email")
            return false

        }
        else
        {
            emailadd.setError(null)
        }
        text=branch.text.toString()
        if(text.isEmpty())
        {
            branch.setError(" Field Required")
            return false
        }
        else
        {
            branch.setError(null)
        }
        return true

    }
}

This Is my second activity where I am using bundle

package com.example.formapp

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.TextView

class DataPoint : AppCompatActivity() {
    private lateinit var name : TextView
    private lateinit var email : TextView
    private lateinit var Branch : TextView
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_data_point)

      val bundle = intent.extras
        val nmaseString= "TEST STRING"

        name=findViewById(R.id.username)
        email=findViewById(R.id.emailAddress)
        Branch = findViewById(R.id.branchname)
        name.setText(bundle?.getString("key1","THIS IS A DEFAULT VALUE"))
        if (bundle != null) {
            email.setText(bundle.getString("email","Default"))
            Branch.setText(bundle.getString("branch","Default"))
        }

    }
}

this is the output

xml for datapoint

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".DataPoint">

    <androidx.cardview.widget.CardView
        android:id="@+id/card_view"
        android:layout_width="350dp"

        android:layout_height="300dp"
        android:layout_gravity="center"
        android:elevation="5dp"
        android:outlineAmbientShadowColor="@color/black"
        app:cardCornerRadius="10dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.262"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"

        app:layout_constraintVertical_bias="0.436">

        <TextView
            android:id="@+id/username"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginLeft="0dp"
            android:text="NAME"
            android:textAlignment="center"
            android:textSize="25sp"

            android:translationY="50dp"
            tools:visibility="visible"></TextView>

        <TextView
            android:id="@+id/emailAddress"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginStart="0dp"
            android:textAlignment="center"

            android:translationY="100dp" />

        <TextView
            android:id="@+id/branchname"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginStart="0dp"
            android:textAlignment="center"

            android:translationY="150dp" />

    </androidx.cardview.widget.CardView>

</androidx.constraintlayout.widget.ConstraintLayout>

Body:
It appears you are creating the Bundle and Intent ahead of time.
In onCreate the EditText values are still empty.

Instead, create the Intent & populate the Bundle just before calling the startActivity method.

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_form)
    named =findViewById(R.id.name)
    emailadd  =findViewById(R.id.editTextTextEmailAddress)
    branch=findViewById(R.id.branch)
    desc  =findViewById(R.id.bio)
    val bSumit : Button =findViewById(R.id.submit)

    bSumit.setOnClickListener {
        val isAllinfoCorrect = Checkinfo();
        if(isAllinfoCorrect)
        {

            val email= emailadd.text
            val branchName = branch.text
            val biot= desc.text.toString()
            val fullName = named.text.toString()

            val bundle = Bundle()
            bundle.putString("key1", named.text.toString())
            bundle.putString("email", email.toString())
            bundle.putString("branch",branchName.toString())

            val intent  = Intent(this,DataPoint::class.java)
            intent.putExtras(bundle)

            startActivity(intent)
            Toast.makeText(this,fullName,Toast.LENGTH_LONG).show()
        }
        else
        {
            Toast.makeText(applicationContext,"Please Enter the required fields",Toast.LENGTH_LONG).show()
        }
    }

}


答:
Move this part of code...

```<code>val bundle = Bundle()
bundle.putString("key1", named.text.toString())
bundle.putString("email", email.toString())
bundle.putString("branch",branchName.toString())
val intent  = Intent(this,DataPoint::class.java)
intent.putExtras(bundle)
</code>```

Inside the listener part like this:

```<code>if(isAllinfoCorrect)
{
    val bundle = Bundle()
    bundle.putString("key1", named.text.toString())
    bundle.putString("email", email.toString())
    bundle.putString("branch",branchName.toString())
    val intent  = Intent(this,DataPoint::class.java)
    intent.putExtras(bundle)
    startActivity(intent)
    Toast.makeText(this,fullName,Toast.LENGTH_LONG).show()
}
</code>```

Title: EditText Inputs don't work when stored as a string,or passed in a Bundle

Body:
Move this part of code...

val bundle = Bundle()
bundle.putString("key1", named.text.toString())
bundle.putString("email", email.toString())
bundle.putString("branch",branchName.toString())
val intent  = Intent(this,DataPoint::class.java)
intent.putExtras(bundle)

Inside the listener part like this:

if(isAllinfoCorrect)
{
    val bundle = Bundle()
    bundle.putString("key1", named.text.toString())
    bundle.putString("email", email.toString())
    bundle.putString("branch",branchName.toString())
    val intent  = Intent(this,DataPoint::class.java)
    intent.putExtras(bundle)
    startActivity(intent)
    Toast.makeText(this,fullName,Toast.LENGTH_LONG).show()
}


问:
Set up a number of categories to display on a page
I am basically looking for a way to display only 3 categories on my template page.
I used a foreach loop to display all the categories on my pages

```<code>$categories = get_categories();
foreach($categories as $category) {
   echo '<div class="col-md-4"><a href="' .
    get_category_link($category->term_id) . '">' . $category->name
  . '</a></div>';
}?>
</code>```

this code displays all the categories on my page but I just want to display 3 per page and eventually add paginations

答:
as per my comments above. the code example I can give you is as follows

for($i = 0; $i <= count($categories); $i++) {
    /*
    Pagination purposes this is how you can format data to an object
    base.
    */
    if($i % 3 = 0) {
       // add to an array
    }
}

for ($i = 0; $i <= 3; $i++) {
// echo categories HTML but $categories[$i] instead
}
```

though let it be known that this wont fully work as you would think etc... etc... I cant explain the modulus operator in depth as I cant think of an easy way without you trying to learn it so you can understand it well.

this way you are only getting 3

Body:
I am basically looking for a way to display only 3 categories on my template page.
I used a foreach loop to display all the categories on my pages

$categories = get_categories();
foreach($categories as $category) {
   echo '
term_id) . '">' . $category->name
  . '
';
}?>

this code displays all the categories on my page but I just want to display 3 per page and eventually add paginations

Body:
as per my comments above. the code example I can give you is as follows

for($i = 0; $i <= count($categories); $i++) {
    /*
    Pagination purposes this is how you can format data to an object
    base.
    */
    if($i % 3 = 0) {
       // add to an array
    }
}

for ($i = 0; $i <= 3; $i++) {
// echo categories HTML but $categories[$i] instead
}

though let it be known that this wont fully work as you would think etc... etc... I cant explain the modulus operator in depth as I cant think of an easy way without you trying to learn it so you can understand it well.

this way you are only getting 3


问:
no tasktracker to stop, no namenode to stop localhost:, no datanode to stop localhost
I am trying to install hadoop on ubuntu using this tutorial

I have changed all the conf files and tried every solution available on the internet.
I dont get any error when i run start-all.sh but when i use jps to check for processes, I get this:->

```<code>3132 Jps
2742 SecondaryNameNode
2830 JobTracker
</code>```

when I use stop-all.sh, I get:->

```<code>stopping jobtracker
localhost: no tasktracker to stop
no namenode to stop
localhost: no datanode to stop
localhost: stopping secondarynamenode
</code>```

this is my jobtracker log

```<code>Problem connecting to HDFS Namenode... re-trying
java.net.ConnectException: Call to localhost/127.0.0.1:54310 failed on connection exception: java.net.ConnectException: Connection refused
    at org.apache.hadoop.ipc.Client.wrapException(Client.java:1142)
    at org.apache.hadoop.ipc.Client.call(Client.java:1118)
    at org.apache.hadoop.ipc.RPC$Invoker.invoke(RPC.java:229)
    at com.sun.proxy.$Proxy7.getProtocolVersion(Unknown Source)
    at sun.reflect.GeneratedMethodAccessor2.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at org.apache.hadoop.io.retry.RetryInvocationHandler.invokeMethod(RetryInvocationHandler.java:85)
</code>```

答:
Tasktracker doesn't exist for Hadoop 2+, which you should be using instead of following a blog using Hadoop 1.

As the jps command has shown, there's no active datanode or namenode processes running, so the rest of the output makes sense

dont get any error when i run start-all.sh

That script hides startup errors. You need to look at the actual namenode and datanode log files to see why they aren't starting

Body:
I am trying to install hadoop on ubuntu using this tutorial

I have changed all the conf files and tried every solution available on the internet.
I dont get any error when i run start-all.sh but when i use jps to check for processes, I get this:->

3132 Jps
2742 SecondaryNameNode
2830 JobTracker

when I use stop-all.sh, I get:->

stopping jobtracker
localhost: no tasktracker to stop
no namenode to stop
localhost: no datanode to stop
localhost: stopping secondarynamenode

this is my jobtracker log

Problem connecting to HDFS Namenode... re-trying
java.net.ConnectException: Call to localhost/127.0.0.1:54310 failed on connection exception: java.net.ConnectException: Connection refused
    at org.apache.hadoop.ipc.Client.wrapException(Client.java:1142)
    at org.apache.hadoop.ipc.Client.call(Client.java:1118)
    at org.apache.hadoop.ipc.RPC$Invoker.invoke(RPC.java:229)
    at com.sun.proxy.$Proxy7.getProtocolVersion(Unknown Source)
    at sun.reflect.GeneratedMethodAccessor2.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at org.apache.hadoop.io.retry.RetryInvocationHandler.invokeMethod(RetryInvocationHandler.java:85)


问:
How to map multiple objects having two identical values and one different value to one object with list of those different values?
I have an object called RawCarEnumData having 3 enums:

```<code>public class RawCarEnumData {

    private BrandEnum brand;
    private ModelEnum model;
    private ColorEnum color;

    //getters, setters, constructors

}
</code>```

and an object CarEnumData having 2 enums and a list of enums:

```<code>public class CarEnumData {

    private BrandEnum brand;
    private ModelEnum model;
    private List<ColorEnum> colors;

    //getters, setters, constructors

}
</code>```

Now I have a list of RawCarEnumData objects:

```<code>List<RawCarEnumData> rawCarEnumDataList = List.of(
    new RawCarEnumData(BrandEnum.FORD, ModelEnum.FIESTA, ColorEnum.RED),
    new RawCarEnumData(BrandEnum.FORD, ModelEnum.FIESTA, ColorEnum.BLUE),
    new RawCarEnumData(BrandEnum.FORD, ModelEnum.FIESTA, ColorEnum.YELLOW),
    new RawCarEnumData(BrandEnum.FORD, ModelEnum.FOCUS, ColorEnum.YELLOW)
}
</code>```

Now I want to use stream API to map the List<RawCarEnumData> to List<CarEnumData> so the final output will look like this:

```<code>List<CarEnumData> carEnumData:
    - CarEnumData(BrandEnum.FORD, ModelEnum.FIESTA, List.of(ColorEnum.RED, ColorEnum.BLUE, ColorEnum.YELLOW))
    - CarEnumData(BrandEnum.FORD, ModelEnum.FOCUS, List.of(ColorEnum.YELLOW))
</code>```

I have tried a few things but without success. How can this be achieved? Is this even possible?

答:
So what you want to do is to group your RawCarEnumDatas by brand and model, and then reduce each list of RawCarEnumDatas into one CarEnumData. One way to do this would be the following (like Ivo Beckers answer but in Java):

```<code>rawCarEnumDataList.stream()
    .collect(Collectors.groupingBy(car -> Map.entry(car.brand, car.model)))
    .values()
    .stream()
    .map(
        list ->
            new CarEnumData(
                list.get(0).brand,
                list.get(0).model,
                list.stream().map(RawCarEnumData::color).distinct().toList()))
    .toList();
</code>```

Breaking it down, the Collectors.groupingBy gives you a map with keys given by applying a function, and a list of all values that corresponds to that key. Then we pick out the values from this map (giving us a collection of lists of RawCarEnumData) and map each list to a CarEnumData using the first RawCarEnumData for the brand and model, and collecting distinct colors from all the RawCarEnumDatas.

You didn't mention which Java version you use, if using an older version you may have to use collect(Collectors.toList()) and some other way to create the group key.

A slightly fancier way to go about would be to use Collectors.teeing introduced in Java 12:

```<code>final var result =
    rawCarEnumDataList.stream()
        .collect(
            Collectors.groupingBy(
                car -> Map.entry(car.brand, car.model),
                Collectors.teeing(
                    toList(),
                    Collectors.mapping(car -> car.color, toSet()),
                    (list, colors) ->
                        new CarEnumData(
                            list.get(0).brand, list.get(0).model, List.copyOf(colors)))))
        .values();
</code>```

Body:
I have an object called RawCarEnumData having 3 enums:

public class RawCarEnumData {

    private BrandEnum brand;
    private ModelEnum model;
    private ColorEnum color;

    //getters, setters, constructors

}

and an object CarEnumData having 2 enums and a list of enums:

public class CarEnumData {

    private BrandEnum brand;
    private ModelEnum model;
    private List<ColorEnum> colors;

    //getters, setters, constructors

}

Now I have a list of RawCarEnumData objects:

List<RawCarEnumData> rawCarEnumDataList = List.of(
    new RawCarEnumData(BrandEnum.FORD, ModelEnum.FIESTA, ColorEnum.RED),
    new RawCarEnumData(BrandEnum.FORD, ModelEnum.FIESTA, ColorEnum.BLUE),
    new RawCarEnumData(BrandEnum.FORD, ModelEnum.FIESTA, ColorEnum.YELLOW),
    new RawCarEnumData(BrandEnum.FORD, ModelEnum.FOCUS, ColorEnum.YELLOW)
}

Now I want to use stream API to map the List<RawCarEnumData> to List<CarEnumData> so the final output will look like this:

List<CarEnumData> carEnumData:
    - CarEnumData(BrandEnum.FORD, ModelEnum.FIESTA, List.of(ColorEnum.RED, ColorEnum.BLUE, ColorEnum.YELLOW))
    - CarEnumData(BrandEnum.FORD, ModelEnum.FOCUS, List.of(ColorEnum.YELLOW))

I have tried a few things but without success. How can this be achieved? Is this even possible?

Body:
So what you want to do is to group your RawCarEnumDatas by brand and model, and then reduce each list of RawCarEnumDatas into one CarEnumData. One way to do this would be the following (like Ivo Beckers answer but in Java):

rawCarEnumDataList.stream()
    .collect(Collectors.groupingBy(car -> Map.entry(car.brand, car.model)))
    .values()
    .stream()
    .map(
        list ->
            new CarEnumData(
                list.get(0).brand,
                list.get(0).model,
                list.stream().map(RawCarEnumData::color).distinct().toList()))
    .toList();

Breaking it down, the Collectors.groupingBy gives you a map with keys given by applying a function, and a list of all values that corresponds to that key. Then we pick out the values from this map (giving us a collection of lists of RawCarEnumData) and map each list to a CarEnumData using the first RawCarEnumData for the brand and model, and collecting distinct colors from all the RawCarEnumDatas.

You didn't mention which Java version you use, if using an older version you may have to use collect(Collectors.toList()) and some other way to create the group key.

A slightly fancier way to go about would be to use Collectors.teeing introduced in Java 12:

final var result =
    rawCarEnumDataList.stream()
        .collect(
            Collectors.groupingBy(
                car -> Map.entry(car.brand, car.model),
                Collectors.teeing(
                    toList(),
                    Collectors.mapping(car -> car.color, toSet()),
                    (list, colors) ->
                        new CarEnumData(
                            list.get(0).brand, list.get(0).model, List.copyOf(colors)))))
        .values();


问:
How to go exec and pass user input required by the command on run
golang expert, I'm relatively new to go exec stuff and trying to replicate the below command in golang exec

```<code>root@e4187cadd9ed:/opt/sample# ../solana transfer -k ../id.json  --from  prompt://?key=0/2 DE53G9MjqzX8WtexjdySsqogsTgGPD8kzAZFVsQce5fK  0.3  --url devnet
[from] seed phrase:
[from] If this seed phrase has an associated passphrase, enter it now. Otherwise, press ENTER to continue:
</code>```

The program will ask for a seed phrase that needs to be passed so that the program will continue and this can't be passed in the argument.

```<code>cmd := exec.Command(app, arg0, arg1, arg2, arg3,arg4,arg5,arg6)

    subStdin, err := cmd.StdinPipe()
    // check err
    defer subStdin.Close()
    io.WriteString(subStdin, "found post practice action leave spread impact chair skate coach kingdom coral")
</code>```

after that progmram except one more input that I don't know hot to write it in go lang and continute the program

How to pass this particular value dynamically using go lang ?

package main

//solana transfer --from  prompt://?key=0/2 DE53G9MjqzX8WtexjdySsqogsTgGPD8kzAZFVsQce5fK  0.3  --url devnet

import (
    "bytes"
    "fmt"
    "io"
    "os/exec"
)

func main() {
    app := "../solana"

    arg0 := "transfer"
    arg1 := "--from"
    arg2 := "prompt://?key=0/2"
    arg3 := "DE53G9MjqzX8WtexjdySsqogsTgGPD8kzAZFVsQce5fK"
    arg4 := "0.3"
    arg5 := "--url"
    arg6 := "devnet"

    cmd := exec.Command(app, arg0, arg1, arg2, arg3,arg4,arg5,arg6)

    subStdin, err := cmd.StdinPipe()
    // check err
    defer subStdin.Close()
    io.WriteString(subStdin, "abx sd sda sd dsa sd sad sda dsa coach asd dds")
    var out bytes.Buffer
    var stderr bytes.Buffer
    cmd.Stdout = &out
    cmd.Stderr = &stderr
    err = cmd.Run()
    if err != nil {
        fmt.Println(fmt.Sprint(err) + ": " + stderr.String())
        return
    }
    fmt.Println("Result: " + out.String())
    stdout, err := cmd.Output()
    fmt.Println(string(stdout))
}
```

The go program which is written takes all the user input but exit in the user prompt any pointer will be great help here.

答:
Maybe flags could be useful -

package flag implements command-line flag parsing

Usage example

Body:
golang expert, I'm relatively new to go exec stuff and trying to replicate the below command in golang exec

root@e4187cadd9ed:/opt/sample# ../solana transfer -k ../id.json  --from  prompt://?key=0/2 DE53G9MjqzX8WtexjdySsqogsTgGPD8kzAZFVsQce5fK  0.3  --url devnet
[from] seed phrase:
[from] If this seed phrase has an associated passphrase, enter it now. Otherwise, press ENTER to continue:

The program will ask for a seed phrase that needs to be passed so that the program will continue and this can't be passed in the argument.

cmd := exec.Command(app, arg0, arg1, arg2, arg3,arg4,arg5,arg6)

    subStdin, err := cmd.StdinPipe()
    // check err
    defer subStdin.Close()
    io.WriteString(subStdin, "found post practice action leave spread impact chair skate coach kingdom coral")

after that progmram except one more input that I don't know hot to write it in go lang and continute the program

How to pass this particular value dynamically using go lang ?

package main

//solana transfer --from  prompt://?key=0/2 DE53G9MjqzX8WtexjdySsqogsTgGPD8kzAZFVsQce5fK  0.3  --url devnet

import (
    "bytes"
    "fmt"
    "io"
    "os/exec"
)

func main() {
    app := "../solana"

    arg0 := "transfer"
    arg1 := "--from"
    arg2 := "prompt://?key=0/2"
    arg3 := "DE53G9MjqzX8WtexjdySsqogsTgGPD8kzAZFVsQce5fK"
    arg4 := "0.3"
    arg5 := "--url"
    arg6 := "devnet"

    cmd := exec.Command(app, arg0, arg1, arg2, arg3,arg4,arg5,arg6)

    subStdin, err := cmd.StdinPipe()
    // check err
    defer subStdin.Close()
    io.WriteString(subStdin, "abx sd sda sd dsa sd sad sda dsa coach asd dds")
    var out bytes.Buffer
    var stderr bytes.Buffer
    cmd.Stdout = &out
    cmd.Stderr = &stderr
    err = cmd.Run()
    if err != nil {
        fmt.Println(fmt.Sprint(err) + ": " + stderr.String())
        return
    }
    fmt.Println("Result: " + out.String())
    stdout, err := cmd.Output()
    fmt.Println(string(stdout))
}

The go program which is written takes all the user input but exit in the user prompt any pointer will be great help here.


问:
What's the best way to get options Active Storage variant from db?
I need to get a options ( for example, resize_to_limit: [300, 222], kuwahara: '3%' ) of variant Active Storage (Ruby on Rails 6.1) from the db.
My decision:

app/admin/slideshow.rb

```<code>form do |f|
  f.inputs 'Slideshow' do
  f.input :name
  f.input :options,
          input_html: { value: f.object.options || "{ resize_to_limit: [300, 222], kuwahara: '3%' }" },
          label: 'Options. For example: { resize_to_limit: [300, 222], monochrome: true }'
  f.input :images, as: :file, input_html: { multiple: true }
  end
  f.actions
end
</code>```

app/controllers/slideshow_controllers.rb

```<code>  def options
   @options = proc {
   $SAFE = 1
   eval(Slideshow.take.options) if slideshow
}.call
  end

  def slideshow
   Slideshow.published.take
  end
</code>```

index.html.erb

```<code><% if slideshow_present? %>
    <% @slideshow.images.each do |x| %>
        <a href="<%= path_to_file(x) %>" data-lightbox="photo" class="col-sm-4">
        <%= image_tag x.variant(@options),
                :class => "img-fluid" %>
        </a>
    <% end %>
<% end %>
</code>```

app/helpers/slideshows_helper.rb

```<code>  def path_to_file(x)
   Rails.application.routes.url_helpers.rails_blob_path(x, only_path: true)
  end
</code>```

But I think using eval is not the best way to go. Perhaps you can recommend the best solution for me?

P.S. Is it advisable to use Ruby safe levels?

答:
It's very simple...

app/admin/slideshow.rb

```<code>  form do |f|
    f.inputs 'Slideshow' do
      f.input :name
      f.input :options,
              input_html: { value: f.object.options || '{ "resize_to_limit": [300, 222], "kuwahara": "3%", "quality": 15 }' },
              label: 'Options. For example: { "resize_to_limit": [300, 222], "monochrome": true }'
      f.input :images, as: :file, input_html: { multiple: true }
    end
    f.actions
  end
</code>```

app/controllers/slideshow_controllers.rb

```<code>  def options
    #     @options = proc {
    #       $SAFE = 1
    #       eval(Slideshow.take.options) if slideshow
    #     }.call
    @options = JSON.parse(Slideshow.take.options) if slideshow
  end
</code>```

For example

Body:
I need to get a options ( for example, resize_to_limit: [300, 222], kuwahara: '3%' ) of variant Active Storage (Ruby on Rails 6.1) from the db.
My decision:

app/admin/slideshow.rb

form do |f|
  f.inputs 'Slideshow' do
  f.input :name
  f.input :options,
          input_html: { value: f.object.options || "{ resize_to_limit: [300, 222], kuwahara: '3%' }" },
          label: 'Options. For example: { resize_to_limit: [300, 222], monochrome: true }'
  f.input :images, as: :file, input_html: { multiple: true }
  end
  f.actions
end

app/controllers/slideshow_controllers.rb

  def options
   @options = proc {
   $SAFE = 1
   eval(Slideshow.take.options) if slideshow
}.call
  end

  def slideshow
   Slideshow.published.take
  end

index.html.erb

<% if slideshow_present? %>
    <% @slideshow.images.each do |x| %>
        <a href="<%= path_to_file(x) %>" data-lightbox="photo" class="col-sm-4">
        <%= image_tag x.variant(@options),
                :class => "img-fluid" %>

    <% end %>
<% end %>

app/helpers/slideshows_helper.rb

  def path_to_file(x)
   Rails.application.routes.url_helpers.rails_blob_path(x, only_path: true)
  end

But I think using eval is not the best way to go. Perhaps you can recommend the best solution for me?

P.S. Is it advisable to use Ruby safe levels?

Body:
It's very simple...

app/admin/slideshow.rb

  form do |f|
    f.inputs 'Slideshow' do
      f.input :name
      f.input :options,
              input_html: { value: f.object.options || '{ "resize_to_limit": [300, 222], "kuwahara": "3%", "quality": 15 }' },
              label: 'Options. For example: { "resize_to_limit": [300, 222], "monochrome": true }'
      f.input :images, as: :file, input_html: { multiple: true }
    end
    f.actions
  end

app/controllers/slideshow_controllers.rb

  def options
    #     @options = proc {
    #       $SAFE = 1
    #       eval(Slideshow.take.options) if slideshow
    #     }.call
    @options = JSON.parse(Slideshow.take.options) if slideshow
  end

For example


问:
Psudo-Random Number Prediction
I am building a program using various methods of generating psudo random numbers. With reasonable results. I of course get better results (statistically speaking), if I use either the inbuilt random number generator in visual C#, or some other formal psudo random code where the method is not known to me. This is not my question.

My question is, given any of the methods used, and given the fact that any computer generated random number is done according to a specified formula and code logic, it is not by definition truly random. Hense the term psudo random.

Given that fact, is it possible to accurately predict what the number will be. Or at least predict it more accurately than a good guess. My research says that anything guessed correctly up to 73% of the time is really only good guessing. So in order to be considered accurate prediction, it must be able to show correct "guesses" more than 73% of the time in order to say it is not a guess.

Assume we dont know the seed, or if we do know the seed, then we dont know the formula used to get the result from the seed.

The below was edited after I accepted an answer and is for future people woundering what I meant.

up to 73% is a "good guesser" - the accepted answer says there is no such thing. So I will clarify.

In the context of the documentary that I watched they weighted things as follows (my words not direct quotes of the program):

Below 37% is just plain wrong (or a poor guesser).

37% to 63% is the expected range of a normal persons ability to guess, some poorly some well. On average it comes to around 50%.

Really "good guessers", were able to break the 63% barrier and sometimes by a large amount either because they knew what their counterparts (in the case of twins) might answer and therefore answered likewise, or had some other system (in the case of fortune tellers and the like).

Tests were done to determine these systems and it was found that comming close to the 73% barrier by anyone was almost impossible, and it was simply impossible to do it on a regular basis (i.e. more than once) showing that they got lucky the first time round. So anyone who got more than 63% but less than 73% on a regular basis was simply labeled a "good guesser".

One of the answers below suggest if you flip a coin 4 times and you guess right 3 out of 4 times you get 75%. But to do it 10 or 100 times is much more difficult. In the explanation above, the first case would show you were able to predict the future accurately enough to make a difference. Continuing with the same test under the same conditions, ie another 4 flips, and another 4. Would almost always bring the person well below the 73% mark showing them to be at best a "good guesser".

I only mention this to clarify. Its not actually part of the question. Thank you all for your answers and suggestions.

答:
Given that fact, is it possible to accurately predict what the number will be.

No. To prevent exactly that there are cryptographically strong pseudo random number generators.  Even if you know all the parameters (except the seed), you cannot predict the next number. Just like you cannot invert a cryptographic hash, or decrypt an encrypted message without the key.

Title: Psudo-Random Number Prediction


问:
How to call a login function in TestCafe from a Utility class?
I am new to TestCafe and TypeScript.

I want to create a login function from a utility class and call it in beforeEach method.

答:
Please refer to the following articles to see how to organize your code in utility classes in the most optimal way:

https://testcafe.io/documentation/402826/guides/concepts/page-model
https://testcafe.io/documentation/402845/guides/advanced-guides/authentication


问:
how to convert the time type of 2020-06-02 10:40:28.001 to 1591065628 in TDengine database?
how to convert the time type of 2020-06-02 10:40:28.001 to 1591065628 in TDengine database?

I want to convert the time in a certain format and can see it in the shell. Take an example, I want to convert the time 2020-06-02 10:40:28.001 to 1591065628, what should I do?

答:
you can use taos -r option, it will output time as uint64_t

ubuntu@taos ~ $ taos -r

taos> use test;
Database changed.

taos> select * from tb;
       ts       |   speed    |            desc             |
================================================================
 1644216894189 |           1 | test                        |
Query OK, 1 row(s) in set (0.006103s)

```


问:
Hiding error messages if writing to a file fails in a Windows .BAT script
i just subscribe here.

I would want to hide the "Acces is denied." error message in case writing to a read-only file fails. Could someone tell me why the following code doesn't work as expected ? I'm using Windows 10.

```<code>:: This file is assumed to be read-only.
echo( >"MyReadOnlyFile.txt" 2>nul
( echo( ) >"MyReadOnlyFile.txt" 2>nul
</code>```

In both case the "Access is denied." message is displayed, although the following "How-to: Redirection" page at SS64 says the contrary: https://ss64.com/nt/syntax-redirection.html

```<code>Redirect to NUL (hide errors)
command >filename 2> nul  Redirect output to file but suppress error
(command)>filename 2> nul  Redirect output to file but suppress CMD.exe errors
</code>```

Thanks in advance for your help.

Lionel.

答:
You need to enclose the whole redirection expression in parantheses, otherwise you just redirect the output of the echo command:

(echo/> "MyReadOnlyFile.txt") 2> nul
```
<p>Anyway, I'd use something that does not alter the file contents just in case it's not write-protected:</p>
<pre class="lang-cmd prettyprint-override"><code>(rem/>>"MyReadOnlyFile.txt") 2> nul
</code>```

Body:
i just subscribe here.

I would want to hide the "Acces is denied." error message in case writing to a read-only file fails. Could someone tell me why the following code doesn't work as expected ? I'm using Windows 10.

:: This file is assumed to be read-only.
echo( >"MyReadOnlyFile.txt" 2>nul
( echo( ) >"MyReadOnlyFile.txt" 2>nul

In both case the "Access is denied." message is displayed, although the following "How-to: Redirection" page at SS64 says the contrary: https://ss64.com/nt/syntax-redirection.html

Redirect to NUL (hide errors)
command >filename 2> nul  Redirect output to file but suppress error
(command)>filename 2> nul  Redirect output to file but suppress CMD.exe errors

Thanks in advance for your help.

Lionel.

Body:
You need to enclose the whole redirection expression in parantheses, otherwise you just redirect the output of the echo command:

(echo/> "MyReadOnlyFile.txt") 2> nul

Anyway, I'd use something that does not alter the file contents just in case it's not write-protected:

(rem/>>"MyReadOnlyFile.txt") 2> nul


问:
How to make a batch upgrade system for an rpg game
I am making a batch rpg game, and am working on a shop. You are supposed to be able to upgrade your weapons/armor, and i would like to know how to make a way so the price increases when you buy. Heres what i have:

```<code>if %money% GEQ (%WeaponLevel% * 4) / 2 then set money=(%WeaponLevel% * 4) / 2 & set WeaponLevel=%WeaponLevel% + 1
</code>```

Thanks! Hope i'm not too far off :)

答:
You could try:

```<code>rem My weapon upgrade script
set price=weaponlevel * 4
set /a money-= %price%
</code>```

Run that script whenever the player goes to upgrade the weapon and the price will be equal to the weapon level * 4 everytime and will reduce the money by that set price. I hope this help : D

Body:
I am making a batch rpg game, and am working on a shop. You are supposed to be able to upgrade your weapons/armor, and i would like to know how to make a way so the price increases when you buy. Heres what i have:

if %money% GEQ (%WeaponLevel% * 4) / 2 then set money=(%WeaponLevel% * 4) / 2 & set WeaponLevel=%WeaponLevel% + 1

Thanks! Hope i'm not too far off :)

Body:
You could try:

rem My weapon upgrade script
set price=weaponlevel * 4
set /a money-= %price%

Run that script whenever the player goes to upgrade the weapon and the price will be equal to the weapon level * 4 everytime and will reduce the money by that set price. I hope this help : D


问:
Message received from background. Values reset
I'm sending post request from "angular->port 4200" to "expressjs server->port 8000".

As an example i'm folowing this example: https://github.com/kuncevic/angular-httpclient-examples/blob/master/client/src/app/app.component.ts

I'm getting two error :

1)undefined from Nodejs(data and req.body.text)

2)Message received from background. Values reset

Angular side:

```<code>  callServer() {
            const culture = this.getLangCookie().split("-")[0];
            const headers = new HttpHeaders()
            headers.set('Authorization', 'my-auth-token')
            headers.set('Content-Type', 'application/json');

            this.http.post<string>(`http://127.0.0.1:8000/appculture`, culture, {
              headers: headers
            })
            .subscribe(data => {
            });
        }
</code>```

expressjs side:

```<code>const express = require('express');
const app = express();
const bodyParser = require('body-parser');
var path = require('path');

app.all("/*", function(req, res, next){
    res.header('Access-Control-Allow-Origin', '*');
    res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
    res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization, Content-Length, X-Requested-With');
    next();
});

app.use( bodyParser.json() );       // to support JSON-encoded bodies
app.use(bodyParser.urlencoded({     // to support URL-encoded bodies
  extended: true
}));

app.post('/appculture', function (req, res) {
  var currentCulture = `${req.body.text} from Nodejs`;
  req.body.text = `${req.body.text} from Nodejs`;
  res.send(req.body)
})

app.listen(8000, () => {
    console.log('server started');
})
</code>```

答:
Angular side:

```<code> callServer() {
            const culture = this.getLangCookie().split("-")[0];
            const headers = new HttpHeaders()
            headers.set('Authorization', 'my-auth-token')
            headers.set('Content-Type', 'application/json');

            this.http.get(`http://127.0.0.1:8000/appculture?c=` + culture, {
              headers: headers
            })
            .subscribe(data => {
            });
        }
</code>```

Nodejs side:

```<code>app.get('/appculture', function (req, res) {
  currentCulture = req.query.c;
  res.send(req.body)
})
</code>```

Body:
I'm sending post request from "angular->port 4200" to "expressjs server->port 8000".

As an example i'm folowing this example: https://github.com/kuncevic/angular-httpclient-examples/blob/master/client/src/app/app.component.ts

I'm getting two error :

1)undefined from Nodejs(data and req.body.text)

2)Message received from background. Values reset

Angular side:

  callServer() {
            const culture = this.getLangCookie().split("-")[0];
            const headers = new HttpHeaders()
            headers.set('Authorization', 'my-auth-token')
            headers.set('Content-Type', 'application/json');

            this.http.post<string>(`http://127.0.0.1:8000/appculture`, culture, {
              headers: headers
            })
            .subscribe(data => {
            });
        }

expressjs side:

const express = require('express');
const app = express();
const bodyParser = require('body-parser');
var path = require('path');

app.all("/*", function(req, res, next){
    res.header('Access-Control-Allow-Origin', '*');
    res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
    res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization, Content-Length, X-Requested-With');
    next();
});

app.use( bodyParser.json() );       // to support JSON-encoded bodies
app.use(bodyParser.urlencoded({     // to support URL-encoded bodies
  extended: true
}));

app.post('/appculture', function (req, res) {
  var currentCulture = `${req.body.text} from Nodejs`;
  req.body.text = `${req.body.text} from Nodejs`;
  res.send(req.body)
})

app.listen(8000, () => {
    console.log('server started');
})

Body:
Angular side:

 callServer() {
            const culture = this.getLangCookie().split("-")[0];
            const headers = new HttpHeaders()
            headers.set('Authorization', 'my-auth-token')
            headers.set('Content-Type', 'application/json');

            this.http.get(`http://127.0.0.1:8000/appculture?c=` + culture, {
              headers: headers
            })
            .subscribe(data => {
            });
        }

Nodejs side:

app.get('/appculture', function (req, res) {
  currentCulture = req.query.c;
  res.send(req.body)
})


问:
I have unpacked the tuple, still getting error, can anyone explain what's wrong in this code?
[] I have unpacked the tuple, still getting error, can anyone explain what's wrong in this code?1

答:
I tried running your code, I didn't get any errors but there was no output on the console.

I rewrote it this way

```<code>def guest_list(guests):

    for person in guests:
        name = person[0]
        age = person[1]
        profession = person[2]
        print("{} is {} years old and works as a {}".format(name, age, profession))

guest_list([("Ken", 30, "Chef"), ("Pat", 35, "Lawyer"), ("Amanda", 25, "Engineer")])
</code>```

Body:
I tried running your code, I didn't get any errors but there was no output on the console.

I rewrote it this way

def guest_list(guests):

    for person in guests:
        name = person[0]
        age = person[1]
        profession = person[2]
        print("{} is {} years old and works as a {}".format(name, age, profession))

guest_list([("Ken", 30, "Chef"), ("Pat", 35, "Lawyer"), ("Amanda", 25, "Engineer")])


问:
Can we connect to Sharepoint Rest Api through azure apim?
Is it possible to connect SharePoint rest apis through azure apim backend?</p>

答:
Is it possible to connect SharePoint rest apis through azure apim backend?

Yes we can connect to Sharepoint Rest Api through Azure Apim.

If Sharepoint have the REST endpoint or any of the supported backend then yes they can use APIM to call any REST endpoint (either Sharepoint or any).

You can refer this link for Complete basic operations using SharePoint REST endpoints.


问:
boto3 read bucket files using concurrency method
I am trying to read bucket files without to saving them as a file:

```<code>    import boto3
    import botocore
    from io import StringIO
    import pandas as pd

    s3 = boto3.resource('s3',config=botocore.config.Config(signature_version=botocore.UNSIGNED))
    bucket = self.s3.Bucket('deutsche-boerse-xetra-pds')
    objects = self.bucket.objects.filter(Prefix= date)
    file = pd.read_csv(StringIO(self.bucket.Object(key=object.key).get().get('Body').read().decode('utf-8')))
</code>```

This code works quite well. However, I would like to use concurrency (python asyncio) to speed up the reading process. I did a search into documentation but I could only find something for the download function but not for the get function.

Do you have any suggestion?

Thanks in advance.

答:
I found out a solution which works with multiprocessing since my final goal was to reduce the processing time.

As follow the code:

```<code>def generate_bucket():
        s3_resoursce = boto3.resource('s3',config=botocore.config.Config(signature_version=botocore.UNSIGNED))
        xetra_bucket = s3_resoursce.Bucket('deutsche-boerse-xetra-pds')

        return s3_resoursce, xetra_bucket

def read_csv(object):
    s3local, bucket_local = self.generate_bucket()

    return pd.read_csv(StringIO(bucket_local.Object(key=object).get().get('Body').read().decode('utf-8')))

def import_raw_data(date: List[str]) -> pd.DataFrame:
        import multiprocessing

        s3local, bucket_local2 = self.generate_bucket()
        objects = [i.key for i in list(bucket_local2.objects.filter(Prefix= date[0]))]

        with multiprocessing.Pool(multiprocessing.cpu_count()) as p:
            df = pd.concat(p.map(self.read_csv, objects))

    return df
</code>```

For me it works, but I am sure that there could be the possibility to improve this code. I'm open to suggestions.

Body:
I am trying to read bucket files without to saving them as a file:

    import boto3
    import botocore
    from io import StringIO
    import pandas as pd

    s3 = boto3.resource('s3',config=botocore.config.Config(signature_version=botocore.UNSIGNED))
    bucket = self.s3.Bucket('deutsche-boerse-xetra-pds')
    objects = self.bucket.objects.filter(Prefix= date)
    file = pd.read_csv(StringIO(self.bucket.Object(key=object.key).get().get('Body').read().decode('utf-8')))

This code works quite well. However, I would like to use concurrency (python asyncio) to speed up the reading process. I did a search into documentation but I could only find something for the download function but not for the get function.

Do you have any suggestion?

Thanks in advance.

Body:
I found out a solution which works with multiprocessing since my final goal was to reduce the processing time.

As follow the code:

def generate_bucket():
        s3_resoursce = boto3.resource('s3',config=botocore.config.Config(signature_version=botocore.UNSIGNED))
        xetra_bucket = s3_resoursce.Bucket('deutsche-boerse-xetra-pds')

        return s3_resoursce, xetra_bucket

def read_csv(object):
    s3local, bucket_local = self.generate_bucket()

    return pd.read_csv(StringIO(bucket_local.Object(key=object).get().get('Body').read().decode('utf-8')))

def import_raw_data(date: List[str]) -> pd.DataFrame:
        import multiprocessing

        s3local, bucket_local2 = self.generate_bucket()
        objects = [i.key for i in list(bucket_local2.objects.filter(Prefix= date[0]))]

        with multiprocessing.Pool(multiprocessing.cpu_count()) as p:
            df = pd.concat(p.map(self.read_csv, objects))

    return df

For me it works, but I am sure that there could be the possibility to improve this code. I'm open to suggestions.


问:
AttributeError: 'Sequential' object has no attribute 'op'
I am trying to replace the Keras Functional API with the Sequential API. I have added a minimalistic example that works without requiring any data imports.

Here is the code with the Functional API which works -

#Taken from - https://tomroth.com.au/keras/

```<code>import numpy as np

n_row = 1000
x1 = np.random.randn(n_row)
x2 = np.random.randn(n_row)
x3 = np.random.randn(n_row)
y_classifier = np.array([1 if (x1[i] + x2[i] + (x3[i])/3 + np.random.randn(1) > 1) else 0 for i in range(n_row)])
y_cts = x1 + x2 + x3/3 + np.random.randn(n_row)
dat = np.array([x1, x2, x3]).transpose()

# Generate indexes of test and train
idx_list = np.linspace(0,999,num=1000)
idx_test = np.random.choice(n_row, size = 200, replace=False)
idx_train = np.delete(idx_list, idx_test).astype('int')

# Split data into test and train
dat_train = dat[idx_train,:]
dat_test = dat[idx_test,:]
y_classifier_train = y_classifier[idx_train]
y_classifier_test = y_classifier[idx_test]
y_cts_train = y_cts[idx_train]
y_cts_test = y_cts[idx_test]

# setup
from keras.models import Input, Model
from keras.layers import Dense
from keras.models import Sequential

# # Build the model with Sequential API
# inputs = Input(shape=(3,))
# model = Sequential()
# model.add(inputs)
# model.add(Dense(2, activation="relu"))
# logistic_model = Model(inputs, model)

# Build the model with Functional API
inputs = Input(shape=(3,))
output = Dense(1, activation='sigmoid')(inputs)

logistic_model = Model(inputs, output)

# Compile the model
logistic_model.compile(optimizer='sgd',
                       loss = 'binary_crossentropy',
                       metrics=['accuracy'])

# Fit on training data
logistic_model.optimizer.lr = 0.001
logistic_model.fit(x=dat_train, y=y_classifier_train, epochs = 5,
                   validation_data = (dat_test, y_classifier_test))

logistic_model.fit(x=dat_train, y=y_classifier_train, epochs = 500, verbose=0,
                   validation_data = (dat_test, y_classifier_test))
logistic_model.fit(x=dat_train, y=y_classifier_train, epochs = 1, verbose=1,
                   validation_data = (dat_test, y_classifier_test))
</code>```

However, when I try it with the Sequential API,

```<code>import numpy as np

n_row = 1000
x1 = np.random.randn(n_row)
x2 = np.random.randn(n_row)
x3 = np.random.randn(n_row)
y_classifier = np.array([1 if (x1[i] + x2[i] + (x3[i])/3 + np.random.randn(1) > 1) else 0 for i in range(n_row)])
y_cts = x1 + x2 + x3/3 + np.random.randn(n_row)
dat = np.array([x1, x2, x3]).transpose()

# Generate indexes of test and train
idx_list = np.linspace(0,999,num=1000)
idx_test = np.random.choice(n_row, size = 200, replace=False)
idx_train = np.delete(idx_list, idx_test).astype('int')

# Split data into test and train
dat_train = dat[idx_train,:]
dat_test = dat[idx_test,:]
y_classifier_train = y_classifier[idx_train]
y_classifier_test = y_classifier[idx_test]
y_cts_train = y_cts[idx_train]
y_cts_test = y_cts[idx_test]

# setup
from keras.models import Input, Model
from keras.layers import Dense
from keras.models import Sequential

# Build the model with Sequential API
inputs = Input(shape=(3,))
model = Sequential()
model.add(inputs)
model.add(Dense(2, activation="relu"))
logistic_model = Model(inputs, model)

# # Build the model with Functional API
# inputs = Input(shape=(3,))
# output = Dense(1, activation='sigmoid')(inputs)

logistic_model = Model(inputs, output)

# Compile the model
logistic_model.compile(optimizer='sgd',
                       loss = 'binary_crossentropy',
                       metrics=['accuracy'])

# Fit on training data
logistic_model.optimizer.lr = 0.001
logistic_model.fit(x=dat_train, y=y_classifier_train, epochs = 5,
                   validation_data = (dat_test, y_classifier_test))

logistic_model.fit(x=dat_train, y=y_classifier_train, epochs = 500, verbose=0,
                   validation_data = (dat_test, y_classifier_test))
logistic_model.fit(x=dat_train, y=y_classifier_train, epochs = 1, verbose=1,
                   validation_data = (dat_test, y_classifier_test))
</code>```

I get the following error -

```<code>2022-02-03 14:42:56.883439: I tensorflow/core/platform/cpu_feature_guard.cc:142] This TensorFlow binary is optimized with oneAPI Deep Neural Network Library (oneDNN)to use the following CPU instructions in performance-critical operations:  AVX AVX2
To enable them in other operations, rebuild TensorFlow with the appropriate compiler flags.
Traceback (most recent call last):
  File "C:/Users/thoma/AppData/Roaming/JetBrains/PyCharmCE2020.3/scratches/scratch_19.py", line 35, in <module>
    logistic_model = Model(inputs, model)
  File "C:\Users\thoma\anaconda3\envs\bug_fix\lib\site-packages\tensorflow\python\keras\engine\training.py", line 242, in __new__
    return functional.Functional(*args, **kwargs)
  File "C:\Users\thoma\anaconda3\envs\bug_fix\lib\site-packages\tensorflow\python\training\tracking\base.py", line 457, in _method_wrapper
    result = method(self, *args, **kwargs)
  File "C:\Users\thoma\anaconda3\envs\bug_fix\lib\site-packages\tensorflow\python\keras\engine\functional.py", line 115, in __init__
    self._init_graph_network(inputs, outputs)
  File "C:\Users\thoma\anaconda3\envs\bug_fix\lib\site-packages\tensorflow\python\training\tracking\base.py", line 457, in _method_wrapper
    result = method(self, *args, **kwargs)
  File "C:\Users\thoma\anaconda3\envs\bug_fix\lib\site-packages\tensorflow\python\keras\engine\functional.py", line 142, in _init_graph_network
    base_layer_utils.create_keras_history(self._nested_outputs)
  File "C:\Users\thoma\anaconda3\envs\bug_fix\lib\site-packages\tensorflow\python\keras\engine\base_layer_utils.py", line 191, in create_keras_history
    _, created_layers = _create_keras_history_helper(tensors, set(), [])
  File "C:\Users\thoma\anaconda3\envs\bug_fix\lib\site-packages\tensorflow\python\keras\engine\base_layer_utils.py", line 226, in _create_keras_history_helper
    op = tensor.op  # The Op that created this Tensor.
AttributeError: 'Sequential' object has no attribute 'op'

Process finished with exit code 1
</code>```

Body:
I am trying to replace the Keras Functional API with the Sequential API. I have added a minimalistic example that works without requiring any data imports.

Here is the code with the Functional API which works -

#Taken from - https://tomroth.com.au/keras/

import numpy as np

n_row = 1000
x1 = np.random.randn(n_row)
x2 = np.random.randn(n_row)
x3 = np.random.randn(n_row)
y_classifier = np.array([1 if (x1[i] + x2[i] + (x3[i])/3 + np.random.randn(1) > 1) else 0 for i in range(n_row)])
y_cts = x1 + x2 + x3/3 + np.random.randn(n_row)
dat = np.array([x1, x2, x3]).transpose()

# Generate indexes of test and train
idx_list = np.linspace(0,999,num=1000)
idx_test = np.random.choice(n_row, size = 200, replace=False)
idx_train = np.delete(idx_list, idx_test).astype('int')

# Split data into test and train
dat_train = dat[idx_train,:]
dat_test = dat[idx_test,:]
y_classifier_train = y_classifier[idx_train]
y_classifier_test = y_classifier[idx_test]
y_cts_train = y_cts[idx_train]
y_cts_test = y_cts[idx_test]

# setup
from keras.models import Input, Model
from keras.layers import Dense
from keras.models import Sequential

# # Build the model with Sequential API
# inputs = Input(shape=(3,))
# model = Sequential()
# model.add(inputs)
# model.add(Dense(2, activation="relu"))
# logistic_model = Model(inputs, model)

# Build the model with Functional API
inputs = Input(shape=(3,))
output = Dense(1, activation='sigmoid')(inputs)

logistic_model = Model(inputs, output)

# Compile the model
logistic_model.compile(optimizer='sgd',
                       loss = 'binary_crossentropy',
                       metrics=['accuracy'])

# Fit on training data
logistic_model.optimizer.lr = 0.001
logistic_model.fit(x=dat_train, y=y_classifier_train, epochs = 5,
                   validation_data = (dat_test, y_classifier_test))

logistic_model.fit(x=dat_train, y=y_classifier_train, epochs = 500, verbose=0,
                   validation_data = (dat_test, y_classifier_test))
logistic_model.fit(x=dat_train, y=y_classifier_train, epochs = 1, verbose=1,
                   validation_data = (dat_test, y_classifier_test))

However, when I try it with the Sequential API,

import numpy as np

n_row = 1000
x1 = np.random.randn(n_row)
x2 = np.random.randn(n_row)
x3 = np.random.randn(n_row)
y_classifier = np.array([1 if (x1[i] + x2[i] + (x3[i])/3 + np.random.randn(1) > 1) else 0 for i in range(n_row)])
y_cts = x1 + x2 + x3/3 + np.random.randn(n_row)
dat = np.array([x1, x2, x3]).transpose()

# Generate indexes of test and train
idx_list = np.linspace(0,999,num=1000)
idx_test = np.random.choice(n_row, size = 200, replace=False)
idx_train = np.delete(idx_list, idx_test).astype('int')

# Split data into test and train
dat_train = dat[idx_train,:]
dat_test = dat[idx_test,:]
y_classifier_train = y_classifier[idx_train]
y_classifier_test = y_classifier[idx_test]
y_cts_train = y_cts[idx_train]
y_cts_test = y_cts[idx_test]

# setup
from keras.models import Input, Model
from keras.layers import Dense
from keras.models import Sequential

# Build the model with Sequential API
inputs = Input(shape=(3,))
model = Sequential()
model.add(inputs)
model.add(Dense(2, activation="relu"))
logistic_model = Model(inputs, model)

# # Build the model with Functional API
# inputs = Input(shape=(3,))
# output = Dense(1, activation='sigmoid')(inputs)

logistic_model = Model(inputs, output)

# Compile the model
logistic_model.compile(optimizer='sgd',
                       loss = 'binary_crossentropy',
                       metrics=['accuracy'])

# Fit on training data
logistic_model.optimizer.lr = 0.001
logistic_model.fit(x=dat_train, y=y_classifier_train, epochs = 5,
                   validation_data = (dat_test, y_classifier_test))

logistic_model.fit(x=dat_train, y=y_classifier_train, epochs = 500, verbose=0,
                   validation_data = (dat_test, y_classifier_test))
logistic_model.fit(x=dat_train, y=y_classifier_train, epochs = 1, verbose=1,
                   validation_data = (dat_test, y_classifier_test))

I get the following error -

2022-02-03 14:42:56.883439: I tensorflow/core/platform/cpu_feature_guard.cc:142] This TensorFlow binary is optimized with oneAPI Deep Neural Network Library (oneDNN)to use the following CPU instructions in performance-critical operations:  AVX AVX2
To enable them in other operations, rebuild TensorFlow with the appropriate compiler flags.
Traceback (most recent call last):
  File "C:/Users/thoma/AppData/Roaming/JetBrains/PyCharmCE2020.3/scratches/scratch_19.py", line 35, in <module>
    logistic_model = Model(inputs, model)
  File "C:\Users\thoma\anaconda3\envs\bug_fix\lib\site-packages\tensorflow\python\keras\engine\training.py", line 242, in __new__
    return functional.Functional(*args, **kwargs)
  File "C:\Users\thoma\anaconda3\envs\bug_fix\lib\site-packages\tensorflow\python\training\tracking\base.py", line 457, in _method_wrapper
    result = method(self, *args, **kwargs)
  File "C:\Users\thoma\anaconda3\envs\bug_fix\lib\site-packages\tensorflow\python\keras\engine\functional.py", line 115, in __init__
    self._init_graph_network(inputs, outputs)
  File "C:\Users\thoma\anaconda3\envs\bug_fix\lib\site-packages\tensorflow\python\training\tracking\base.py", line 457, in _method_wrapper
    result = method(self, *args, **kwargs)
  File "C:\Users\thoma\anaconda3\envs\bug_fix\lib\site-packages\tensorflow\python\keras\engine\functional.py", line 142, in _init_graph_network
    base_layer_utils.create_keras_history(self._nested_outputs)
  File "C:\Users\thoma\anaconda3\envs\bug_fix\lib\site-packages\tensorflow\python\keras\engine\base_layer_utils.py", line 191, in create_keras_history
    _, created_layers = _create_keras_history_helper(tensors, set(), [])
  File "C:\Users\thoma\anaconda3\envs\bug_fix\lib\site-packages\tensorflow\python\keras\engine\base_layer_utils.py", line 226, in _create_keras_history_helper
    op = tensor.op  # The Op that created this Tensor.
AttributeError: 'Sequential' object has no attribute 'op'

Process finished with exit code 1

Body:
The equivalent of this model using the Functional API:

import tensorflow as tf

inputs = tf.keras.layers.Input(shape=(3,))
output = tf.keras.layers.Dense(1, activation='sigmoid')(inputs)
model1 = tf.keras.Model(inputs, output)
print(model1.summary())

Model: "model_1"
_________________________________________________________________
 Layer (type)                Output Shape              Param #
=================================================================
 input_3 (InputLayer)        [(None, 3)]               0

 dense_5 (Dense)             (None, 1)                 4

=================================================================
Total params: 4
Trainable params: 4
Non-trainable params: 0
_________________________________________________________________
None

Is this using the Sequential API:

model2 = tf.keras.Sequential()
model2.add(tf.keras.layers.Dense(1, activation="sigmoid", input_dim=3))
print(model2.summary())

Model: "sequential_5"
_________________________________________________________________
 Layer (type)                Output Shape              Param #
=================================================================
 dense_6 (Dense)             (None, 1)                 4

=================================================================
Total params: 4
Trainable params: 4
Non-trainable params: 0
_________________________________________________________________
None


问:
R Riverplot remove node labels on one side of Sankey plot
I'm using Riverplot to create Sankey plots and placing them in one plot to create a continuous look with three plots. My problem is that I only want node labels on the outmost left and right nodes, not inside.

I've managed to remove the labels from the middle plot with the following code to create the objects, but I was wondering if there is a way to remove only one side of the labels. I've tried creating blank node labels, but both sides of the plot get removed when I've done this.

```<code>make_rp = function(edges) {
  nodes = data.frame(ID=unique(c(edges$N1, edges$N2)),
                     x=rep(c(1,2), each=9))

  style = sapply(nodes$ID, function(id)
    list(col=cols[gsub('(  |) ', '', id)]),
    simplify=FALSE)

  rp = makeRiver(nodes, edges, styles=style)
}

make_rp_inner = function(edges) {
  nodes = data.frame(ID=unique(c(edges$N1, edges$N2)),
                     x=rep(c(1,2), each=9))

  style = sapply(nodes$ID, function(id)
    list(col=cols[gsub('(   |) ', '', id)]),
    simplify=FALSE)

  rp = makeRiver(nodes, edges, styles=style, node_labels=c('','','','','','','','',''))
}
</code>```

and this is my code for plotting:

```<code>par(mar=c(0,0,0,0), mfrow=c(1,3), cex=1.2)
riverplot(rp_90_00,srt=0, plot_area=c(1,.7), gravity='top',
          nodewidth=1.2, node_margin=0.2, fix.pdf=TRUE)

riverplot(rp_00_10,srt=0, plot_area=c(1,.7), gravity='top',
          nodewidth=1, node_margin=0.2, fix.pdf=TRUE)  # uses rp_innner function

riverplot(rp_10_20,srt=0, plot_area=c(1,.7), gravity='top',
          nodewidth=1.4, node_margin=0.2, fix.pdf=TRUE)

</code>```

This is the plot I have currently and I want all but the labels on the outside to be removed.

I fear this might be impossible with how the Riverplot package is set up, but any help would be appreciated.

答:
I found somewhat of a solution to this problem, though it involves a lot of manual input. I ended up having to remove all the node labels. The main idea is node_labels being essentially null, but you can't define it simply as =NULL. The following code is a simplified versions of what I've done:

```<code>plot_n = makeRiver(nodes=nodes, edges=edges, styles=style,
                   node_labels=c('','','','','','','','',''))
</code>```

I then added labels manually to the plot.

```<code>par(mfrow=c(1,3))

riverplot(plot_1)

text("LDW", x = 0.04, y = .88)
text("MDW", x = 0.04, y = .72)
text("LDL", x = 0.04, y = .615)
text("MDL", x = 0.04, y = .523)
text("LDB", x = 0.04, y = .425)
text("MDB", x = 0.04, y = .33)
text("LDA", x = 0.04, y = .235)
text("MDA", x = 0.04, y = .15)
text("HD", x = 0.03, y = .06)

riverplot(plot_2)

riverplot(plot_3)

text("LDW", x = .96, y = .915)
text("MDW", x = 0.96, y = .762)
text("LDL", x = 0.96, y = .64)
text("MDL", x = 0.96, y = .54)
text("LDB", x = 0.96, y = .44)
text("MDB", x = 0.96, y = .341)
text("LDA", x = 0.96, y = .246)
text("MDA", x = 0.96, y = .155)
text("HD", x = 0.98, y = .063)
</code>```

What I noticed is different results occur in pdf versus png, jpeg, etc. formats, but tweaking is fairly easy once the general points are figured out. I hope this can help anyone with a similar problem until a better solution gets discovered or implemented.
The following image is the fixed version of the one in my question.

Body:
I'm using Riverplot to create Sankey plots and placing them in one plot to create a continuous look with three plots. My problem is that I only want node labels on the outmost left and right nodes, not inside.

I've managed to remove the labels from the middle plot with the following code to create the objects, but I was wondering if there is a way to remove only one side of the labels. I've tried creating blank node labels, but both sides of the plot get removed when I've done this.

make_rp = function(edges) {
  nodes = data.frame(ID=unique(c(edges$N1, edges$N2)),
                     x=rep(c(1,2), each=9))

  style = sapply(nodes$ID, function(id)
    list(col=cols[gsub('(  |) ', '', id)]),
    simplify=FALSE)

  rp = makeRiver(nodes, edges, styles=style)
}

make_rp_inner = function(edges) {
  nodes = data.frame(ID=unique(c(edges$N1, edges$N2)),
                     x=rep(c(1,2), each=9))

  style = sapply(nodes$ID, function(id)
    list(col=cols[gsub('(   |) ', '', id)]),
    simplify=FALSE)

  rp = makeRiver(nodes, edges, styles=style, node_labels=c('','','','','','','','',''))
}

and this is my code for plotting:

par(mar=c(0,0,0,0), mfrow=c(1,3), cex=1.2)
riverplot(rp_90_00,srt=0, plot_area=c(1,.7), gravity='top',
          nodewidth=1.2, node_margin=0.2, fix.pdf=TRUE)

riverplot(rp_00_10,srt=0, plot_area=c(1,.7), gravity='top',
          nodewidth=1, node_margin=0.2, fix.pdf=TRUE)  # uses rp_innner function

riverplot(rp_10_20,srt=0, plot_area=c(1,.7), gravity='top',
          nodewidth=1.4, node_margin=0.2, fix.pdf=TRUE)

This is the plot I have currently and I want all but the labels on the outside to be removed.

I fear this might be impossible with how the Riverplot package is set up, but any help would be appreciated.

Body:
I found somewhat of a solution to this problem, though it involves a lot of manual input. I ended up having to remove all the node labels. The main idea is node_labels being essentially null, but you can't define it simply as =NULL. The following code is a simplified versions of what I've done:

plot_n = makeRiver(nodes=nodes, edges=edges, styles=style,
                   node_labels=c('','','','','','','','',''))

I then added labels manually to the plot.

par(mfrow=c(1,3))

riverplot(plot_1)

text("LDW", x = 0.04, y = .88)
text("MDW", x = 0.04, y = .72)
text("LDL", x = 0.04, y = .615)
text("MDL", x = 0.04, y = .523)
text("LDB", x = 0.04, y = .425)
text("MDB", x = 0.04, y = .33)
text("LDA", x = 0.04, y = .235)
text("MDA", x = 0.04, y = .15)
text("HD", x = 0.03, y = .06)

riverplot(plot_2)

riverplot(plot_3)

text("LDW", x = .96, y = .915)
text("MDW", x = 0.96, y = .762)
text("LDL", x = 0.96, y = .64)
text("MDL", x = 0.96, y = .54)
text("LDB", x = 0.96, y = .44)
text("MDB", x = 0.96, y = .341)
text("LDA", x = 0.96, y = .246)
text("MDA", x = 0.96, y = .155)
text("HD", x = 0.98, y = .063)

What I noticed is different results occur in pdf versus png, jpeg, etc. formats, but tweaking is fairly easy once the general points are figured out. I hope this can help anyone with a similar problem until a better solution gets discovered or implemented.
The following image is the fixed version of the one in my question.


问:
Do interfaces have any purpose besides achieving polymorphism and multiple inheritance?
I am trying to understand what the benefits of using interfaces are so that I can know when and how to use them. Most sources on the internet are relatively surface-level, explaining how interfaces work but now why to use them, and when I look up the titular question, I don't get any results that tell me whether the purpose of interfaces extends beyond polymorphism and multiple inheritances.

My reasoning is that if an interface were inherited by only one class, it would be useless, and when an interface is inherited by multiple classes, it makes no difference unless it is used for polymorphism, and the only thing that makes implementation different from extension is multiple inheritances.

If I knew for sure that their purpose was limited to this, I would have an increased confidence in my design decisions, and if I learned of a purpose outside of this, it would fill a serious gap in my knowledge. I have used the design patterns tag because there is perhaps a design pattern which makes use of interfaces in a way that is distinctly beyond mere polymorphism or multiple inheritances.

答:
Assuming that you're talking about the language feature (e.g. interface keyword in Java), as opposed to the general computing term, the purpose of interfaces is polymorphism.

A tool such as interfaces can be abused for other purposes, for example:

As a way of communicating commonality - this can backfire, because if polymorphism isn't the goal of the design, then the classes which declare implementing the interface are making an unnecessary commitment to implement it. That may cease to be relevant when the commonality is eventually broken, which can happen because the classes aren't used polymorphically.

As a way of documenting the contract and allowing the class implementation to change - In Java, this is achieved with public/protected methods with Javadoc are the way to document the contract. Some languages don't even have that, and they still document contracts. Of course, this only works if the contract comes in form of function calls (as opposed to e.g. RESTful HTTP APIs), and it only works if you have a rule about what you document, e.g. package boundary; you wouldn't want to create an interface for every class, even if you document the contract for every class.

To physically hide stuff from the consumer of your interface - this is also about documenting the contract, but if your class has data, or protected methods, and you want to prevent anything outside your package from inheriting, you can expose only an interface. But you can also use final.

Interfaces aren't designed to achieve multiple inheritance; they rather facilitate multiple inheritance only to the extent that is useful for polymorphism; it doesn't really allow you to inherit any fields, and until recently in Java with default methods (so, not by design), not even code.

You would see, in the wild, packages where only one class implements the interface. That doesn't render the interface useless; more implementations may come in the future, and in fact, the package might want to allow callers to offer their own implementation.


问:
System.NotSupportedException: 'The use of 'System.Threading.CancellationToken' on the task-based asynchronous method is not supported.'
I want to use CancellationToken in one of async tasks in my WCF service. the implementation is as follows:

```<code> [ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall, ConcurrencyMode = ConcurrencyMode.Reentrant)]
public partial class MyService: IMyService
{
     private void Initialize()
    {
        _serviceHost = new ServiceHost(this, new Uri[] { new Uri("net.pipe://localhost") });
        var binding = new NetNamedPipeBinding();

        _serviceHost.AddServiceEndpoint(typeof(IMyService), binding, "MyService");
        var behavior = _serviceHost.Description.Behaviors.Find<ServiceBehaviorAttribute>();
        behavior.InstanceContextMode = InstanceContextMode.Single;
        _serviceHost.Open(); // I get error on this line
    }

    public async Task<List<object>> DoSomeWorkAsync(CancellationToken ct = default(CancellationToken))
    {
        //do some work
        ...

        var list = await SomeAwaitableTask(ct);
        return list;
    }
}
</code>```

the WCF interface:

```<code>[ServiceContract(CallbackContract = typeof(IClientCallback))]
public interface IMyService
{
    [OperationContract]
    [FaultContract(typeof(ServiceExceptionDTO))]
    Task<List<object>> DoSomeWorkAsync(CancellationToken ct = default(CancellationToken));
}
</code>```

I get this error :
System.NotSupportedException: 'The use of 'System.Threading.CancellationToken' on the task-based asynchronous method is not supported.'

what should I do and how can I use cancellation token inside my async task?

答:
There is no way to cross service boundaries and cancel on the server side.

You can do this using WCF client-side and task-based async patterns by registering an Abort action with a cancellation token
Or use the extension method WithCancellation of Microsoft.VisualStudio.Threading.ThreadingTools.

For details, see the link below:

How to cancel an async WCF call?

What's the best way to cancel an asynchronous WCF request?

How to use the CancellationToken property?

Body:
I want to use CancellationToken in one of async tasks in my WCF service. the implementation is as follows:

 [ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall, ConcurrencyMode = ConcurrencyMode.Reentrant)]
public partial class MyService: IMyService
{
     private void Initialize()
    {
        _serviceHost = new ServiceHost(this, new Uri[] { new Uri("net.pipe://localhost") });
        var binding = new NetNamedPipeBinding();

        _serviceHost.AddServiceEndpoint(typeof(IMyService), binding, "MyService");
        var behavior = _serviceHost.Description.Behaviors.Find<ServiceBehaviorAttribute>();
        behavior.InstanceContextMode = InstanceContextMode.Single;
        _serviceHost.Open(); // I get error on this line
    }

    public async Task<List<object>> DoSomeWorkAsync(CancellationToken ct = default(CancellationToken))
    {
        //do some work
        ...

        var list = await SomeAwaitableTask(ct);
        return list;
    }
}

the WCF interface:

[ServiceContract(CallbackContract = typeof(IClientCallback))]
public interface IMyService
{
    [OperationContract]
    [FaultContract(typeof(ServiceExceptionDTO))]
    Task<List<object>> DoSomeWorkAsync(CancellationToken ct = default(CancellationToken));
}

I get this error :
System.NotSupportedException: 'The use of 'System.Threading.CancellationToken' on the task-based asynchronous method is not supported.'

what should I do and how can I use cancellation token inside my async task?


问:
Android adb wireless/WIFI debug Operation timed out
I followed steps in this post and tried to connect to my Motorola X Gen 2 for Wifi debugging, on OS X El Cap.

I connected my phone to the laptop with usb cable,
I killed and started server, the server was started successfully, and then in:

```<code>./adb devices
</code>```

I got

```<code>List of devices attached
TA44909GA0  device
</code>```

Then I did

```<code>./adb tcpip 5555
</code>```

And I tried

```<code>./adb connect <IP addr of my phone>:5555
</code>```

both with usb cable connected and disconnected, none of them worked. Both returned error message saying:

```<code>unable to connect to ***.***.***.***:5555: Operation timed out
</code>```

I cannot figure out what is happening here, I tried the Android Studio plugin ADB WIFI, which returned the same message, operation timed out. I restarted everything, tried connecting with a different cable and all, nothing worked.

Does anyone know what's happening here?

答:
If you are using Mac OS.

Check by clicking on the wifi icon in the toolbar. If there is any warning.

In my case there was a warning saying the wifi is using WPA protocol and its not secure.

I went to my router settings and changes the protocol to WPA2/WPA3 auto.

After that the warning went away and the wireless debugging started working.

Body:
I followed steps in this post and tried to connect to my Motorola X Gen 2 for Wifi debugging, on OS X El Cap.

I connected my phone to the laptop with usb cable,
I killed and started server, the server was started successfully, and then in:

./adb devices

I got

List of devices attached
TA44909GA0  device

Then I did

./adb tcpip 5555

And I tried

./adb connect <IP addr of my phone>:5555

both with usb cable connected and disconnected, none of them worked. Both returned error message saying:

unable to connect to ***.***.***.***:5555: Operation timed out

I cannot figure out what is happening here, I tried the Android Studio plugin ADB WIFI, which returned the same message, operation timed out. I restarted everything, tried connecting with a different cable and all, nothing worked.

Does anyone know what's happening here?