问:
Where do I put the nav_host portion of the xml code?
I am trying to figure out where I should be putting the nav_host in my xml files. I am not fully understanding how to get around my application fragments in general.

I have read this Add Drawer layout into main activity

I had most of this working before trying to add the Navigation host (Meaning I could use the drawer menu and navigate). I have not been able to navigate from a fragment to anywhere else with a button that is on that fragment.

My current activity_main.xml

```<code>
    <?xml version="1.0" encoding="utf-8"?>
    <androidx.drawerlayout.widget.DrawerLayout 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:id="@+id/drawer_layout"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:fitsSystemWindows="true"
        tools:context=".MainActivity"
        tools:openDrawer="start">

        <androidx.coordinatorlayout.widget.CoordinatorLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent">
            <com.google.android.material.appbar.AppBarLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:theme="@style/ThemeOverlay.AppCompat.ActionBar">

                <androidx.appcompat.widget.Toolbar
                    android:id="@+id/toolbar"
                    android:layout_width="match_parent"
                    android:layout_height="?attr/actionBarSize"
                    android:background="@color/colorPrimary"
                    android:elevation="4dp"
                    app:popupTheme="@style/ThemeOverlay.AppCompat.Light"/>

            </com.google.android.material.appbar.AppBarLayout>

        </androidx.coordinatorlayout.widget.CoordinatorLayout>

        <androidx.fragment.app.FragmentContainerView
            android:id="@+id/mainActivityHost"
            android:name="androidx.navigation.fragment.NavHostFragment"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            app:defaultNavHost="true"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent"
            app:navGraph="@navigation/mobile_navigation"
            tools:layout="@layout/fragment_home" />

        <com.google.android.material.navigation.NavigationView
            android:id="@+id/nav_view"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_gravity="start"
            app:headerLayout="@layout/nav_header_main"
            app:menu="@menu/drawer_menu"/>

    </androidx.drawerlayout.widget.DrawerLayout>

</code>```

Is where I have the nav_host correct? Or should I have a different Fragment all together for the nav_host?

My MainActivity.class

```<code>
    package com.signin.app;

    import android.os.Bundle;
    import android.view.MenuItem;
    import android.widget.Toast;

    import androidx.annotation.NonNull;
    import androidx.appcompat.app.ActionBarDrawerToggle;
    import androidx.appcompat.app.AppCompatActivity;
    import androidx.appcompat.widget.Toolbar;
    import androidx.core.view.GravityCompat;
    import androidx.drawerlayout.widget.DrawerLayout;

    import com.google.android.material.navigation.NavigationView;

    public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {

        private Toolbar toolbar;

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);

            toolbar = findViewById(R.id.toolbar);
            setSupportActionBar(toolbar);

            DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
            ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                    this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
            drawer.addDrawerListener(toggle);
            toggle.syncState();

            NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
            navigationView.setNavigationItemSelectedListener(this);

            // The program should always start on home.
            if (savedInstanceState == null) {
                getSupportFragmentManager().beginTransaction().replace(R.id.mainActivityHost, new HomeFragment()).commit();
                navigationView.setCheckedItem(R.id.nav_home);
            }
        }

        @SuppressWarnings("StatementWithEmptyBody")
        @Override
        public boolean onNavigationItemSelected(@NonNull MenuItem item) {
            // Handle navigation view item clicks here.
            int id = item.getItemId();

            if (id == R.id.nav_home) {

            } else if (id == R.id.nav_signin) {

            } else if (id == R.id.nav_flights) {

            } else if (id == R.id.nav_hotels) {

            } else if (id == R.id.nav_profile) {

            }

            DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
            drawer.closeDrawer(GravityCompat.START);
            return true;
        }
    //
    //    @Override
    //    public void onBackPressed() {
    //        if (drawer.isDrawerOpen(GravityCompat.START)) {
    //            drawer.closeDrawer(GravityCompat.START);
    //        } else {
    //            super.onBackPressed();
    //        }
    //    }

    }

</code>```

Before I messed with it I could open the drawer click the menu items and go to a fragment, so pretending that still worked the problem was that I could go to Signin fragment, but the buttons on that fragment would not take me anywhere, they mostly just crashed the application.

```<code>
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.navigation.Navigation;

public class SigninFragment extends Fragment {
    private EditText editText;
    private Button btn_signup, btn_signin, btn_forgot_pass;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.activity_main, container,false);

        editText = view.findViewById(R.id.email);
        btn_signup = view.findViewById(R.id.btn_signup);
        btn_signin = view.findViewById(R.id.btn_signin);
        btn_forgot_pass = view.findViewById(R.id.btn_forgot_pass);

        btn_signup.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //Toast.makeText(getContext(), "Sign Up", Toast.LENGTH_SHORT).show();
                Navigation.findNavController(view).navigate(R.id.nav_signup);
            }
        });

        btn_signin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(getContext(), "Sign in", Toast.LENGTH_SHORT).show();
            }
        });

        return view;
    }

}```
Also, please note that nav_signup is not in the drawer menu so I wasn't sure where I was supposed to identify it, (i.e., in the fragment_signup.xml, in its own menu, somewhere else.) right now the id for fragment_signup, is `android:id="@+id/nav_signup"`

```

答:
I'm not sure I understand the question
Navigation.findNavController(view).navigate(R.id.nav_signup); - it should do the navigation and R.id.nav_signup should be destination or action. I'm not sure what R.id.nav_signup is atm. If destination then probably it should be fragment id.

Here's doc about navigations https://developer.android.com/guide/navigation/navigation-navigate#java

And here is Google course about navigation between fragments https://developer.android.com/codelabs/basic-android-kotlin-training-fragments-navigation-component#6 (This guide is in Kotlin but that's just a syntax difference, hopefully still can be useful)

And the final code of this is here https://github.com/google-developer-training/android-basics-kotlin-words-app (it uses navigation/nav_graph.xml to define navigations between fragments)

And for example in src/main/java/com/example/wordsapp/LetterAdapter.kt has navigation to different fragment.

       holder.button.setOnClickListener {
            // LetterListFragmentDirections is defined in nav_graph.xml
            val action = LetterListFragmentDirections.actionLetterListFragmentToWordListFragment(letter = holder.button.text.toString())
            // Navigate using that action
            holder.view.findNavController().navigate(action)
        }
```

I haven't used fragments a long time, but I hope this will be helpful :)

Body:
I am trying to figure out where I should be putting the nav_host in my xml files. I am not fully understanding how to get around my application fragments in general.

I have read this Add Drawer layout into main activity

I had most of this working before trying to add the Navigation host (Meaning I could use the drawer menu and navigate). I have not been able to navigate from a fragment to anywhere else with a button that is on that fragment.

My current activity_main.xml

    <?xml version="1.0" encoding="utf-8"?>
    <androidx.drawerlayout.widget.DrawerLayout 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:id="@+id/drawer_layout"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:fitsSystemWindows="true"
        tools:context=".MainActivity"
        tools:openDrawer="start">

        <androidx.coordinatorlayout.widget.CoordinatorLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent">
            <com.google.android.material.appbar.AppBarLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:theme="@style/ThemeOverlay.AppCompat.ActionBar">

                <androidx.appcompat.widget.Toolbar
                    android:id="@+id/toolbar"
                    android:layout_width="match_parent"
                    android:layout_height="?attr/actionBarSize"
                    android:background="@color/colorPrimary"
                    android:elevation="4dp"
                    app:popupTheme="@style/ThemeOverlay.AppCompat.Light"/>

            </com.google.android.material.appbar.AppBarLayout>

        </androidx.coordinatorlayout.widget.CoordinatorLayout>

        <androidx.fragment.app.FragmentContainerView
            android:id="@+id/mainActivityHost"
            android:name="androidx.navigation.fragment.NavHostFragment"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            app:defaultNavHost="true"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent"
            app:navGraph="@navigation/mobile_navigation"
            tools:layout="@layout/fragment_home" />

        <com.google.android.material.navigation.NavigationView
            android:id="@+id/nav_view"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_gravity="start"
            app:headerLayout="@layout/nav_header_main"
            app:menu="@menu/drawer_menu"/>

    </androidx.drawerlayout.widget.DrawerLayout>

Is where I have the nav_host correct? Or should I have a different Fragment all together for the nav_host?

My MainActivity.class

    package com.signin.app;

    import android.os.Bundle;
    import android.view.MenuItem;
    import android.widget.Toast;

    import androidx.annotation.NonNull;
    import androidx.appcompat.app.ActionBarDrawerToggle;
    import androidx.appcompat.app.AppCompatActivity;
    import androidx.appcompat.widget.Toolbar;
    import androidx.core.view.GravityCompat;
    import androidx.drawerlayout.widget.DrawerLayout;

    import com.google.android.material.navigation.NavigationView;

    public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {

        private Toolbar toolbar;

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);

            toolbar = findViewById(R.id.toolbar);
            setSupportActionBar(toolbar);

            DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
            ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                    this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
            drawer.addDrawerListener(toggle);
            toggle.syncState();

            NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
            navigationView.setNavigationItemSelectedListener(this);

            // The program should always start on home.
            if (savedInstanceState == null) {
                getSupportFragmentManager().beginTransaction().replace(R.id.mainActivityHost, new HomeFragment()).commit();
                navigationView.setCheckedItem(R.id.nav_home);
            }
        }

        @SuppressWarnings("StatementWithEmptyBody")
        @Override
        public boolean onNavigationItemSelected(@NonNull MenuItem item) {
            // Handle navigation view item clicks here.
            int id = item.getItemId();

            if (id == R.id.nav_home) {

            } else if (id == R.id.nav_signin) {

            } else if (id == R.id.nav_flights) {

            } else if (id == R.id.nav_hotels) {

            } else if (id == R.id.nav_profile) {

            }

            DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
            drawer.closeDrawer(GravityCompat.START);
            return true;
        }
    //
    //    @Override
    //    public void onBackPressed() {
    //        if (drawer.isDrawerOpen(GravityCompat.START)) {
    //            drawer.closeDrawer(GravityCompat.START);
    //        } else {
    //            super.onBackPressed();
    //        }
    //    }

    }

Before I messed with it I could open the drawer click the menu items and go to a fragment, so pretending that still worked the problem was that I could go to Signin fragment, but the buttons on that fragment would not take me anywhere, they mostly just crashed the application.

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.navigation.Navigation;

public class SigninFragment extends Fragment {
    private EditText editText;
    private Button btn_signup, btn_signin, btn_forgot_pass;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.activity_main, container,false);

        editText = view.findViewById(R.id.email);
        btn_signup = view.findViewById(R.id.btn_signup);
        btn_signin = view.findViewById(R.id.btn_signin);
        btn_forgot_pass = view.findViewById(R.id.btn_forgot_pass);

        btn_signup.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //Toast.makeText(getContext(), "Sign Up", Toast.LENGTH_SHORT).show();
                Navigation.findNavController(view).navigate(R.id.nav_signup);
            }
        });

        btn_signin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(getContext(), "Sign in", Toast.LENGTH_SHORT).show();
            }
        });

        return view;
    }

}```
Also, please note that nav_signup is not in the drawer menu so I wasn't sure where I was supposed to identify it, (i.e., in the fragment_signup.xml, in its own menu, somewhere else.) right now the id for fragment_signup, is `android:id="@+id/nav_signup"`

Body:
I'm not sure I understand the question
Navigation.findNavController(view).navigate(R.id.nav_signup); - it should do the navigation and R.id.nav_signup should be destination or action. I'm not sure what R.id.nav_signup is atm. If destination then probably it should be fragment id.

Here's doc about navigations https://developer.android.com/guide/navigation/navigation-navigate#java

And here is Google course about navigation between fragments https://developer.android.com/codelabs/basic-android-kotlin-training-fragments-navigation-component#6 (This guide is in Kotlin but that's just a syntax difference, hopefully still can be useful)

And the final code of this is here https://github.com/google-developer-training/android-basics-kotlin-words-app (it uses navigation/nav_graph.xml to define navigations between fragments)

And for example in src/main/java/com/example/wordsapp/LetterAdapter.kt has navigation to different fragment.

       holder.button.setOnClickListener {
            // LetterListFragmentDirections is defined in nav_graph.xml
            val action = LetterListFragmentDirections.actionLetterListFragmentToWordListFragment(letter = holder.button.text.toString())
            // Navigate using that action
            holder.view.findNavController().navigate(action)
        }

I haven't used fragments a long time, but I hope this will be helpful :)


来源: stackexchange

问:
convert HQL query to criteria api
I'm wondering if is possible to convert this HQL query into a criteria api query.

```<code>select s1
from Student
where
     (
        select max(s2.Score)
        from Student
        where s1.Id = s2.Id
     )
      = 10
</code>```

(selects the students that have their max score value equal to 10)

I don't know if I could use a detached criteria because of the 's1.Id = s2.Is' condition

Thanx for anyone who can help me

答:
her goes

```<code>var subquery = Session.CreateCriteria<Student>()
    .Add(Restrictions.EqProperty("Id", "s1.Id"))
    .SetProjection(Projections.Max("Score"));

var results = Session.CreateCriteria<Student>("s1")
    .Add(Subqueries.Eq(10, subquery))
    .List<Patient>();
</code>```

but i'm not sure if the original query is correct because the subquery should always return 1 row if Id is the primary key

ContentLicense: CC BY-SA 2.5

Title: convert HQL query to criteria api

Body:
I'm wondering if is possible to convert this HQL query into a criteria api query.

select s1
from Student
where
     (
        select max(s2.Score)
        from Student
        where s1.Id = s2.Id
     )
      = 10

(selects the students that have their max score value equal to 10)

I don't know if I could use a detached criteria because of the 's1.Id = s2.Is' condition

Thanx for anyone who can help me

Body:
her goes

var subquery = Session.CreateCriteria<Student>()
    .Add(Restrictions.EqProperty("Id", "s1.Id"))
    .SetProjection(Projections.Max("Score"));

var results = Session.CreateCriteria<Student>("s1")
    .Add(Subqueries.Eq(10, subquery))
    .List<Patient>();

but i'm not sure if the original query is correct because the subquery should always return 1 row if Id is the primary key

ContentLicense: CC BY-SA 3.0


问:
How to avoid for loop in spark?
I've a use case as below in PySpark:

```<code>df.show()
emp_no dept_no emp_name emp_address location
 1.     10.     ABC.     AAA.         X
 2.     20.     DEF.     CCC.         Y
 3.     20.     GHI.     DDD.         Z
 4.     10.     JKL.     EEE.         Y
</code>```

And, I've below 2 lists:

```<code>dept_list = [10, 20]
location_list = ['Y', 'Z']
</code>```

now i'm iterating lists for data-frame and doing joining as below:

```<code>lst = []
for a, b in zip(dept_list, location_list):
  df1 = df.where(col('dept_no' == a))
  df2 = df.where(col('location' == b))
  join_conditions = [df1.dept_no==df2.dept_no, df1.emp_address==df2.emp_address]
  result_df = df1.join(df2, join_conditions, how="inner").select(df1.emp_id, df1.emp_name)
  lst.append(result_df)
</code>```

Finally doing union of all as below:

```<code>from functools import reduce
from pyspark.sql import DataFrame
final_df = reduce(DataFrame.union, lst)
</code>```

Now final result:

```<code>final_df.show()
emp_no emp_name
  4.   JKL
  3.   GHI
</code>```

How can I avoid this FOR loop ?

EDIT1:
if we have similar lists for same column [i.e., location] then how to use ?
For example:

```<code>location_list_1 = ['X', 'Y']
location_list_2 = ['Z', 'Z'] # value can be repeated here, but len(location_list_1)=len(location_list_2)

lst = []
for a, b in zip(location_list_1, location_list_2):
  df1 = df.where(col('location' == a))
  df2 = df.where(col('location' == b))
  join_conditions = [df1.dept_no==df2.dept_no, df1.emp_address==df2.emp_address]
  result_df = df1.join(df2, join_conditions, how="fullouter").select(nvl(df1.emp_id, df2.emp_id), nvl(df1.emp_name, df2.emp_name))
  lst.append(result_df)
</code>```

And output should be:

```<code>emp_no emp_name
  1.   ABC  # from 1st iteration in FOR loop [for location 'X' & 'Z']
  3.   GHI  # from 1st iteration in FOR loop [for location 'X' & 'Z']
  2.   DEF  # from 2nd iteration in FOR loop [for location 'Y' & 'Z']
  4.   JKL  # from 2nd iteration in FOR loop [for location 'Y' & 'Z']
  3.   GHI  # from 2nd iteration in FOR loop [for location 'Y' & 'Z']

# Here, 3-GHI should come twice.
</code>```

Here similarly, how to avoid FOR loop ?

答:
I think this should work:

from functools import reduce
from operator import __or__
from pyspark.sql import functions as f

final_df = df.alias("a").join(
  df.alias("b"),
  on=reduce(
    __or__,
    [
      (f.col("a.dept_no") == f.lit(a)) & (f.col("b.location") == f.lit(b))
      for a, b in zip(dept_list, location_list)
    ]
  ) & (
    f.col("a.dept_no") == f.col("b.dept_no")
  ) & (
    f.col("a.emp_address") == f.col("b.emp_address")
  )
).select("a.emp_id", "b.emp_name")
```

ContentLicense: CC BY-SA 4.0

Title: How to avoid for loop in spark?

Body:
I've a use case as below in PySpark:

df.show()
emp_no dept_no emp_name emp_address location
 1.     10.     ABC.     AAA.         X
 2.     20.     DEF.     CCC.         Y
 3.     20.     GHI.     DDD.         Z
 4.     10.     JKL.     EEE.         Y

And, I've below 2 lists:

dept_list = [10, 20]
location_list = ['Y', 'Z']

now i'm iterating lists for data-frame and doing joining as below:

lst = []
for a, b in zip(dept_list, location_list):
  df1 = df.where(col('dept_no' == a))
  df2 = df.where(col('location' == b))
  join_conditions = [df1.dept_no==df2.dept_no, df1.emp_address==df2.emp_address]
  result_df = df1.join(df2, join_conditions, how="inner").select(df1.emp_id, df1.emp_name)
  lst.append(result_df)

Finally doing union of all as below:

from functools import reduce
from pyspark.sql import DataFrame
final_df = reduce(DataFrame.union, lst)

Now final result:

final_df.show()
emp_no emp_name
  4.   JKL
  3.   GHI

How can I avoid this FOR loop ?

EDIT1:
if we have similar lists for same column [i.e., location] then how to use ?
For example:

location_list_1 = ['X', 'Y']
location_list_2 = ['Z', 'Z'] # value can be repeated here, but len(location_list_1)=len(location_list_2)

lst = []
for a, b in zip(location_list_1, location_list_2):
  df1 = df.where(col('location' == a))
  df2 = df.where(col('location' == b))
  join_conditions = [df1.dept_no==df2.dept_no, df1.emp_address==df2.emp_address]
  result_df = df1.join(df2, join_conditions, how="fullouter").select(nvl(df1.emp_id, df2.emp_id), nvl(df1.emp_name, df2.emp_name))
  lst.append(result_df)

And output should be:

emp_no emp_name
  1.   ABC  # from 1st iteration in FOR loop [for location 'X' & 'Z']
  3.   GHI  # from 1st iteration in FOR loop [for location 'X' & 'Z']
  2.   DEF  # from 2nd iteration in FOR loop [for location 'Y' & 'Z']
  4.   JKL  # from 2nd iteration in FOR loop [for location 'Y' & 'Z']
  3.   GHI  # from 2nd iteration in FOR loop [for location 'Y' & 'Z']

# Here, 3-GHI should come twice.

Here similarly, how to avoid FOR loop ?


问:
Make Visual Studio understand CamelCase when hitting Ctrl and cursor keys
Is there a way that I can configure Visual Studio 2008 to understand CamelCase?  Specifically, I'd like to be able to get Ctrl + right or left cursor to take me to a subsection of a variable or type name.

i.e., if my cursor was at the start of this line:

LongNamedExampleClass longNamed = new LongNamedExampleClass();
```

and I hit Ctrl + right, I'd like to jump to "Named" in the class name, rather than the start of the variable name.  If I hit it again, I'd like to go to "Example".  I hope that makes sense.

I used this navigational feature in Eclipse quite a lot, and find it difficult to unlearn something so ingrained.

答:
For those using Visual Studio 2022.

Ctrl +Alt + right or left will jump to sub words(camel case navigation).

Body:
Is there a way that I can configure Visual Studio 2008 to understand CamelCase?  Specifically, I'd like to be able to get Ctrl + right or left cursor to take me to a subsection of a variable or type name.

i.e., if my cursor was at the start of this line:

LongNamedExampleClass longNamed = new LongNamedExampleClass();

and I hit Ctrl + right, I'd like to jump to "Named" in the class name, rather than the start of the variable name.  If I hit it again, I'd like to go to "Example".  I hope that makes sense.

I used this navigational feature in Eclipse quite a lot, and find it difficult to unlearn something so ingrained.


问:
How to replace the text with the previous text in the label?
I am trying to write a code to have a label, and a button, and whenever we click on the button the defined text just replaces with the previous text in the Label. Right now it adds it the previous text.

```<code>from tkinter import *

root = Tk()
root.geometry("400x400")

my_label = Label(text="Hello").pack()

def test():
    my_label = Label(text="Bye").pack()

my_button = Button(root, text="Open a file", command=test).pack()

root.mainloop()
</code>```

I saw that people using config to do that. But I don't understand what is the problem with my code.

```<code>from tkinter import *

root = Tk()
root.geometry("400x400")

global my_label
my_label = Label(text="Hello").pack()

def test():
    my_label.config(text="Bye")

my_button = Button(root, text="Open a file", command=test).pack()

root.mainloop()
</code>```

It gives me this error:

```<code>AttributeError: 'NoneType' object has no attribute 'config'
</code>```

答:
You don't use global at the global level.  You should remove that.

The PROBLEM is that the .pack() method returns None.  Tkinter is a hopelessly antiquated relic of software days gone by, and does not use good object practices.  You need

```<code>my_label = Label(text="hello")
my_label.pack()
</code>```

Body:
I am trying to write a code to have a label, and a button, and whenever we click on the button the defined text just replaces with the previous text in the Label. Right now it adds it the previous text.

from tkinter import *

root = Tk()
root.geometry("400x400")

my_label = Label(text="Hello").pack()

def test():
    my_label = Label(text="Bye").pack()

my_button = Button(root, text="Open a file", command=test).pack()

root.mainloop()

I saw that people using config to do that. But I don't understand what is the problem with my code.

from tkinter import *

root = Tk()
root.geometry("400x400")

global my_label
my_label = Label(text="Hello").pack()

def test():
    my_label.config(text="Bye")

my_button = Button(root, text="Open a file", command=test).pack()

root.mainloop()

It gives me this error:

AttributeError: 'NoneType' object has no attribute 'config'

Body:
You don't use global at the global level.  You should remove that.

The PROBLEM is that the .pack() method returns None.  Tkinter is a hopelessly antiquated relic of software days gone by, and does not use good object practices.  You need

my_label = Label(text="hello")
my_label.pack()


问:
How to send data to port in binary format
I am newbie in Low level programming. In my project(C#.NET) we are using EDBS protocol(7 bit format) for communication and i have the data in bit format to send like 00101010 so we would please guide me how to send these to port.I know that the serial port class accepts data in binary format but dont know how convert the bit format into byte .

Thanks in advance

prem

答: .Net only receives data in byte (the smallest unit), you can use BitConverter to convert various value type to byte of array and vice verse.</p>

OwnerDisplayName: prem

LastEditorDisplayName: Brian Campbell

OwnerDisplayName: Akash Kava


问:
cannot create python virtual environment (exit status 101)
When I try to generate a virtual environment, the following error pops up on Windows 11:

```<code>PS C:\programming\tmp> python -m venv venv
Error: Command '['C:\\programming\\tmp\\venv\\Scripts\\python.exe', '-Im', 'ensurepip', '--upgrade', '--default-pip']' returned non-zero exit status 101.
</code>```

I have uninstalled all versions of python I did reinstall python 3.10.1 but the error remains.
Based on this post I did try to install it for all users with no success.
I also added python to PATH.

My guess is that it is related to pip, since python -m venv --without-pip venv_no_pip works (but I need pip thus this is no good solution).

I would appreciate any hint on what to do since I'm out of ideas.

答: I encountered the same problem (well, all users install did work on my PC) and found a solution. If your python is installed on a path with a space, check out my self-answer</p>

Body:
When I try to generate a virtual environment, the following error pops up on Windows 11:

PS C:\programming\tmp> python -m venv venv
Error: Command '['C:\\programming\\tmp\\venv\\Scripts\\python.exe', '-Im', 'ensurepip', '--upgrade', '--default-pip']' returned non-zero exit status 101.

I have uninstalled all versions of python I did reinstall python 3.10.1 but the error remains.
Based on this post I did try to install it for all users with no success.
I also added python to PATH.

My guess is that it is related to pip, since python -m venv --without-pip venv_no_pip works (but I need pip thus this is no good solution).

I would appreciate any hint on what to do since I'm out of ideas.


问:
How to clear cache ssas tabular
I had some problem with ssas model. becous the deployed model did not show the changes. I wana clear chache hope to solve the issue. But I do not know how to clear chache.</p>

答:
To clear cache on Tabular (and MultiDimensional), you can run this XMLA command:

```<code><ClearCache xmlns="http://schemas.microsoft.com/analysisservices/2003/engine">
    <Object>
        <DatabaseID>MGROI_dev</DatabaseID>
    </Object>
</ClearCache>
</code>```

from https://learn.microsoft.com/en-us/analysis-services/instances/clear-the-analysis-services-caches?view=asallproducts-allversions

Title: How to clear cache ssas tabular

Body:
To clear cache on Tabular (and MultiDimensional), you can run this XMLA command:

<ClearCache xmlns="http://schemas.microsoft.com/analysisservices/2003/engine">
    <Object>
        <DatabaseID>MGROI_dev</DatabaseID>
    </Object>
</ClearCache>

from https://learn.microsoft.com/en-us/analysis-services/instances/clear-the-analysis-services-caches?view=asallproducts-allversions


问:
Not able to install robot framework on Jython
I'm new to robot framework with appium using Eclipse with RED editor

I'm trying to install robot framework on jython using this command

C:\Users\Uday>jython -m pip install robotframework

But I'm getting below error

[33mDEPRECATION: A future version of pip will drop support for Python 2.7.←[0m

Collecting robotframework

←[31m  ERROR: Certificate did not match expected hostname: pypi.org. Certificate: {'notAfter': 'Nov 23 18:41:10 2022 GMT', 'subject': ((('commonName', 'www.python.org'),),), 'subjectAltName': (('DNS', 'www.python.org'), ('DNS', '*.python.org'), ('DNS', 'docs.python.org'), ('DNS', 'downloads.python.org'), ('DNS', 'pypi.python.org'))}←[0m

←[33m  WARNING: Retrying (Retry(total=4, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError(CertificateError("hostname 'pypi.org' doesn't match either of 'www.python.org', '*.python.org', 'docs.python.org', 'downloads.python.org', 'pypi.python.org'",),)': /simple/robotframework/←[0m

←[31m  ERROR: Certificate did not match expected hostname: pypi.org. Certificate: {'notAfter': 'Nov 23 18:41:10 2022 GMT', 'subject': ((('commonName', 'www.python.org'),),), 'subjectAltName': (('DNS', 'www.python.org'), ('DNS', '*.python.org'), ('DNS', 'docs.python.org'), ('DNS', 'downloads.python.org'), ('DNS', 'pypi.python.org'))}←[0m

←[33m  WARNING: Retrying (Retry(total=3, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError(CertificateError("hostname 'pypi.org' doesn't match either of 'www.python.org', '*.python.org', 'docs.python.org', 'downloads.python.org', 'pypi.python.org'",),)': /simple/robotframework/←[0m

←[31m  ERROR: Certificate did not match expected hostname: pypi.org. Certificate: {'notAfter': 'Nov 23 18:41:10 2022 GMT', 'subject': ((('commonName', 'www.python.org'),),), 'subjectAltName': (('DNS', 'www.python.org'), ('DNS', '*.python.org'), ('DNS', 'docs.python.org'), ('DNS', 'downloads.python.org'), ('DNS', 'pypi.python.org'))}←[0m

←[33m  WARNING: Retrying (Retry(total=2, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError(CertificateError("hostname 'pypi.org' doesn't match either of 'www.python.org', '*.python.org', 'docs.python.org', 'downloads.python.org', 'pypi.python.org'",),)': /simple/robotframework/←[0m

←[31m  ERROR: Certificate did not match expected hostname: pypi.org. Certificate: {'notAfter': 'Nov 23 18:41:10 2022 GMT', 'subject': ((('commonName', 'www.python.org'),),), 'subjectAltName': (('DNS', 'www.python.org'), ('DNS', '*.python.org'), ('DNS', 'docs.python.org'), ('DNS', 'downloads.python.org'), ('DNS', 'pypi.python.org'))}←[0m

←[33m  WARNING: Retrying (Retry(total=1, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError(CertificateError("hostname 'pypi.org' doesn't match either of 'www.python.org', '*.python.org', 'docs.python.org', 'downloads.python.org', 'pypi.python.org'",),)': /simple/robotframework/←[0m

←[31m  ERROR: Certificate did not match expected hostname: pypi.org. Certificate: {'notAfter': 'Nov 23 18:41:10 2022 GMT', 'subject': ((('commonName', 'www.python.org'),),), 'subjectAltName': (('DNS', 'www.python.org'), ('DNS', '*.python.org'), ('DNS', 'docs.python.org'), ('DNS', 'downloads.python.org'), ('DNS', 'pypi.python.org'))}←[0m

←[33m  WARNING: Retrying (Retry(total=0, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError(CertificateError("hostname 'pypi.org' doesn't match either of 'www.python.org', '*.python.org', 'docs.python.org', 'downloads.python.org', 'pypi.python.org'",),)': /simple/robotframework/←[0m

←[31m  ERROR: Certificate did not match expected hostname: pypi.org. Certificate: {'notAfter': 'Nov 23 18:41:10 2022 GMT', 'subject': ((('commonName', 'www.python.org'),),), 'subjectAltName': (('DNS', 'www.python.org'), ('DNS', '*.python.org'), ('DNS', 'docs.python.org'), ('DNS', 'downloads.python.org'), ('DNS', 'pypi.python.org'))}←[0m

Could not fetch URL https://pypi.org/simple/robotframework/: There was a problem confirming the ssl certificate: HTTPSConnectionPool(host='pypi.org', port=443): Max retries exceeded with url: /simple/robotframework/ (Caused by SSLError(CertificateError("hostname 'pypi.org' doesn't match either of 'www.python.org', '*.python.org', 'docs.python.org', 'downloads.python.org', 'pypi.python.org'",),)) - skipping

←[31m  ERROR: Could not find a version that satisfies the requirement robotframework (from versions: none)←[0m

←[31mERROR: No matching distribution found for robotframework←[0m

←[31mERROR: Certificate did not match expected hostname: pypi.org. Certificate: {'notAfter': 'Nov 23 18:41:10 2022 GMT', 'subject': ((('commonName', 'www.python.org'),),), 'subjectAltName': (('DNS', 'www.python.org'), ('DNS', '*.python.org'), ('DNS', 'docs.python.org'), ('DNS', 'downloads.python.org'), ('DNS', 'pypi.python.org'))}←[0m

Could not fetch URL https://pypi.org/simple/pip/: There was a problem confirming the ssl certificate: HTTPSConnectionPool(host='pypi.org', port=443): Max retries exceeded with url: /simple/pip/ (Caused by SSLError(CertificateError("hostname 'pypi.org' doesn't match either of 'www.python.org', '*.python.org', 'docs.python.org', 'downloads.python.org', 'pypi.python.org'",),)) - skipping

Can anyone please help here

答:
I have faced that same issue, and one way around it is to install directly from the GitHub release.

For robotframework, it appears that version 4.1.2 is the last release that supports [J/P]ython 2.7, so you would install it by running the following command:

jython -m pip install https://github.com/robotframework/robotframework/archive/refs/tags/v4.1.2.zip
```

And that should do it.

Body:
I have faced that same issue, and one way around it is to install directly from the GitHub release.

For robotframework, it appears that version 4.1.2 is the last release that supports [J/P]ython 2.7, so you would install it by running the following command:

jython -m pip install https://github.com/robotframework/robotframework/archive/refs/tags/v4.1.2.zip

And that should do it.


问:
Creational Design Pattern for this Problem?
I have the following problem illustrated by the pseudo code below (might not make a whole lot of sense):

```<code>class Form {
    boolean loggedOn = false;
    String id = null;
    ...get/set shared methods
}

class SearchFormA extends Form{
    String name = null;
    String email = null;

    ...get/set methods
}

class SearchFormB extends Form{
    String age = null;
    String gender = null;

    ...get/set methods
}

class Search {
    public Search(HttpServletRequest request){
            String searchMode = (String) request.getSearchMode();
        if("0".equals(searchMode)){
            SearchFormA formA = new SearchFormA();
            formA.setName((String)request.getParameter("name"));
            formA.setId((String)request.getParameter("id"));
            ...populate form
            request.getSession().setAttribute("formA",formA);
        }

        if("1".equals(searchMode)){
            SearchFormB formB = new SearchFormB();
            formB.setAge((String)request.getParameter("age"));
            formB.setId((String)request.getParameter("id"));
            ...populate form
            request.getSession().setAttribute("formB",formB);
        }

        ...rest of code
    }
}
</code>```

What i've done is using reflection, but is there any other way to do it at compile time?
I've also tried Factory method, but the classes SearchFormA and SearchFormB does not have much in common.

EDIT: ok basically, in this case i have 4-5 searchModes, each searchMode has a different form. Between these forms they share certain similar fields. In future i might have to add 10 searchModes and it's going to be repeating alot of populating of the same fields.

答:
What you're obviously trying to avoid is that in the Search method you'd have to keep appending to the if structure (spaghetti code).

I feel like the situation you're describing isn't all that different from the one I wrote this answer for. That would mean that Strategy and Template (and others) could come in handy here.

Cheers,
Wim

Body:
I have the following problem illustrated by the pseudo code below (might not make a whole lot of sense):

class Form {
    boolean loggedOn = false;
    String id = null;
    ...get/set shared methods
}

class SearchFormA extends Form{
    String name = null;
    String email = null;

    ...get/set methods
}

class SearchFormB extends Form{
    String age = null;
    String gender = null;

    ...get/set methods
}

class Search {
    public Search(HttpServletRequest request){
            String searchMode = (String) request.getSearchMode();
        if("0".equals(searchMode)){
            SearchFormA formA = new SearchFormA();
            formA.setName((String)request.getParameter("name"));
            formA.setId((String)request.getParameter("id"));
            ...populate form
            request.getSession().setAttribute("formA",formA);
        }

        if("1".equals(searchMode)){
            SearchFormB formB = new SearchFormB();
            formB.setAge((String)request.getParameter("age"));
            formB.setId((String)request.getParameter("id"));
            ...populate form
            request.getSession().setAttribute("formB",formB);
        }

        ...rest of code
    }
}

What i've done is using reflection, but is there any other way to do it at compile time?
I've also tried Factory method, but the classes SearchFormA and SearchFormB does not have much in common.

EDIT: ok basically, in this case i have 4-5 searchModes, each searchMode has a different form. Between these forms they share certain similar fields. In future i might have to add 10 searchModes and it's going to be repeating alot of populating of the same fields.


问:
Disable query caching in SQLAlchemy
I am trying to generate dynamic sql queries based on certain conditions in SQLAlchemy. I have a model that is gets queried constantly based on different conditions

The code goes like this:

condition 1:

```<code>allowed_names = ['a', 'b', 'c']
join_condition = f'and_(Parent.parent_id==Child.parent_id, Child.name.in_({allowed_names}))'
Parent.children = relationship('Child', primaryjoin=join_condition, lazy='selectin')
</code>```

condition 2:

```<code>allowed_names = ['x', 'y', 'z']
join_condition = f'and_(Parent.parent_id==Child.parent_id, Child.name.in_({allowed_names}))'
Parent.children = relationship('Child', primaryjoin=join_condition, lazy='selectin')
</code>```

I get results of the query the following way:

```<code>res = Parent.filter(Parent.parent_id.in_([1, 2, 3])).limit(100).offset(1).all()
</code>```

If I run the query based on condition 1 first and run the query based on condition 2 again without stopping the program, it returns results based on query 1 since it ran first.
After printing out the sql query that gets executed, I figured out that it only runs the condition that was executed first.

Does SQLALchemy cache the string query?
I noticed the old value of allowed_names in the filter condition in the query

```<code>[cached since 7.236s ago] {'name_1_1': 'a', 'name_1_2': 'b', 'name_1_3': 'c'}
</code>```

Am I missing something here, or is it a SQLAlchemy bug??

答:
I don't think relationship is meant to be used dynamically like this.  Sqlalchemy probably extracts the information just the first time the class is loaded.  So when you dynamically change the relationship property later nothing changes.

Also lazy="selectin" actually eager loads this information which is more confusing if you are trying to dynamically change it.

I think you could probably just use "selectin" to load all the children for each parent and then just filter those children with python if there are not that many of them.  Then you don't have to manage multiple relationships.

I guess it depends on if there are a lot of children per parent or not.

Single relationship filtered with python

class Parent(Base):
    __tablename__ = "parents"
    id = Column(Integer, primary_key=True, index=True)
    @property
    def abc_children(self):
        return [child for child in self.children of child.name in ["a" , "b", "c"]]

    @property
    def xyz_children(self):
        return [child for child in self.children of child.name in ["x" , "y", "z"]]

    children = relationship(Child, primaryjoin = "Parent.id==Child.parent_id", backref="parent", lazy="selectin")

# Then this would be accessed with
parent.xyz_children
# or
parent.abc_children

```
<h3>Multiple relationships loaded with <code>.options()</code></h3>
<p>Otherwise you could load a <code>viewonly=True</code> property on demand using options but that is kind of messy.</p>
<pre class="lang-py prettyprint-override"><code>
class Child(Base):
    __tablename__ = "childs"
    id = Column(Integer, primary_key=True, index=True)
    parent_id = Column(Integer, ForeignKey('parents.id'), nullable=True)
    name = Column(String)

class Parent(Base):
    __tablename__ = "parents"
    id = Column(Integer, primary_key=True, index=True)
    abc_names = ["a" , "b", "c"]
    abc_children = relationship(Child, primaryjoin = f"and_(Parent.id==Child.parent_id, Child.name.in_({abc_names}))", viewonly=True)
    xyz_names = ["x" , "y", "z"]
    xyz_children = relationship(Child, primaryjoin = f"and_(Parent.id==Child.parent_id, Child.name.in_({xyz_names}))", viewonly=True)
    children = relationship(Child, primaryjoin = "Parent.id==Child.parent_id", backref="parent")

if __name__ == '__main__':

    metadata.create_all(engine)
    with Session(engine) as session:
        # Test data
        p = Parent()
        session.add(p)
        p.children.extend(Child(name=name) for name in ["a", "b", "z"])
        session.add_all(p.children)
        session.commit()

        # This loads all 3 relationships, the two filtered and the entire list, you could pick or choose.
        p = session.query(Parent).filter(Parent.id == p.id).options(
            selectinload(Parent.abc_children),
            selectinload(Parent.xyz_children),
            selectinload(Parent.children)).first()

        assert len(p.abc_children) == 2
        assert len(p.xyz_children) == 1
        assert len(p.children) == 3
</code>```

Title: Disable query caching in SQLAlchemy

Body:
I am trying to generate dynamic sql queries based on certain conditions in SQLAlchemy. I have a model that is gets queried constantly based on different conditions

The code goes like this:

condition 1:

allowed_names = ['a', 'b', 'c']
join_condition = f'and_(Parent.parent_id==Child.parent_id, Child.name.in_({allowed_names}))'
Parent.children = relationship('Child', primaryjoin=join_condition, lazy='selectin')

condition 2:

allowed_names = ['x', 'y', 'z']
join_condition = f'and_(Parent.parent_id==Child.parent_id, Child.name.in_({allowed_names}))'
Parent.children = relationship('Child', primaryjoin=join_condition, lazy='selectin')

I get results of the query the following way:

res = Parent.filter(Parent.parent_id.in_([1, 2, 3])).limit(100).offset(1).all()

If I run the query based on condition 1 first and run the query based on condition 2 again without stopping the program, it returns results based on query 1 since it ran first.
After printing out the sql query that gets executed, I figured out that it only runs the condition that was executed first.

Does SQLALchemy cache the string query?
I noticed the old value of allowed_names in the filter condition in the query

[cached since 7.236s ago] {'name_1_1': 'a', 'name_1_2': 'b', 'name_1_3': 'c'}

Am I missing something here, or is it a SQLAlchemy bug??

Body:
I don't think relationship is meant to be used dynamically like this.  Sqlalchemy probably extracts the information just the first time the class is loaded.  So when you dynamically change the relationship property later nothing changes.

Also lazy="selectin" actually eager loads this information which is more confusing if you are trying to dynamically change it.

I think you could probably just use "selectin" to load all the children for each parent and then just filter those children with python if there are not that many of them.  Then you don't have to manage multiple relationships.

I guess it depends on if there are a lot of children per parent or not.

Single relationship filtered with python

class Parent(Base):
    __tablename__ = "parents"
    id = Column(Integer, primary_key=True, index=True)
    @property
    def abc_children(self):
        return [child for child in self.children of child.name in ["a" , "b", "c"]]

    @property
    def xyz_children(self):
        return [child for child in self.children of child.name in ["x" , "y", "z"]]

    children = relationship(Child, primaryjoin = "Parent.id==Child.parent_id", backref="parent", lazy="selectin")

# Then this would be accessed with
parent.xyz_children
# or
parent.abc_children

Multiple relationships loaded with .options()

Otherwise you could load a viewonly=True property on demand using options but that is kind of messy.

class Child(Base):
    __tablename__ = "childs"
    id = Column(Integer, primary_key=True, index=True)
    parent_id = Column(Integer, ForeignKey('parents.id'), nullable=True)
    name = Column(String)

class Parent(Base):
    __tablename__ = "parents"
    id = Column(Integer, primary_key=True, index=True)
    abc_names = ["a" , "b", "c"]
    abc_children = relationship(Child, primaryjoin = f"and_(Parent.id==Child.parent_id, Child.name.in_({abc_names}))", viewonly=True)
    xyz_names = ["x" , "y", "z"]
    xyz_children = relationship(Child, primaryjoin = f"and_(Parent.id==Child.parent_id, Child.name.in_({xyz_names}))", viewonly=True)
    children = relationship(Child, primaryjoin = "Parent.id==Child.parent_id", backref="parent")

if __name__ == '__main__':

    metadata.create_all(engine)
    with Session(engine) as session:
        # Test data
        p = Parent()
        session.add(p)
        p.children.extend(Child(name=name) for name in ["a", "b", "z"])
        session.add_all(p.children)
        session.commit()

        # This loads all 3 relationships, the two filtered and the entire list, you could pick or choose.
        p = session.query(Parent).filter(Parent.id == p.id).options(
            selectinload(Parent.abc_children),
            selectinload(Parent.xyz_children),
            selectinload(Parent.children)).first()

        assert len(p.abc_children) == 2
        assert len(p.xyz_children) == 1
        assert len(p.children) == 3


问:
TypeError: ‘type’ object is not subscriptable
I’m trying to get the function below to run. However I’m getting an error saying</p>
```<code>TypeError: ‘type’ object is not subscriptable

def dist(loc1: tuple[float], loc2: tuple[float]) -> float:
    dx = loc1[0] - loc2[0]
    dy = loc1[1] - loc2[1]
    return (dx**2 + dy**2)**0.5
</code>```

答:
You need to use typing.Tuple, not the tuple class.

```<code>from typing import Tuple

def dist(loc1: Tuple[float], loc2: Tuple[float]) -> float:
    dx = loc1[0] - loc2[0]
    dy = loc1[1] - loc2[1]
    return (dx**2 + dy**2)**0.5
dist((1,2),(2,1)) # output 1.4142135623730951
</code>```

Body:
I’m trying to get the function below to run. However I’m getting an error saying

TypeError: ‘type’ object is not subscriptable

def dist(loc1: tuple[float], loc2: tuple[float]) -> float:
    dx = loc1[0] - loc2[0]
    dy = loc1[1] - loc2[1]
    return (dx**2 + dy**2)**0.5

Body:
You need to use typing.Tuple, not the tuple class.

from typing import Tuple

def dist(loc1: Tuple[float], loc2: Tuple[float]) -> float:
    dx = loc1[0] - loc2[0]
    dy = loc1[1] - loc2[1]
    return (dx**2 + dy**2)**0.5
dist((1,2),(2,1)) # output 1.4142135623730951


问:
GitHub Authentication Issue - git 2.6.2 - Mac OS X Yosemite 10.10.5 - HelloWorld.md Markdown File
GitHub Authentication Issue when creating HelloWorld.md markdown file and using Git to push file to repository on GitHub
(for The Data Scientist's Toolbox Project on Coursera)

Git Version 2.6.2
_  Mac OS X Yosemite Version 10.10.5

Three images show steps followed up until issue.

Step # 1 - Image link shown in first comment below

Step # 2

Step # 3

Step # 3 Image shows GitHub authentication issue in Terminal. Will accept GitHub username, but will not accept password... it does not allow ANY typing ability/access at all to answer password question prompt.

How do I gain access?

Authentication issue forums solutions have not worked so far.

Help much appreciated!

答:
Would you still have the issue nowadays (2022), you would need as a password a PAT (Personal Access Token).

Token authentication is required since Aug. 2021.

Using a credential helper (osxkeychain) to cache that password /token will help you avoid entering said token on every push.


问:
SQL timeouts in ASP.NET after server migration
We have several ASP.NET WebForm sites running on IIS. We switched hosting providers and migrated all of the sites and databases.
After the migration, we are getting timeouts in several places in several sites after 30 seconds. Some are LINQ queries, some are MS Reports, some stored procs.

The code and web.configs were copied directly, so there should be no difference except for the SQL and IIS versions and configurations.
We  went from SQL Server 2014 to SQL Server 2019 now running on Windows Server 2019.
IIS server is also on a 2019 server.

In SQL Server, 'Allow remote connections' is checked with a remote query timeout of 600 seconds.

I have added 'Connection Timeout=120' to the connection string in the web.config but it is still timing out after 30 seconds.

Here is an example of one of them coming from a report:

An error has occurred during report processing.
Exception has been thrown by the target of an invocation.
Execution Timeout Expired. The timeout period elapsed prior to completion of the operation or the server is not responding.
The wait operation timed out

Some of these sites are pretty old and using older methods for connecting to database. I have seen some posts about adding a timeout to the SqlCommand object, but most places we have do not use one. Some code is within a custom data layer and I don't have access to all of the source code to try adding the timeout value.

Any ideas of where this timeout may be coming from?

Any direction would be appreciated.

答:
Any ideas of where this timeout may be coming from?

These are client-side timeouts caused by queries running longer than the SqlCommand.CommandTimeout, which defaults to 30sec.

The recommended upgrade process is to initially leave the databases at their original compatibility level after upgrade to minimize the risk of plan reversion.  Then turn on Query Store to gather a performance baseline before increasing the database compatibility level.  See

Change the Database Compatibility Level and use the Query Store


问:
2D Numpy array of dtype=int: maximize distance between identical integers
Apologies for double-posting. I haven't found a solution yet.

Former post: Conditional Numpy shuffling

Problem
I have a randomly shuffled 2D array of dtype=int and would like to maximize the distance between identical integers. This is an optimization problem.

E.g. I have:

```<code>np.array([1, 2, 2, 2],
         [3, 2, 1, 1],
         [1, 3, 3, 1],
         [1, 5, 5, 1])
</code>```

Some integers are too close to each other in 0-axis and 1-axis direction. E.g. both 5. Is there a heuristic or scipy-optimization approach that somewhat solves this problem?

Thank you in advance and kind regards

答:
I invented my own little approach making use of scipy.ndimage.distance_transform_edt and random sampling. It is far from optimal, but it does the job quite okay, depending on your aim:

```<code>import numpy as np
from scipy.ndimage import distance_transform_edt

def maximize_arr_replicate_distances(input_arr: np.array) -> np.array:

    # Assert the input array
    assert isinstance(input_arr, np.ndarray), "'input_arr' is not a Numpy array."
    assert input_arr.ndim == 2, f"'input_arr' is not an 'm x n' matrix."
    assert np.issubdtype(input_arr.dtype, np.integer), "'input_arr' is not of dtype class 'integer'."

    # Bin: Bin all unique elements into subarrays
    unique_elements = np.unique(input_arr)
    binned_uniques = [input_arr[input_arr == i].tolist() for i in unique_elements]

    # Determine a sampling order: randomly sample from subarrays without replacement and append to new list
    sampling_order = []
    while(any(binned_uniques)):
        random_index = np.random.randint(unique_elements.size)
        if binned_uniques[random_index]:
            sampling_order.append(binned_uniques[random_index].pop())

    # Distribute elements: Append elements to empty array based on sampling order and maximum possible distance between replicates
    output_arr = np.full(input_arr.shape, np.nan)
    for i in sampling_order.copy():
        if np.any(output_arr == i):
            distance_transform = distance_transform_edt(output_arr != i)
            mask = np.in1d(output_arr, unique_elements[unique_elements != i]).reshape(input_arr.shape)
            distance_transform_masked = np.ma.masked_array(distance_transform, mask=mask)
            distance_transform_max = np.argwhere(distance_transform_masked == np.amax(distance_transform_masked))
            rand_max_y, rand_max_x = distance_transform_max[np.random.randint(len(distance_transform_max))]
            output_arr[rand_max_y, rand_max_x] = i
        else:
            nan_indices = np.argwhere(np.isnan(output_arr))
            rand_nan_y, rand_nan_x = nan_indices[np.random.randint(len(nan_indices))]
            output_arr[rand_nan_y, rand_nan_x] = i

    return output_arr.astype(int)

input_arr = np.array([[1, 0, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0],
                      [1, 0, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0],
                      [1, 0, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0],
                      [1, 0, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0],
                      [1, 0, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0],
                      [1, 0, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0],
                      [1, 0, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0],
                      [1, 0, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0]])

print(maximize_arr_replicate_distances(input_arr))

# [[7 0 0 0 1 0 0 0 1 0 0 7]
#  [0 0 0 0 0 0 0 0 0 0 0 1]
#  [1 0 0 0 0 0 7 0 0 0 0 0]
#  [0 0 0 0 0 0 0 1 0 0 0 0]
#  [0 0 0 7 0 0 0 0 0 0 1 0]
#  [7 0 0 0 0 0 0 0 7 0 0 0]
#  [0 0 0 0 0 0 0 0 0 0 0 0]
#  [0 0 1 0 7 0 0 0 0 1 0 7]]
</code>```

It works okay with all kinds of inputs.

Note that the algorithm is biased towards the borders of an array. E.g. 1 will have the following frequency distribution [%] if you repeat this 10,000 times:

```<code>from typing import Callable

def evaluate(input_arr: np.array, function: Callable[[np.array], np.array], sample_index: int, iterations: int = 10_000) -> np.array:

    sum_arr = np.zeros((input_arr.shape))
    for i in range(iterations):
        sum_arr += np.where(function(input_arr) == sample_index, 1, 0)
    hit_frequencies = sum_arr / sum_arr.sum() * 100  # [%]

    return np.around(hit_frequencies, 2)

maximize_replicate_distances = evaluate(input_arr, maximize_arr_replicate_distances, 1)

print(maximize_replicate_distances)

# Frequency distribution of sample replicate '1' after distance-maximizing shuffling (n = 10,000) [%]:
# [[4.06 2.1  0.93 1.25 1.34 2.02 2.1  1.38 1.21 0.93 2.15 4.04]
#  [2.48 0.26 0.15 0.3  0.41 0.85 0.82 0.42 0.28 0.13 0.27 2.42]
#  [1.07 0.14 0.13 0.46 0.5  0.58 0.63 0.55 0.44 0.12 0.14 1.08]
#  [1.55 0.4  0.9  1.49 0.82 0.7  0.77 0.8  1.48 0.84 0.44 1.61]
#  [1.67 0.44 0.92 1.48 0.81 0.74 0.76 0.81 1.42 0.88 0.43 1.72]
#  [1.04 0.14 0.12 0.4  0.55 0.59 0.6  0.52 0.47 0.14 0.16 1.09]
#  [2.44 0.24 0.15 0.26 0.42 0.88 0.81 0.41 0.3  0.15 0.26 2.33]
#  [3.99 2.11 0.97 1.33 1.39 1.98 2.01 1.42 1.3  0.97 2.12 3.96]]
</code>```

Body:
Apologies for double-posting. I haven't found a solution yet.

Former post: Conditional Numpy shuffling

Problem
I have a randomly shuffled 2D array of dtype=int and would like to maximize the distance between identical integers. This is an optimization problem.

E.g. I have:

np.array([1, 2, 2, 2],
         [3, 2, 1, 1],
         [1, 3, 3, 1],
         [1, 5, 5, 1])

Some integers are too close to each other in 0-axis and 1-axis direction. E.g. both 5. Is there a heuristic or scipy-optimization approach that somewhat solves this problem?

Thank you in advance and kind regards

Body:
I invented my own little approach making use of scipy.ndimage.distance_transform_edt and random sampling. It is far from optimal, but it does the job quite okay, depending on your aim:

import numpy as np
from scipy.ndimage import distance_transform_edt

def maximize_arr_replicate_distances(input_arr: np.array) -> np.array:

    # Assert the input array
    assert isinstance(input_arr, np.ndarray), "'input_arr' is not a Numpy array."
    assert input_arr.ndim == 2, f"'input_arr' is not an 'm x n' matrix."
    assert np.issubdtype(input_arr.dtype, np.integer), "'input_arr' is not of dtype class 'integer'."

    # Bin: Bin all unique elements into subarrays
    unique_elements = np.unique(input_arr)
    binned_uniques = [input_arr[input_arr == i].tolist() for i in unique_elements]

    # Determine a sampling order: randomly sample from subarrays without replacement and append to new list
    sampling_order = []
    while(any(binned_uniques)):
        random_index = np.random.randint(unique_elements.size)
        if binned_uniques[random_index]:
            sampling_order.append(binned_uniques[random_index].pop())

    # Distribute elements: Append elements to empty array based on sampling order and maximum possible distance between replicates
    output_arr = np.full(input_arr.shape, np.nan)
    for i in sampling_order.copy():
        if np.any(output_arr == i):
            distance_transform = distance_transform_edt(output_arr != i)
            mask = np.in1d(output_arr, unique_elements[unique_elements != i]).reshape(input_arr.shape)
            distance_transform_masked = np.ma.masked_array(distance_transform, mask=mask)
            distance_transform_max = np.argwhere(distance_transform_masked == np.amax(distance_transform_masked))
            rand_max_y, rand_max_x = distance_transform_max[np.random.randint(len(distance_transform_max))]
            output_arr[rand_max_y, rand_max_x] = i
        else:
            nan_indices = np.argwhere(np.isnan(output_arr))
            rand_nan_y, rand_nan_x = nan_indices[np.random.randint(len(nan_indices))]
            output_arr[rand_nan_y, rand_nan_x] = i

    return output_arr.astype(int)

input_arr = np.array([[1, 0, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0],
                      [1, 0, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0],
                      [1, 0, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0],
                      [1, 0, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0],
                      [1, 0, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0],
                      [1, 0, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0],
                      [1, 0, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0],
                      [1, 0, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0]])

print(maximize_arr_replicate_distances(input_arr))

# [[7 0 0 0 1 0 0 0 1 0 0 7]
#  [0 0 0 0 0 0 0 0 0 0 0 1]
#  [1 0 0 0 0 0 7 0 0 0 0 0]
#  [0 0 0 0 0 0 0 1 0 0 0 0]
#  [0 0 0 7 0 0 0 0 0 0 1 0]
#  [7 0 0 0 0 0 0 0 7 0 0 0]
#  [0 0 0 0 0 0 0 0 0 0 0 0]
#  [0 0 1 0 7 0 0 0 0 1 0 7]]

It works okay with all kinds of inputs.

Note that the algorithm is biased towards the borders of an array. E.g. 1 will have the following frequency distribution [%] if you repeat this 10,000 times:

from typing import Callable

def evaluate(input_arr: np.array, function: Callable[[np.array], np.array], sample_index: int, iterations: int = 10_000) -> np.array:

    sum_arr = np.zeros((input_arr.shape))
    for i in range(iterations):
        sum_arr += np.where(function(input_arr) == sample_index, 1, 0)
    hit_frequencies = sum_arr / sum_arr.sum() * 100  # [%]

    return np.around(hit_frequencies, 2)

maximize_replicate_distances = evaluate(input_arr, maximize_arr_replicate_distances, 1)

print(maximize_replicate_distances)

# Frequency distribution of sample replicate '1' after distance-maximizing shuffling (n = 10,000) [%]:
# [[4.06 2.1  0.93 1.25 1.34 2.02 2.1  1.38 1.21 0.93 2.15 4.04]
#  [2.48 0.26 0.15 0.3  0.41 0.85 0.82 0.42 0.28 0.13 0.27 2.42]
#  [1.07 0.14 0.13 0.46 0.5  0.58 0.63 0.55 0.44 0.12 0.14 1.08]
#  [1.55 0.4  0.9  1.49 0.82 0.7  0.77 0.8  1.48 0.84 0.44 1.61]
#  [1.67 0.44 0.92 1.48 0.81 0.74 0.76 0.81 1.42 0.88 0.43 1.72]
#  [1.04 0.14 0.12 0.4  0.55 0.59 0.6  0.52 0.47 0.14 0.16 1.09]
#  [2.44 0.24 0.15 0.26 0.42 0.88 0.81 0.41 0.3  0.15 0.26 2.33]
#  [3.99 2.11 0.97 1.33 1.39 1.98 2.01 1.42 1.3  0.97 2.12 3.96]]


问:
Org-mode export to Latex: page break at each section and subsection
I want the pdf document to always have a page break at a section and subsection. I could add

#+latex: \clearpage

before each heading and sub-heading on org-mode. However, I think it makes my org document kind of confusing and visually dirty.

Is there a way to do it all at once, i.e., to force a page break so that all sections and subsections begin always on a new page?

I'd be glad if anyone help me.

答:
You could add

```<code>\usepackage{titlesec}
\newcommand{\sectionbreak}{\clearpage}
\newcommand{\subsectionbreak}{\clearpage}
</code>```

to your header. This has the advantage that it will automatically check if the previous unit actually had content and only add a page break in this case. This means that a section directly followed by a subsection won't be split across empty pages.

Body:
You could add

\usepackage{titlesec}
\newcommand{\sectionbreak}{\clearpage}
\newcommand{\subsectionbreak}{\clearpage}

to your header. This has the advantage that it will automatically check if the previous unit actually had content and only add a page break in this case. This means that a section directly followed by a subsection won't be split across empty pages.


问:
Dataset format for copying csv files from a sftp server to blob storage
Hi I want to copy csv files from a sftp server to blob storage using copy activity of adf without processing the content. Is there a difference using a binary dataset instead of a csv dataset for the source and sink?</p>

答:
If I understand the ask correctly, you want to copy csv files from SFTP to blob storage as-is. If that is the case, you can use binary dataset on both source and sink of your copy activity. When using Binary dataset, the service does not parse file content but treat it as-is. Where as if you use CSV file format, the service will parse file content and you will have to configuration file specs in the connection settings of your dataset.

Please note that when using Binary dataset in copy activity, you can only copy from Binary dataset to Binary dataset.


问:
PyTorch - Neural Network - Output single scalar value
Let's say we have the following neural network in PyTorch

```<code>seq_model = nn.Sequential(
nn.Linear(1, 13),
nn.Tanh(),
nn.Linear(13, 1))
</code>```

With the following input tensor

```<code>input = torch.tensor([1.0, 1.0, 5.0], dtype=torch.float32).unsqueeze(1)
</code>```

I can run forward through the net and get

```<code>seq_model(input)

tensor([[-0.0165],
        [-0.0165],
        [-0.2289]], grad_fn=<TanhBackward0>)
</code>```

Probably I also can get a single scalar value as an output, but I'm not sure how.
Thank you. I'm trying to use such an network for reinforcment learning, and use it
as an value function approximator for game board state evaluation.

答:
The first dimension of input represents the number of observations in your minibatch (3), the second dimension represents instead the number of features (1).

If you want to forward a single 3d input, the network must be modified (nn.Linear(1, 13) becomes nn.Linear(3, 13)), and you must remove unsqueeze(1) on input. Otherwise, you can merge the three outputs by using a loss to compute a single scalar from them.

Body:
Let's say we have the following neural network in PyTorch

seq_model = nn.Sequential(
nn.Linear(1, 13),
nn.Tanh(),
nn.Linear(13, 1))

With the following input tensor

input = torch.tensor([1.0, 1.0, 5.0], dtype=torch.float32).unsqueeze(1)

I can run forward through the net and get

seq_model(input)

tensor([[-0.0165],
        [-0.0165],
        [-0.2289]], grad_fn=<TanhBackward0>)

Probably I also can get a single scalar value as an output, but I'm not sure how.
Thank you. I'm trying to use such an network for reinforcment learning, and use it
as an value function approximator for game board state evaluation.


问:
Make the background of image fade to the bottom using css
I have a background image set up on my home page.

and for mobile as you see the image has a sharp cut i would like to have a background such as:

so that background has a gradient fade till bottom is there a way to achieve this with css or designing and using a background that way is the best option?

答:
Use body or container background (div)

#container{
width:100%;
height:100vh;
background: rgb(252,161,120);
background: linear-gradient(0deg, rgba(252,161,120,1) 0%, rgba(247,147,101,1) 30%, rgba(246,123,71,1) 66%, rgba(244,102,42,1) 100%);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="container"></div></code>```

Body:
Use body or container background (div)

#container{
width:100%;
height:100vh;
background: rgb(252,161,120);
background: linear-gradient(0deg, rgba(252,161,120,1) 0%, rgba(247,147,101,1) 30%, rgba(246,123,71,1) 66%, rgba(244,102,42,1) 100%);
}

<div id="container"></div>


问:
How to format time in ISO 8601 in Twilio API
I'm trying to use Twilio's messaging services to schedule a text, but I can't figure out how to format the time properly. I've pretty much copied the instructions to a T from Twilio's website, but I keep getting an invalid syntax error. Here's the line of code for the send_at variable:

```<code>send_at=datetime(2022-2-8'T'17:50:00'Z'),
</code>```

How do I format this properly so it'll run? Thanks in advance for the help.

答:
How is this timestamp being generated? Are you hard-coding it? The syntax error you're seeing is Python being unable to understand what's in between the parentheses, it doesn't seem syntactically correct.

You could simply use the isoformat() method from Python's datetime library instead to convert a regular datetime object to ISO afterwards, example:

```<code>>>> import datetime
>>> x = datetime.datetime(2022, 2, 8, 17, 50)
>>> x.isoformat()
'2022-02-08T17:50:00'
</code>```

Twilio's own docs directly suggest this pattern (see the "Send Scheduled SMS in Python" section):

```<code>message = client.messages.create(
from_=messaging_service_sid,
to='+1xxxxxxxxxx',  # ← your phone number here
body='Friendly reminder that you have an appointment with us next week.',
schedule_type='fixed',
send_at=send_when.isoformat() + 'Z',
)
</code>```

Looks like the only additional detail is appending that 'Z' at the end, which is the only difference between my first snippet and your original example. If there are different docs that you followed that you can share a link to, happy to give more specific advice.

Body:
I'm trying to use Twilio's messaging services to schedule a text, but I can't figure out how to format the time properly. I've pretty much copied the instructions to a T from Twilio's website, but I keep getting an invalid syntax error. Here's the line of code for the send_at variable:

send_at=datetime(2022-2-8'T'17:50:00'Z'),

How do I format this properly so it'll run? Thanks in advance for the help.

Body:
How is this timestamp being generated? Are you hard-coding it? The syntax error you're seeing is Python being unable to understand what's in between the parentheses, it doesn't seem syntactically correct.

You could simply use the isoformat() method from Python's datetime library instead to convert a regular datetime object to ISO afterwards, example:

>>> import datetime
>>> x = datetime.datetime(2022, 2, 8, 17, 50)
>>> x.isoformat()
'2022-02-08T17:50:00'

Twilio's own docs directly suggest this pattern (see the "Send Scheduled SMS in Python" section):

message = client.messages.create(
from_=messaging_service_sid,
to='+1xxxxxxxxxx',  # ← your phone number here
body='Friendly reminder that you have an appointment with us next week.',
schedule_type='fixed',
send_at=send_when.isoformat() + 'Z',
)

Looks like the only additional detail is appending that 'Z' at the end, which is the only difference between my first snippet and your original example. If there are different docs that you followed that you can share a link to, happy to give more specific advice.


问:
How to use play frameworks Secure module to login a user after that user has been created
I am using the "Secure" module from play framework and its mostly working great. I can login a user by posting a from the the /login route in my application.

However, when I "create/signup" a new user, I would like for that user to be automatically logged in after user creation. This, I can't seem to get working programmatically, i.e., by not having to post a form to login.

My current code for my user create action is like:

```<code>    public static void create(@Required @Email String email, @Required String password, @Required @Equals("password") String passwordConfirmation) {
        User user = new User(email);
        user.password = new Crypto().encryptAES(password);
    user.save();

        try {
        Secure.authenticate(email, password, false); // <== this is the action in secure module mapped to /login
    } catch(Throwable t) {
        t.printStackTrace();
    }
   }
</code>```

So I manually call Secure.authentication(username, password, remember) method, but this just redirects me to the login page and not my target page.

I have a feeling that a cookie or something is not being set because I am calling Secure.authenticate directly and not via a request/response, but I'm just not sure.

Any ideas?

答:
One idea could be to set the username in the session (after user signed up successfully)

```<code>session.put("username", username);
</code>```

This will make sure Secure.connected() return as expected.

if you need 'remember me',

```<code>if(remember){
     response.setCookie("rememberme", Crypto.sign(username) + "-" + username, "30d");
}
</code>```

Actually this is what Secure module does after successful authentication.
Check Secure module

Body:
I am using the "Secure" module from play framework and its mostly working great. I can login a user by posting a from the the /login route in my application.

However, when I "create/signup" a new user, I would like for that user to be automatically logged in after user creation. This, I can't seem to get working programmatically, i.e., by not having to post a form to login.

My current code for my user create action is like:

    public static void create(@Required @Email String email, @Required String password, @Required @Equals("password") String passwordConfirmation) {
        User user = new User(email);
        user.password = new Crypto().encryptAES(password);
    user.save();

        try {
        Secure.authenticate(email, password, false); // <== this is the action in secure module mapped to /login
    } catch(Throwable t) {
        t.printStackTrace();
    }
   }

So I manually call Secure.authentication(username, password, remember) method, but this just redirects me to the login page and not my target page.

I have a feeling that a cookie or something is not being set because I am calling Secure.authenticate directly and not via a request/response, but I'm just not sure.

Any ideas?

Body:
One idea could be to set the username in the session (after user signed up successfully)

session.put("username", username);

This will make sure Secure.connected() return as expected.

if you need 'remember me',

if(remember){
     response.setCookie("rememberme", Crypto.sign(username) + "-" + username, "30d");
}

Actually this is what Secure module does after successful authentication.
Check Secure module


问:
Building an Flutter iOS mobile application in AppCenter that uses Mapbox
I have followed the directions here for mapbox, and can successfully build the package locally. I have previously been able to build my app with older versions of mapbox, but this new version breaks it.

I have post-clone script below to add the .netrc file to the build computer and then run the flutter build command. It makes it to the flutter build line, and then fails on pod install. The error message doesn't indicate what URL returns 403. This is the code output from running with --verbose.

I have entered the mapbox_key into the App Center environment variables for the build and verified it is being set properly with the echo command.

Has anyone experienced this problem before and know how to fix it?

error message

```<code>                   Cloning into '/var/folders/24/8k48jl6d249_n_qfxwsl6xvm0000gn/T/d20220201-5726-105j6ub'...
                    Cloning into '/var/folders/24/8k48jl6d249_n_qfxwsl6xvm0000gn/T/d20220201-5726-cc9t4i'...
                    % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                                   Dload  Upload   Total   Spent    Left  Speed

     0     0    0     0    0     0      0      0 --:--:-- --:--:-- --:--:--     0
     0    66    0     0    0     0      0      0 --:--:-- --:--:-- --:--:--     0
                  curl: (22) The requested URL returned error: 403

[  +14 ms] "flutter ios" took 426,650ms.
[   +7 ms] Error running pod install
[        ]
           #0      throwToolExit (package:flutter_tools/src/base/common.dart:10:3)
           #1      CocoaPods._runPodInstall (package:flutter_tools/src/macos/cocoapods.dart:340:7)
           <asynchronous suspension>
           #2      CocoaPods.processPods (package:flutter_tools/src/macos/cocoapods.dart:168:7)
           <asynchronous suspension>
           #3      processPodsIfNeeded (package:flutter_tools/src/macos/cocoapod_utils.dart:44:30)
           <asynchronous suspension>
           #4      buildXcodeProject (package:flutter_tools/src/ios/mac.dart:203:3)
           <asynchronous suspension>
           #5      _BuildIOSSubCommand.runCommand (package:flutter_tools/src/commands/build_ios.dart:264:37)
           <asynchronous suspension>
           #6      FlutterCommand.run.<anonymous closure> (package:flutter_tools/src/runner/flutter_command.dart:1125:27)
           <asynchronous suspension>
           #7      AppContext.run.<anonymous closure> (package:flutter_tools/src/base/context.dart:150:19)
           <asynchronous suspension>
           #8      CommandRunner.runCommand (package:args/command_runner.dart:209:13)
           <asynchronous suspension>
           #9      FlutterCommandRunner.runCommand.<anonymous closure> (package:flutter_tools/src/runner/flutter_command_runner.dart:288:9)
           <asynchronous suspension>
           #10     AppContext.run.<anonymous closure> (package:flutter_tools/src/base/context.dart:150:19)
           <asynchronous suspension>
           #11     FlutterCommandRunner.runCommand (package:flutter_tools/src/runner/flutter_command_runner.dart:236:5)
           <asynchronous suspension>
           #12     run.<anonymous closure>.<anonymous closure> (package:flutter_tools/runner.dart:62:9)
           <asynchronous suspension>
           #13     AppContext.run.<anonymous closure> (package:flutter_tools/src/base/context.dart:150:19)
           <asynchronous suspension>
           #14     main (package:flutter_tools/executable.dart:92:3)
           <asynchronous suspension>

[   +3 ms] ensureAnalyticsSent: 1ms
[   +1 ms] Running shutdown hooks
[        ] Shutdown hooks complete
[        ] exiting with code 1
##[error]The process '/bin/bash' failed with exit code 1
##[error]Bash failed with error: The process '/bin/bash' failed with exit code 1
##[section]Finishing: Post Clone Script
##[section]Starting: Xcode build (signed)
</code>```

post-clone script

```<code>#!/usr/bin/env bash

set -e
set -x

cd ~
echo "machine api.mapbox.com
login mapbox
password $mapbox_key" > .netrc

chmod 0600 .netrc
cat .netrc

cd ./work/1/s/rider_app

git clone https://github.com/flutter/flutter.git -b 2.5.3 --depth 1
export PATH="$PATH:`pwd`/flutter/bin"

flutter doctor

flutter clean

echo "Installed flutter in `pwd`/flutter"

flutter build ios --verbose --release --no-codesign --no-sound-null-safety --dart-define=TRC_API_URL=$TRC_API_URL --dart-define=TRC_RIDER_GRPC_API_URL=$TRC_RIDER_GRPC_API_URL

</code>```

答: I needed to select at least all of these token scopes in order to fix this issue. I am not sure which additional scope fixed the problem. I only had DOWNLOADS:READ selected originally.

Body:
I have followed the directions here for mapbox, and can successfully build the package locally. I have previously been able to build my app with older versions of mapbox, but this new version breaks it.

I have post-clone script below to add the .netrc file to the build computer and then run the flutter build command. It makes it to the flutter build line, and then fails on pod install. The error message doesn't indicate what URL returns 403. This is the code output from running with --verbose.

I have entered the mapbox_key into the App Center environment variables for the build and verified it is being set properly with the echo command.

Has anyone experienced this problem before and know how to fix it?

error message

                   Cloning into '/var/folders/24/8k48jl6d249_n_qfxwsl6xvm0000gn/T/d20220201-5726-105j6ub'...
                    Cloning into '/var/folders/24/8k48jl6d249_n_qfxwsl6xvm0000gn/T/d20220201-5726-cc9t4i'...
                    % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                                   Dload  Upload   Total   Spent    Left  Speed

     0     0    0     0    0     0      0      0 --:--:-- --:--:-- --:--:--     0
     0    66    0     0    0     0      0      0 --:--:-- --:--:-- --:--:--     0
                  curl: (22) The requested URL returned error: 403

[  +14 ms] "flutter ios" took 426,650ms.
[   +7 ms] Error running pod install
[        ]
           #0      throwToolExit (package:flutter_tools/src/base/common.dart:10:3)
           #1      CocoaPods._runPodInstall (package:flutter_tools/src/macos/cocoapods.dart:340:7)
           <asynchronous suspension>
           #2      CocoaPods.processPods (package:flutter_tools/src/macos/cocoapods.dart:168:7)
           <asynchronous suspension>
           #3      processPodsIfNeeded (package:flutter_tools/src/macos/cocoapod_utils.dart:44:30)
           <asynchronous suspension>
           #4      buildXcodeProject (package:flutter_tools/src/ios/mac.dart:203:3)
           <asynchronous suspension>
           #5      _BuildIOSSubCommand.runCommand (package:flutter_tools/src/commands/build_ios.dart:264:37)
           <asynchronous suspension>
           #6      FlutterCommand.run.<anonymous closure> (package:flutter_tools/src/runner/flutter_command.dart:1125:27)
           <asynchronous suspension>
           #7      AppContext.run.<anonymous closure> (package:flutter_tools/src/base/context.dart:150:19)
           <asynchronous suspension>
           #8      CommandRunner.runCommand (package:args/command_runner.dart:209:13)
           <asynchronous suspension>
           #9      FlutterCommandRunner.runCommand.<anonymous closure> (package:flutter_tools/src/runner/flutter_command_runner.dart:288:9)
           <asynchronous suspension>
           #10     AppContext.run.<anonymous closure> (package:flutter_tools/src/base/context.dart:150:19)
           <asynchronous suspension>
           #11     FlutterCommandRunner.runCommand (package:flutter_tools/src/runner/flutter_command_runner.dart:236:5)
           <asynchronous suspension>
           #12     run.<anonymous closure>.<anonymous closure> (package:flutter_tools/runner.dart:62:9)
           <asynchronous suspension>
           #13     AppContext.run.<anonymous closure> (package:flutter_tools/src/base/context.dart:150:19)
           <asynchronous suspension>
           #14     main (package:flutter_tools/executable.dart:92:3)
           <asynchronous suspension>

[   +3 ms] ensureAnalyticsSent: 1ms
[   +1 ms] Running shutdown hooks
[        ] Shutdown hooks complete
[        ] exiting with code 1
##[error]The process '/bin/bash' failed with exit code 1
##[error]Bash failed with error: The process '/bin/bash' failed with exit code 1
##[section]Finishing: Post Clone Script
##[section]Starting: Xcode build (signed)

post-clone script

#!/usr/bin/env bash

set -e
set -x

cd ~
echo "machine api.mapbox.com
login mapbox
password $mapbox_key" > .netrc

chmod 0600 .netrc
cat .netrc

cd ./work/1/s/rider_app

git clone https://github.com/flutter/flutter.git -b 2.5.3 --depth 1
export PATH="$PATH:`pwd`/flutter/bin"

flutter doctor

flutter clean

echo "Installed flutter in `pwd`/flutter"

flutter build ios --verbose --release --no-codesign --no-sound-null-safety --dart-define=TRC_API_URL=$TRC_API_URL --dart-define=TRC_RIDER_GRPC_API_URL=$TRC_RIDER_GRPC_API_URL


问:
How can I pass the `Graphql` mutation query in cypress req and get the data back in response?
How can I pass the Graphql mutation query in cypress req and get the data back in the response ?
I am getting an error like Validation error of type FieldUndefined: Field 'mutation' in type Query undefined @CreateOrganizationTeam '

```<code>let author = 'Main Author';
let teamname = 'Green Team';
let query = `mutation CreateOrganizationTeam($input: {category: "", author:${author}, isActive: false, orgId: 10, teamName: ${teamname}}) {
  createOrganizationTeam(input: $input) {
    author
    isActive
    teamName
  }
}`;

/* Cypress test to verify the GraphQl response data  */
Then('I access the graphQL end point', () => {
  cy.request({
    method: 'POST',
    url: 'https://some-end-point/api',
    headers: {
      'content-type': 'application/json'
    },
    body: JSON.stringify({
      query,
      variables: {
        input: {
          author,
          isActive,
          teamName,
        }
      }
    })
  }).then((response)=>{
    console.log("GraphQL resp output:"+response.body.data);
  });
});
</code>```

答:
I think you need to quote the templated variables,

let query = `mutation CreateOrganizationTeam($input: {
  category: "",
  author:"${author}",       // quotes around the templated string
  isActive: false,
  orgId: 10,
  teamName: "${teamname}"   // quotes around the templated string
}) {
```
<p>In the response you may need <code>.json()</code></p>
<pre class="lang-js prettyprint-override"><code>.then(r => r.json())
.then(data => {
  console.log("GraphQL resp output:", data);
})
</code>```

Body:
How can I pass the Graphql mutation query in cypress req and get the data back in the response ?
I am getting an error like Validation error of type FieldUndefined: Field 'mutation' in type Query undefined @CreateOrganizationTeam '

let author = 'Main Author';
let teamname = 'Green Team';
let query = `mutation CreateOrganizationTeam($input: {category: "", author:${author}, isActive: false, orgId: 10, teamName: ${teamname}}) {
  createOrganizationTeam(input: $input) {
    author
    isActive
    teamName
  }
}`;

/* Cypress test to verify the GraphQl response data  */
Then('I access the graphQL end point', () => {
  cy.request({
    method: 'POST',
    url: 'https://some-end-point/api',
    headers: {
      'content-type': 'application/json'
    },
    body: JSON.stringify({
      query,
      variables: {
        input: {
          author,
          isActive,
          teamName,
        }
      }
    })
  }).then((response)=>{
    console.log("GraphQL resp output:"+response.body.data);
  });
});

Body:
I think you need to quote the templated variables,

let query = `mutation CreateOrganizationTeam($input: {
  category: "",
  author:"${author}",       // quotes around the templated string
  isActive: false,
  orgId: 10,
  teamName: "${teamname}"   // quotes around the templated string
}) {

In the response you may need .json()

.then(r => r.json())
.then(data => {
  console.log("GraphQL resp output:", data);
})


问:
How to stop all idle EC2 instances using AWS Lambda
I have been trying to detect and shutdown AWS EC2 instances that are idle (<10% CPU).

Lambda code (set with IAM role AmazonEC2FullAccess):

```<code>import boto3
def put_cpu_alarm(instance_id):
    cloudWatch   = boto3.client('cloudwatch')
    cloudWatch.put_metric_alarm(
        AlarmName          = f'CPU_ALARM_{instance_id}',
        AlarmDescription   = 'Alarm when server CPU does not exceed 10%',
        AlarmActions       = ['arn:aws:automate:us-east-1:ec2:stop'],
        MetricName         = 'CPUUtilization',
        Namespace          = 'AWS/EC2' ,
        Statistic          = 'Average',
        Dimensions         = [{'Name': 'InstanceId', 'Value': instance_id}],
        Period             = 300,
        EvaluationPeriods  = 3,
        Threshold          = 10,
        ComparisonOperator = 'LessThanOrEqualToThreshold',
        TreatMissingData   = 'notBreaching'
    )
def lambda_handler(event, context):
    instance_id = event['detail']['instance-id']
    ec2 = boto3.resource('ec2')
    instance = ec2.Instance(instance_id)
    put_cpu_alarm(instance_id)
</code>```

Event pattern in Cloudwatch Rule

```<code>{
  "source": [
    "aws.ec2"
  ],
  "detail-type": [
    "EC2 Instance State-change Notification"
  ],
  "detail": {
    "state": [
      "running"
    ]
  }
}
</code>```

Error I am getting,

```<code>[ERROR] KeyError: 'detail'
Traceback (most recent call last):
  File "/var/task/lambda_function.py", line 19, in lambda_handler
    instance_id = event['detail']['instance-id']
</code>```

Expecting result:

Detect and stop EC2 idle running instances.

答:
The event parameter passed to an AWS Lambda function contains multiple Records. You can see this by debugging the function with print(event).

Therefore, your code should loop through each Record:

def lambda_handler(event, context):
  for record in event['Records']:
    instance_id = record['detail']['instance-id']
    ...
```

Body:
I have been trying to detect and shutdown AWS EC2 instances that are idle (<10% CPU).

Lambda code (set with IAM role AmazonEC2FullAccess):

import boto3
def put_cpu_alarm(instance_id):
    cloudWatch   = boto3.client('cloudwatch')
    cloudWatch.put_metric_alarm(
        AlarmName          = f'CPU_ALARM_{instance_id}',
        AlarmDescription   = 'Alarm when server CPU does not exceed 10%',
        AlarmActions       = ['arn:aws:automate:us-east-1:ec2:stop'],
        MetricName         = 'CPUUtilization',
        Namespace          = 'AWS/EC2' ,
        Statistic          = 'Average',
        Dimensions         = [{'Name': 'InstanceId', 'Value': instance_id}],
        Period             = 300,
        EvaluationPeriods  = 3,
        Threshold          = 10,
        ComparisonOperator = 'LessThanOrEqualToThreshold',
        TreatMissingData   = 'notBreaching'
    )
def lambda_handler(event, context):
    instance_id = event['detail']['instance-id']
    ec2 = boto3.resource('ec2')
    instance = ec2.Instance(instance_id)
    put_cpu_alarm(instance_id)

Event pattern in Cloudwatch Rule

{
  "source": [
    "aws.ec2"
  ],
  "detail-type": [
    "EC2 Instance State-change Notification"
  ],
  "detail": {
    "state": [
      "running"
    ]
  }
}

Error I am getting,

[ERROR] KeyError: 'detail'
Traceback (most recent call last):
  File "/var/task/lambda_function.py", line 19, in lambda_handler
    instance_id = event['detail']['instance-id']

Expecting result:

Detect and stop EC2 idle running instances.


问:
Python3.8 venv returned exit status 101
I found similar posts, mostly related to linux on venv having an issue with working. python 3.8 venv missing activate command However, I am confused on how to solve it on windows, and what is happening.

I installed python3.8 from downloading it on pythons website. Then I follow the 3.8 documentation https://docs.python.org/3/library/venv.html which shows:

python3 -m venv /path/to/new/virtual/environment

I do this but then get the following error:

```<code>Error: Command '['E:\\py_envs\\hf4\\Scripts\\python.exe', '-Im', 'ensurepip', '--upgrade', '--default-pip']' returned non-zero exit status 101.
</code>```

When I use:
python -m venv --without-pip hf4

and then hf4\Scripts\activate

It works for activation. What I don't understand is that I can then run pip and it is there during the activated environment. It seems a maybe related issue, is that anything I have installed on my system python is also available. For example, in the activated session:

```<code>(hf4) E:\py_envs>where pip
C:\Users\local user\AppData\Local\Programs\Python\Python38\Scripts\pip.exe
</code>```

One question is naturally how to fix this, the other is that I would appreciate an explanation as to what is happening to better understand it.  Does it search first for the active environment, and if it can't find it, defaults to a system version?

答: I encountered the same problem and found a reason and a solution. If your python is installed on a path with a space, what I found out likely explains your case as well (which nobody really explained to you above). Check out my self-answer to my question. There is one remaining question, however, which is how this sensitivity to the space started all of a sudden, but this fix worked for me.</p>

Title: Python3.8 venv returned exit status 101

Body:
I found similar posts, mostly related to linux on venv having an issue with working. python 3.8 venv missing activate command However, I am confused on how to solve it on windows, and what is happening.

I installed python3.8 from downloading it on pythons website. Then I follow the 3.8 documentation https://docs.python.org/3/library/venv.html which shows:

python3 -m venv /path/to/new/virtual/environment

I do this but then get the following error:

Error: Command '['E:\\py_envs\\hf4\\Scripts\\python.exe', '-Im', 'ensurepip', '--upgrade', '--default-pip']' returned non-zero exit status 101.

When I use:
python -m venv --without-pip hf4

and then hf4\Scripts\activate

It works for activation. What I don't understand is that I can then run pip and it is there during the activated environment. It seems a maybe related issue, is that anything I have installed on my system python is also available. For example, in the activated session:

(hf4) E:\py_envs>where pip
C:\Users\local user\AppData\Local\Programs\Python\Python38\Scripts\pip.exe

One question is naturally how to fix this, the other is that I would appreciate an explanation as to what is happening to better understand it.  Does it search first for the active environment, and if it can't find it, defaults to a system version?


问:
Why do I get "ERROR 1062 (23000): Duplicate entry '4289' for key 1" on an update?
This question has been asked in a number of different flavors before, but the answers supplied in those cases so not come close to helping me solve my problem.

We are running MySQL version "5.0.41-community-log MySQL Community Edition (GPL)"
The table in question is described like this (I have removed most of the table definition for business reasons):

```<code> Field      Type          Null     Key     Default     Extra
 ---------  ------------  -------  ------  ----------  --------------
 id         bigint(20)    NO       PRI     (null)      auto_increment
 ...
 extracted  tinyint(1)    YES              (null)
</code>```

When I run the update SQL statement:

```<code>UPDATE transaction_tbl SET extracted = 1 WHERE id = 4289
</code>```

I get the error:

```<code>ERROR 1062 (23000): Duplicate entry '4289' for key 1
</code>```

running this select statement:

```<code>SELECT id, extracted FROM transaction_tbl WHERE id BETWEEN 4288 AND 4290
</code>```

produces this:

```<code> id     extracted
 -----  ------------
 4288   0
 4289   0
 4290   0
</code>```

I have read in places about using REPAIR on the table but received a response that "The storage engine for the table doesn't support repair"

I am at a bit of a loss. If anyone can help me. I do love to know how to fix this in a way that does not require me to destroy data.

答:
It this table has Innodb you can't use repair(only for MyIsam).
For recover InnoDb table you should run

```<code>Alter table transaction_tbl Engine=Innodb;
</code>```

or restart your server.

For checking table status try to use:

```<code>SHOW TABLE STATUS LIKE 'transaction_tbl'
</code>```

Body:
This question has been asked in a number of different flavors before, but the answers supplied in those cases so not come close to helping me solve my problem.

We are running MySQL version "5.0.41-community-log MySQL Community Edition (GPL)"
The table in question is described like this (I have removed most of the table definition for business reasons):

 Field      Type          Null     Key     Default     Extra
 ---------  ------------  -------  ------  ----------  --------------
 id         bigint(20)    NO       PRI     (null)      auto_increment
 ...
 extracted  tinyint(1)    YES              (null)

When I run the update SQL statement:

UPDATE transaction_tbl SET extracted = 1 WHERE id = 4289

I get the error:

ERROR 1062 (23000): Duplicate entry '4289' for key 1

running this select statement:

SELECT id, extracted FROM transaction_tbl WHERE id BETWEEN 4288 AND 4290

produces this:

 id     extracted
 -----  ------------
 4288   0
 4289   0
 4290   0

I have read in places about using REPAIR on the table but received a response that "The storage engine for the table doesn't support repair"

I am at a bit of a loss. If anyone can help me. I do love to know how to fix this in a way that does not require me to destroy data.

Body:
It this table has Innodb you can't use repair(only for MyIsam).
For recover InnoDb table you should run

Alter table transaction_tbl Engine=Innodb;

or restart your server.

For checking table status try to use:

SHOW TABLE STATUS LIKE 'transaction_tbl'