问:
No MaterialCardView background in darkview
I have recently moved from material-1.0 to 1.2 (the problem is in place with 1.1 too!)
Now, every thing is ok in Light view, but in Dark view, there is no card background. See the attached pictures to see what I mean.

I am attaching my java and xml files so that you can kindly check.

MainActivity

```<code>public class MainActivity extends AppCompatActivity
    implements NavigationView.OnNavigationItemSelectedListener {

  private Context mContext;

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
      AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM);
    } else {
      AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_AUTO_BATTERY);
    }
    SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
    AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES);
    String theme = sharedPref.getString("theme", "Default");
//    Toast.makeText(this, theme, Toast.LENGTH_LONG).show();
    if (theme.equals("Dark")) {
      AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES);
    } else if (theme.equals("Light")) {
      AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);
    } else {
      if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
        AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM);
      } else {
        AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_AUTO_BATTERY);
      }
    }

    super.onCreate(savedInstanceState);
    mContext = getApplicationContext();

    setContentView(R.layout.activity_main);
    Toolbar toolbar = findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

//    Navigation Drawer
    DrawerLayout drawer = findViewById(R.id.drawer_layout);
    ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
        this, drawer, toolbar, R.string.navigation_drawer_open,
        R.string.navigation_drawer_close);
    if (drawer != null) {
      drawer.addDrawerListener(toggle);
    }
    toggle.syncState();

    NavigationView navigationView = findViewById(R.id.nav_view);
    if (navigationView != null) {
      navigationView.setNavigationItemSelectedListener(this);
    }
  }

  @Override
  public boolean onNavigationItemSelected(MenuItem item) {
    DrawerLayout drawer = findViewById(R.id.drawer_layout);
    // Handle navigation view item clicks here.
    switch (item.getItemId()) {
      case R.id.nav_manage:
        // Handle the tools action (for now display a toast).
        drawer.closeDrawer(GravityCompat.START);
        Intent intentSetting = new Intent(this, SettingsActivity.class);
        startActivity(intentSetting);
        return true;
      case R.id.about_phocast:
        // Handle the share action (for now display a toast).
        startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("https://rudrab.github.io/thePhocast")));
        drawer.closeDrawer(GravityCompat.START);
//        displayToast(getString(R.string.chose_share));
        return true;
      default:
        return false;
    }
  }
}
</code>```

activity_main.xml

appbar_main.xml

```<code><androidx.coordinatorlayout.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
  xmlns:app="http://schemas.android.com/apk/res-auto"
  xmlns:tools="http://schemas.android.com/tools"
  android:layout_width="match_parent"
  android:layout_height="match_parent"
  tools:context=".MainActivity">

  <com.google.android.material.appbar.AppBarLayout
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:theme="@style/AppTheme.AppBarOverlay">

    <com.google.android.material.appbar.MaterialToolbar
      android:id="@+id/toolbar"
      android:layout_width="match_parent"
      android:layout_height="?attr/actionBarSize"
      android:background="?attr/colorPrimary"
      android:minHeight="?attr/actionBarSize"
      android:theme="?attr/actionBarTheme"
      android:title="@string/app_name" />

    <com.google.android.material.card.MaterialCardView
      android:layout_width="match_parent"
      android:layout_height="match_parent"
      android:layout_margin="8dp"
      android:layout_marginStart="10dp"
      android:layout_marginBottom="-2dp"
      android:background="?attr/colorPrimary"
      android:theme="@style/Theme.MaterialComponents.DayNight"
      app:cardCornerRadius="4dp"
      app:cardElevation="4dp">

      <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_gravity="center"
        android:orientation="vertical">

        <ImageView
          android:layout_width="match_parent"
          android:layout_height="80dp"
          android:contentDescription="@string/cityimg_desc"
          android:scaleType="fitXY"
          app:srcCompat="@drawable/property_image_3" />

          <TextView
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:background="@drawable/myrect"
            android:elevation="8dp"
            android:paddingStart="@dimen/activity_horizontal_margin"
            android:paddingEnd="0dp"
            android:text="@string/location_not_found"
            android:textColor="#ffffff"
            android:textSize="20sp" />

      </LinearLayout>
    </com.google.android.material.card.MaterialCardView>
  </com.google.android.material.appbar.AppBarLayout>
</androidx.coordinatorlayout.widget.CoordinatorLayout>
</code>```

style.xml=style-night.xml

```<code><resources>

  <!-- Base application theme. -->
  <style name="AppTheme" parent="Theme.MaterialComponents.DayNight">
    <!-- Customize your theme here. -->
    <item name="colorPrimary">@color/colorPrimary</item>
    <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
    <item name="colorAccent">@color/colorAccent</item>
  </style>

  <style name="AppTheme.NoActionBar">
    <item name="windowActionBar">false</item>
    <item name="windowNoTitle">true</item>
  </style>

  <style name="AppTheme.AppBarOverlay" parent="ThemeOverlay.MaterialComponents.Dark.ActionBar" />

</resources>
</code>```

And I cant find out where the error is.

Kindly help/

Update: after @Soumik and @Gabriele's post
My updated theme is:

```<code><?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
  xmlns:app="http://schemas.android.com/apk/res-auto"
  xmlns:tools="http://schemas.android.com/tools"
  android:layout_width="match_parent"
  android:layout_height="match_parent"
  android:theme="@style/Theme.MaterialComponents.DayNight"
  tools:context=".MainActivity">

  <com.google.android.material.appbar.AppBarLayout
    android:layout_width="wrap_content"
    android:layout_height="wrap_content">

    <com.google.android.material.appbar.MaterialToolbar
      android:id="@+id/toolbar"
      android:layout_width="match_parent"
      android:layout_height="?attr/actionBarSize"
      android:background="@color/colorPrimary"
      android:minHeight="?attr/actionBarSize"
      android:theme="?attr/actionBarTheme"
      android:title="@string/app_name" />

    <com.google.android.material.card.MaterialCardView
      style="@style/Widget.MaterialComponents.CardView"
      android:layout_width="match_parent"
      android:layout_height="match_parent"
      android:layout_margin="8dp"
      android:layout_marginStart="10dp"
      android:layout_marginBottom="-2dp"
      app:cardCornerRadius="4dp"
      app:cardBackgroundColor="@color/colorPrimary"
      app:cardElevation="4dp">

      <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_gravity="center"
        android:orientation="vertical">

        <ImageView
          android:layout_width="match_parent"
          android:layout_height="80dp"
          android:contentDescription="@string/cityimg_desc"
          android:scaleType="fitXY"
          app:srcCompat="@drawable/property_image_3" />

        <TextView
          android:layout_width="match_parent"
          android:layout_height="match_parent"
          android:background="@drawable/myrect"
          android:elevation="8dp"
          android:paddingStart="@dimen/activity_horizontal_margin"
          android:paddingEnd="0dp"
          android:text="@string/location_not_found"
          android:textColor="#ffffff"
          android:textSize="20sp" />

      </LinearLayout>
    </com.google.android.material.card.MaterialCardView>
  </com.google.android.material.appbar.AppBarLayout>
</androidx.coordinatorlayout.widget.CoordinatorLayout>
</code>```

The result of the changed xml file is updated, and a screenshot is added. Kindly check.

答:
Use

```<code>    app:cardBackgroundColor="@color/colorPrimary"
</code>```

instead of

```<code>    android:background="?attr/colorPrimary"
</code>```

Body:
I have recently moved from material-1.0 to 1.2 (the problem is in place with 1.1 too!)
Now, every thing is ok in Light view, but in Dark view, there is no card background. See the attached pictures to see what I mean.

I am attaching my java and xml files so that you can kindly check.

MainActivity

public class MainActivity extends AppCompatActivity
    implements NavigationView.OnNavigationItemSelectedListener {

  private Context mContext;

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
      AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM);
    } else {
      AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_AUTO_BATTERY);
    }
    SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
    AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES);
    String theme = sharedPref.getString("theme", "Default");
//    Toast.makeText(this, theme, Toast.LENGTH_LONG).show();
    if (theme.equals("Dark")) {
      AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES);
    } else if (theme.equals("Light")) {
      AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);
    } else {
      if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
        AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM);
      } else {
        AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_AUTO_BATTERY);
      }
    }

    super.onCreate(savedInstanceState);
    mContext = getApplicationContext();

    setContentView(R.layout.activity_main);
    Toolbar toolbar = findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

//    Navigation Drawer
    DrawerLayout drawer = findViewById(R.id.drawer_layout);
    ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
        this, drawer, toolbar, R.string.navigation_drawer_open,
        R.string.navigation_drawer_close);
    if (drawer != null) {
      drawer.addDrawerListener(toggle);
    }
    toggle.syncState();

    NavigationView navigationView = findViewById(R.id.nav_view);
    if (navigationView != null) {
      navigationView.setNavigationItemSelectedListener(this);
    }
  }

  @Override
  public boolean onNavigationItemSelected(MenuItem item) {
    DrawerLayout drawer = findViewById(R.id.drawer_layout);
    // Handle navigation view item clicks here.
    switch (item.getItemId()) {
      case R.id.nav_manage:
        // Handle the tools action (for now display a toast).
        drawer.closeDrawer(GravityCompat.START);
        Intent intentSetting = new Intent(this, SettingsActivity.class);
        startActivity(intentSetting);
        return true;
      case R.id.about_phocast:
        // Handle the share action (for now display a toast).
        startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("https://rudrab.github.io/thePhocast")));
        drawer.closeDrawer(GravityCompat.START);
//        displayToast(getString(R.string.chose_share));
        return true;
      default:
        return false;
    }
  }
}

activity_main.xml

appbar_main.xml

<androidx.coordinatorlayout.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
  xmlns:app="http://schemas.android.com/apk/res-auto"
  xmlns:tools="http://schemas.android.com/tools"
  android:layout_width="match_parent"
  android:layout_height="match_parent"
  tools:context=".MainActivity">

  <com.google.android.material.appbar.AppBarLayout
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:theme="@style/AppTheme.AppBarOverlay">

    <com.google.android.material.appbar.MaterialToolbar
      android:id="@+id/toolbar"
      android:layout_width="match_parent"
      android:layout_height="?attr/actionBarSize"
      android:background="?attr/colorPrimary"
      android:minHeight="?attr/actionBarSize"
      android:theme="?attr/actionBarTheme"
      android:title="@string/app_name" />

    <com.google.android.material.card.MaterialCardView
      android:layout_width="match_parent"
      android:layout_height="match_parent"
      android:layout_margin="8dp"
      android:layout_marginStart="10dp"
      android:layout_marginBottom="-2dp"
      android:background="?attr/colorPrimary"
      android:theme="@style/Theme.MaterialComponents.DayNight"
      app:cardCornerRadius="4dp"
      app:cardElevation="4dp">

      <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_gravity="center"
        android:orientation="vertical">

        <ImageView
          android:layout_width="match_parent"
          android:layout_height="80dp"
          android:contentDescription="@string/cityimg_desc"
          android:scaleType="fitXY"
          app:srcCompat="@drawable/property_image_3" />

          <TextView
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:background="@drawable/myrect"
            android:elevation="8dp"
            android:paddingStart="@dimen/activity_horizontal_margin"
            android:paddingEnd="0dp"
            android:text="@string/location_not_found"
            android:textColor="#ffffff"
            android:textSize="20sp" />

      </LinearLayout>
    </com.google.android.material.card.MaterialCardView>
  </com.google.android.material.appbar.AppBarLayout>
</androidx.coordinatorlayout.widget.CoordinatorLayout>

style.xml=style-night.xml

<resources>

Body:
Use

    app:cardBackgroundColor="@color/colorPrimary"

instead of

    android:background="?attr/colorPrimary"


来源: stackexchange

问:
How to create POJO dynamically using JSON?
I have multiple dyanamic json templates as belows

JSON 1

```<code>{
      "param1": "testuser1",
      "param2": "testuser1@gmail.com"
}
</code>```

JSON 2

```<code>{
      "param1": "testuser2",
      "param2": "testuser2@gmail.com",
      "param3": "New York"
}
</code>```

JSON 3

```<code>{
      "param1": "testuser3"
      "param2": "testuser3@gmail.com",
      "param3": "New York",
      "param4": [
            {
                "sub-param1": "X",
                "sub-param2": "Y"
            },
            {
                "param1": "testuser",
                "param2": "testuser@gmail.com"
            }
          ]
}
</code>```

I want to covert them into JAVA Object at runtime i.e. without creating POJO at compile time. Is this possible ? If yes how to do that?

I tried using Jackson lib to convert json into object (Object Class), but how to create common generic POJO or how to create POJO with setter getter dynamically?

答:
You probably want to deserialize your JSON document into a Map<String, Object> or maybe use the Jackson tree model, as shown below:

TypeReference<Map<String, Object>> type = new TypeReference<Map<String, Object>>() {};
Map<String, Object> map = mapper.readValue(json, type);
```

<pre class="lang-java prettyprint-override"><code>JsonNode jsonNode = mapper.readTree(json);
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have multiple dyanamic json templates as belows

JSON 1

{
      "param1": "testuser1",
      "param2": "testuser1@gmail.com"
}

JSON 2

{
      "param1": "testuser2",
      "param2": "testuser2@gmail.com",
      "param3": "New York"
}

JSON 3

{
      "param1": "testuser3"
      "param2": "testuser3@gmail.com",
      "param3": "New York",
      "param4": [
            {
                "sub-param1": "X",
                "sub-param2": "Y"
            },
            {
                "param1": "testuser",
                "param2": "testuser@gmail.com"
            }
          ]
}

I want to covert them into JAVA Object at runtime i.e. without creating POJO at compile time. Is this possible ? If yes how to do that?

I tried using Jackson lib to convert json into object (Object Class), but how to create common generic POJO or how to create POJO with setter getter dynamically?

Body:
You probably want to deserialize your JSON document into a Map<String, Object> or maybe use the Jackson tree model, as shown below:

TypeReference<Map<String, Object>> type = new TypeReference<Map<String, Object>>() {};
Map<String, Object> map = mapper.readValue(json, type);

JsonNode jsonNode = mapper.readTree(json);


问:
how to display product detail description on product listing page?
I want to show a detailed product description after a short description on the product listing page.

I'm doing this

```<code><?
echo $_product->getDescription();
?>
</code>```

but nothing shows up.

I also tried this

```<code>Mage::getModel('catalog/product')->load($_product->getProductId())->getDescription();
</code>```

but to no success.

答:
Try setting product attribute for descrption field "Used in Product Listing" to "YES".
That will solve your problem and avoid redundant model load</p>

ContentLicense: CC BY-SA 3.0

Body:
I want to show a detailed product description after a short description on the product listing page.

I'm doing this

<?
echo $_product->getDescription();
?>

but nothing shows up.

I also tried this

Mage::getModel('catalog/product')->load($_product->getProductId())->getDescription();

but to no success.


问:
dropdown menu is hiding behind toolbar
i am using ionic4/angular. on-clicking on the ion-avatar a dropdown menu should display but the dropdown menu is hiding in the toolbar. i tried giving z-index but it is not working. Thanks.

stackblitz link

<ion-header>
  <ion-toolbar color="tertiary" >

    <ion-buttons slot="start">
      <ion-back-button defaultHref="/"></ion-back-button>
    </ion-buttons>

    <ion-buttons slot="end">
      <button class="btn btn-light">My Courses</button>
    </ion-buttons>

    <ion-buttons slot="end">
      <ion-button class="iconbell">
        <ion-icon name="notifications-outline" size="large"></ion-icon>
      </ion-button>
    </ion-buttons>

    <ion-buttons slot="end">

        <ion-avatar class="dropdown-toggle" style="margin-right:10px;height: 5vh;width: 5vh;" id="menu1" type="button" data-toggle="dropdown">

        </ion-avatar>

HTML

CSS

JavaScript

About Us

    </ion-buttons>

  </ion-toolbar>
</ion-header>```

答:
There are contain property inside shadow-root with static value [ without dynamic CSS variables ] and that we can override as rule of ionic shadow-element.

example

You can go with popover option of ionic framework

Title: dropdown menu is hiding behind toolbar


问:
How to find a substring from some text in a file and store it in a bash variable?
I have a file named config.txt which has following data:

```<code>ABC_PATH=xxx/xxx
IMAGE=docker.name.net:3000/apache:1.8.109.1
NAMESPACE=xxx
</code>```

Now I am running a shell script in which I want to store 1.8.109.1 (this value may differ, rest will remain same) in a variable, maybe using sed, awk or any other linux tool.
How can I achieve that?

答:
I think this should work:</p>

```<code>cat config.txt | grep apache: | cut -d: -f3
</code>```

Body:
I have a file named config.txt which has following data:

ABC_PATH=xxx/xxx
IMAGE=docker.name.net:3000/apache:1.8.109.1
NAMESPACE=xxx

Now I am running a shell script in which I want to store 1.8.109.1 (this value may differ, rest will remain same) in a variable, maybe using sed, awk or any other linux tool.
How can I achieve that?

Body:
I think this should work:

cat config.txt | grep apache: | cut -d: -f3


问:
How do I get a reflection on a property's property in Kotlin?
say we have a class with a property subClass.

```<code>class TestClass(val property: SubClass)
</code>```

The SubClass has its own property

```<code>class SubClass(val subProperty: Any?)
</code>```

When I only have access to the class itself, I know that I can easily get a reflection to the property via

```<code>val reflection = TestClass::property
</code>```

However, how do I get access to the subProperty via reflection? The following does not work:

```<code>val subReflection = TestClass::property::subProperty
</code>```

I'd apprectiate any insight on that! Thanks!

答:
I have found the answer (thanks to @BernhardKern):</p>

```<code>TestClass::property.toJoin().where(SubClass::subProperty).equal(whatINeed)
</code>```

Body:
say we have a class with a property subClass.

class TestClass(val property: SubClass)

The SubClass has its own property

class SubClass(val subProperty: Any?)

When I only have access to the class itself, I know that I can easily get a reflection to the property via

val reflection = TestClass::property

However, how do I get access to the subProperty via reflection? The following does not work:

val subReflection = TestClass::property::subProperty

I'd apprectiate any insight on that! Thanks!

Body:
I have found the answer (thanks to @BernhardKern):

TestClass::property.toJoin().where(SubClass::subProperty).equal(whatINeed)


问:
Huge heap dump (11GB) - Jhat failed & Eclipse MAT needed help
We got a memory error in our EA and we used -XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=/path/to/some/dir to dump the heap at the time of OOM.

We had a heap memory of 12GB and perm gen of 256MB.

The heap dump is generated in the Linux box where we have our application running and its size is 11.5GB. We don't have privileges to download it to our local.

When we tried to analyze that 11GB heap dump using JHAT it thrown an OOM.

We tried the following commands from our Linux CLI.

```<code>jhat java_pid1491.hprof
jhat -J-Xmx16g -XX:-UseBiasedLocking java_pid1491.hprof
jhat -J-d64 -J-Xmx16g -J-XX:-UseBiasedLocking java_pid1491.hprof#1
</code>```

For all the options its throwing an OOM exception after reading the dump for several minutes(>30 mins).

We googled it and found MAT as a powerful heap dump analyzer, but not a way to use it in LINUX.

Any suggestions would be of greater help. Thanks.

Modified:

Got MAT installed in Linux x86_64 machine but got following error when executed ./MemoryAnalyzer

```<code>(.:17319): GLib-GObject-WARNING **: invalid (NULL) pointer instance
(.:17319): GLib-GObject-CRITICAL **: g_signal_connect_data: assertion `G_TYPE_CHECK_INSTANCE (instance)' failed
(.:17319): Gtk-CRITICAL **: gtk_settings_get_for_screen: assertion `GDK_IS_SCREEN (screen)' failed
(.:17319): GLib-GObject-CRITICAL **: g_object_get: assertion `G_IS_OBJECT (object)' failed
(.:17319): Gtk-WARNING **: Screen for GtkWindow not set; you must always set
a screen for a GtkWindow before using the window
(.:17319): Gdk-CRITICAL **: gdk_pango_context_get_for_screen: assertion `GDK_IS_SCREEN (screen)' failed
(.:17319): Pango-CRITICAL **: pango_context_set_font_description: assertion `context != NULL' failed
(.:17319): Pango-CRITICAL **: pango_context_set_base_dir: assertion `context != NULL' failed
(.:17319): Pango-CRITICAL **: pango_context_set_language: assertion `context != NULL' failed
(.:17319): Pango-CRITICAL **: pango_layout_new: assertion `context != NULL' failed
(.:17319): Pango-CRITICAL **: pango_layout_set_text: assertion `layout != NULL' failed
(.:17319): Pango-CRITICAL **: pango_layout_set_attributes: assertion `layout != NULL' failed
(.:17319): Pango-CRITICAL **: pango_layout_set_alignment: assertion `layout != NULL' failed
(.:17319): Pango-CRITICAL **: pango_layout_set_ellipsize: assertion `PANGO_IS_LAYOUT (layout)' failed
(.:17319): Pango-CRITICAL **: pango_layout_set_single_paragraph_mode: assertion `PANGO_IS_LAYOUT (layout)' failed
(.:17319): Pango-CRITICAL **: pango_layout_set_width: assertion `layout != NULL' failed
(.:17319): Pango-CRITICAL **: pango_layout_get_extents: assertion `layout != NULL' failed
(.:17319): Gtk-CRITICAL **: gtk_icon_theme_get_for_screen: assertion `GDK_IS_SCREEN (screen)' failed
(.:17319): Gtk-CRITICAL **: gtk_settings_get_for_screen: assertion `GDK_IS_SCREEN (screen)' failed
(.:17319): Gtk-CRITICAL **: gtk_icon_size_lookup_for_settings: assertion `GTK_IS_SETTINGS (settings)' failed
(.:17319): Gtk-WARNING **: Invalid icon size 6
(.:17319): Gtk-CRITICAL **: gtk_icon_theme_load_icon: assertion `GTK_IS_ICON_THEME (icon_theme)' failed
Segmentation fault
</code>```

I tried ./ParseHeapDump.sh ../java_pid1491.hprof this and got following error,

```<code>Caused by: java.lang.NoClassDefFoundError: com/ibm/dtfj/image/CorruptDataException
        at org.eclipse.mat.dtfj.InitDTFJ.stop(InitDTFJ.java:70)
</code>```

答:
I was using MAT on Linux yesterday....
check out the proper version here</p>

Body:
We got a memory error in our EA and we used -XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=/path/to/some/dir to dump the heap at the time of OOM.

We had a heap memory of 12GB and perm gen of 256MB.

The heap dump is generated in the Linux box where we have our application running and its size is 11.5GB. We don't have privileges to download it to our local.

When we tried to analyze that 11GB heap dump using JHAT it thrown an OOM.

We tried the following commands from our Linux CLI.

jhat java_pid1491.hprof
jhat -J-Xmx16g -XX:-UseBiasedLocking java_pid1491.hprof
jhat -J-d64 -J-Xmx16g -J-XX:-UseBiasedLocking java_pid1491.hprof#1

For all the options its throwing an OOM exception after reading the dump for several minutes(>30 mins).

We googled it and found MAT as a powerful heap dump analyzer, but not a way to use it in LINUX.

Any suggestions would be of greater help. Thanks.

Modified:

Got MAT installed in Linux x86_64 machine but got following error when executed ./MemoryAnalyzer

(.:17319): GLib-GObject-WARNING **: invalid (NULL) pointer instance
(.:17319): GLib-GObject-CRITICAL **: g_signal_connect_data: assertion `G_TYPE_CHECK_INSTANCE (instance)' failed
(.:17319): Gtk-CRITICAL **: gtk_settings_get_for_screen: assertion `GDK_IS_SCREEN (screen)' failed
(.:17319): GLib-GObject-CRITICAL **: g_object_get: assertion `G_IS_OBJECT (object)' failed
(.:17319): Gtk-WARNING **: Screen for GtkWindow not set; you must always set
a screen for a GtkWindow before using the window
(.:17319): Gdk-CRITICAL **: gdk_pango_context_get_for_screen: assertion `GDK_IS_SCREEN (screen)' failed
(.:17319): Pango-CRITICAL **: pango_context_set_font_description: assertion `context != NULL' failed
(.:17319): Pango-CRITICAL **: pango_context_set_base_dir: assertion `context != NULL' failed
(.:17319): Pango-CRITICAL **: pango_context_set_language: assertion `context != NULL' failed
(.:17319): Pango-CRITICAL **: pango_layout_new: assertion `context != NULL' failed
(.:17319): Pango-CRITICAL **: pango_layout_set_text: assertion `layout != NULL' failed
(.:17319): Pango-CRITICAL **: pango_layout_set_attributes: assertion `layout != NULL' failed
(.:17319): Pango-CRITICAL **: pango_layout_set_alignment: assertion `layout != NULL' failed
(.:17319): Pango-CRITICAL **: pango_layout_set_ellipsize: assertion `PANGO_IS_LAYOUT (layout)' failed
(.:17319): Pango-CRITICAL **: pango_layout_set_single_paragraph_mode: assertion `PANGO_IS_LAYOUT (layout)' failed
(.:17319): Pango-CRITICAL **: pango_layout_set_width: assertion `layout != NULL' failed
(.:17319): Pango-CRITICAL **: pango_layout_get_extents: assertion `layout != NULL' failed
(.:17319): Gtk-CRITICAL **: gtk_icon_theme_get_for_screen: assertion `GDK_IS_SCREEN (screen)' failed
(.:17319): Gtk-CRITICAL **: gtk_settings_get_for_screen: assertion `GDK_IS_SCREEN (screen)' failed
(.:17319): Gtk-CRITICAL **: gtk_icon_size_lookup_for_settings: assertion `GTK_IS_SETTINGS (settings)' failed
(.:17319): Gtk-WARNING **: Invalid icon size 6
(.:17319): Gtk-CRITICAL **: gtk_icon_theme_load_icon: assertion `GTK_IS_ICON_THEME (icon_theme)' failed
Segmentation fault

I tried ./ParseHeapDump.sh ../java_pid1491.hprof this and got following error,

Caused by: java.lang.NoClassDefFoundError: com/ibm/dtfj/image/CorruptDataException
        at org.eclipse.mat.dtfj.InitDTFJ.stop(InitDTFJ.java:70)


问:
How to set a type for data received from Angular HTTP request?
This is my code to fetch data:

```<code>login() {
    const url = api + 'login';
    this.http.post(url, this.userModel)
      .subscribe(
        data => {
          localStorage.token = data.token;
          this.router.navigate(['/home']);
        },
        error => {
          alert(error.error.error);
        }
      )
  }
</code>```

This would return a JSON of

```<code>{
   message: "logged In Successful!",
   token: "e4affa4633fb046333731ae6fadcb980b98636b513a0fb80721759267b4efa5c9b7845663f2b1288"
}
</code>```

It works, it saves to the local storage, but this error keeps popping in my console? why?

答:
You're getting the error because typescript cannot resolve a type for the response object, therefore you need to specify the response object type of your post request:</p>

```<code>  login() {
    const url = api + 'login';
    this.http.post<{ message: string, token: string }>(url, this.userModel)
      .subscribe(
        data => {
          localStorage.token = data.token;
          this.router.navigate(['/home']);
        },
        error => {
          alert(error.error.error);
        }
      )
  }
</code>```

Body:
This is my code to fetch data:

login() {
    const url = api + 'login';
    this.http.post(url, this.userModel)
      .subscribe(
        data => {
          localStorage.token = data.token;
          this.router.navigate(['/home']);
        },
        error => {
          alert(error.error.error);
        }
      )
  }

This would return a JSON of

{
   message: "logged In Successful!",
   token: "e4affa4633fb046333731ae6fadcb980b98636b513a0fb80721759267b4efa5c9b7845663f2b1288"
}

It works, it saves to the local storage, but this error keeps popping in my console? why?

Body:
You're getting the error because typescript cannot resolve a type for the response object, therefore you need to specify the response object type of your post request:

  login() {
    const url = api + 'login';
    this.http.post<{ message: string, token: string }>(url, this.userModel)
      .subscribe(
        data => {
          localStorage.token = data.token;
          this.router.navigate(['/home']);
        },
        error => {
          alert(error.error.error);
        }
      )
  }


问:
Why doesn't selenium click?(Python)
The other day, I started using the Selenium library to press buttons on YouTube, and everything was fine, but the other day, for some reason, it stopped pressing buttons, I didn’t change anything, everything was exactly the same, and when I checked the code on another computer, everything was fine, and most importantly, he didn’t even
gives me errors and pretends that everything went well!
What to do in this situation, I will be glad to every answer! (Worked in python)</p>

```<code>from selenium import webdriver
import time

url = 'url video'
FILE_NAME_PROFILE = "C:/Users/xxx/AppData/Local/Google/Chrome/User Data"
options = webdriver.ChromeOptions()
options.add_argument("user-data-dir=" + FILE_NAME_PROFILE)
driver =webdriver.Chrome(executable_path="C:/Users/xxx/Downloads/chromedriver_win32(1)/chromedriver.exe",chrome_options=options)
driver.get(url)
time.sleep(10)
like = driver.find_element_by_xpath('//yt-icon[@class="style-scope ytd-toggle-button-renderer"]')
like.click()
driver.quit()
</code>```

答:
Try adjusting as thus:</p>

```<code>from selenium import webdriver
import time
from selenium.webdriver.support.ui import WebDriverWait ##new line of code

url = 'url video'
FILE_NAME_PROFILE = "C:/Users/xxx/AppData/Local/Google/Chrome/User Data"
options = webdriver.ChromeOptions()
options.add_argument("user-data-dir=" + FILE_NAME_PROFILE)
driver =webdriver.Chrome(executable_path="C:/Users/xxx/Downloads/chromedriver_win32(1)/chromedriver.exe",chrome_options=options)
driver.get(url)
time.sleep(10)

inp_xpath_search = '//yt-icon[@class="style-scope ytd-toggle-button-renderer"]'

like = WebDriverWait(driver,50).until(lambda driver: driver.find_element_by_xpath(inp_xpath_search))

like.click()
time.sleep(2)

driver.quit()
</code>```

Title: Why doesn't selenium click?(Python)

Body:
The other day, I started using the Selenium library to press buttons on YouTube, and everything was fine, but the other day, for some reason, it stopped pressing buttons, I didn’t change anything, everything was exactly the same, and when I checked the code on another computer, everything was fine, and most importantly, he didn’t even
gives me errors and pretends that everything went well!
What to do in this situation, I will be glad to every answer! (Worked in python)

from selenium import webdriver
import time

url = 'url video'
FILE_NAME_PROFILE = "C:/Users/xxx/AppData/Local/Google/Chrome/User Data"
options = webdriver.ChromeOptions()
options.add_argument("user-data-dir=" + FILE_NAME_PROFILE)
driver =webdriver.Chrome(executable_path="C:/Users/xxx/Downloads/chromedriver_win32(1)/chromedriver.exe",chrome_options=options)
driver.get(url)
time.sleep(10)
like = driver.find_element_by_xpath('//yt-icon[@class="style-scope ytd-toggle-button-renderer"]')
like.click()
driver.quit()

Body:
Try adjusting as thus:

from selenium import webdriver
import time
from selenium.webdriver.support.ui import WebDriverWait ##new line of code

url = 'url video'
FILE_NAME_PROFILE = "C:/Users/xxx/AppData/Local/Google/Chrome/User Data"
options = webdriver.ChromeOptions()
options.add_argument("user-data-dir=" + FILE_NAME_PROFILE)
driver =webdriver.Chrome(executable_path="C:/Users/xxx/Downloads/chromedriver_win32(1)/chromedriver.exe",chrome_options=options)
driver.get(url)
time.sleep(10)

inp_xpath_search = '//yt-icon[@class="style-scope ytd-toggle-button-renderer"]'

like = WebDriverWait(driver,50).until(lambda driver: driver.find_element_by_xpath(inp_xpath_search))

like.click()
time.sleep(2)

driver.quit()


问:
Writing to file a list where a unique string from column 1 gets multiple strings from column 2
I am totally new to python and need help.  I have a table that has 2 columns.  Column 1 contains the Genus and Column 2 contains Species.  I can iterate through the columns using SearchCursor and print out each row with a genus and a species.  What I need to do is print out a unique genus with all of its associated species.  So for example I have:

```<code>Acer    Maple
Acer    Sugar Maple
Acer    Purple Maple
Abies   Jack Pine
Abies    Spruce
</code>```

I want

```<code>Acer|Maple|Sugar Maple|Purple Maple
Abies|Jack Pine|Spruce
</code>```

I have tried but I can not figure out if I need a while loop, and if loop or a for loop.  When I try while and if my loops go on forever.

Here one attempt:

```<code>myCursor1=arcpy.da.SearchCursor(FreqGISTable,["Genus","Species"])
for row in myCursor1:
    gisfile.write((row[0]).upper())
    if (row[0] == row[0]):
          gisfile.write(row[1])
    else:
         if (row[0] != row[0]):
            gisfile.write("END\n")

gisfile.close()
return gisfile
</code>```

So thank you for the help. I had to tweak it a bit. The code works for the most part however, I need it to print all of the col2 items then print "END_OPTIONS|\n" at the very end of the line.

I have tried numerous ways to set it up but it doesn't work. The line = row['col2'] + "|" will not recognize the "|" and when I try to insert the final End Options it places it right after each col2 item.  Any suggestions to fix that?

答:
This is another approach that I think out of:</p>

```<code>df = pd.DataFrame({'col1': ['Acer','Acer','Acer','Abies','Abies'], 'col2' : ['Maple','Sugar Maple','Purple Maple','Jack Pine','Spruce']})

copy = ""

df['col3'] = df['col1'].shift(1)

for row in df.itertuples():
    if row.col1 == row.col3:
        copy = copy + row.col2 + "|"
    elif row.col1 != row.col3:
        copy = copy + " \n" + row.col1 + "|" + row.col2 + "|"
        copy = copy[1:]

print(copy)
</code>```

Body:
I am totally new to python and need help.  I have a table that has 2 columns.  Column 1 contains the Genus and Column 2 contains Species.  I can iterate through the columns using SearchCursor and print out each row with a genus and a species.  What I need to do is print out a unique genus with all of its associated species.  So for example I have:

Acer    Maple
Acer    Sugar Maple
Acer    Purple Maple
Abies   Jack Pine
Abies    Spruce

I want

Acer|Maple|Sugar Maple|Purple Maple
Abies|Jack Pine|Spruce

I have tried but I can not figure out if I need a while loop, and if loop or a for loop.  When I try while and if my loops go on forever.

Here one attempt:

myCursor1=arcpy.da.SearchCursor(FreqGISTable,["Genus","Species"])
for row in myCursor1:
    gisfile.write((row[0]).upper())
    if (row[0] == row[0]):
          gisfile.write(row[1])
    else:
         if (row[0] != row[0]):
            gisfile.write("END\n")

gisfile.close()
return gisfile

So thank you for the help. I had to tweak it a bit. The code works for the most part however, I need it to print all of the col2 items then print "END_OPTIONS|\n" at the very end of the line.

I have tried numerous ways to set it up but it doesn't work. The line = row['col2'] + "|" will not recognize the "|" and when I try to insert the final End Options it places it right after each col2 item.  Any suggestions to fix that?

Body:
This is another approach that I think out of:

df = pd.DataFrame({'col1': ['Acer','Acer','Acer','Abies','Abies'], 'col2' : ['Maple','Sugar Maple','Purple Maple','Jack Pine','Spruce']})

copy = ""

df['col3'] = df['col1'].shift(1)

for row in df.itertuples():
    if row.col1 == row.col3:
        copy = copy + row.col2 + "|"
    elif row.col1 != row.col3:
        copy = copy + " \n" + row.col1 + "|" + row.col2 + "|"
        copy = copy[1:]

print(copy)


问:
Bootstrapping Binomial Distribution
I am working on a simple problem, I want to write a function that will randomly draw n samples of size q from a binomial distribution (say 60% 1, and 40% 0), and then save the share of 1s from each sample in an array (so that I can analyze that array later). For instance, I would like to simulate, if I drew 1,000 samples each of size 30 from a distribution with 60% 1s and 40% 0s, and I would like as an output an array of length 1,000, where each row represents the share of 1's from that sample.</p>

答:
Do you mean Bernoulli distribution ?</p>

```<code>from scipy.stats import bernoulli
data = [bernoulli.rvs(0.6, size=30) for _ in range(1000)]
</code>```

Title: Bootstrapping Binomial Distribution

Body:
Do you mean Bernoulli distribution ?

from scipy.stats import bernoulli
data = [bernoulli.rvs(0.6, size=30) for _ in range(1000)]


问:
How do you rescue I18n::MissingTranslationData?
I want to be able to rescue I18n::MissingTranslationData like so:

```<code>begin
  value = I18n.t('some.key.that.does.not.exist')
  puts value
  return value if value
rescue I18n::MissingTranslationData
  puts "Kaboom!"
end
</code>```

I tried the above, but it doesn't seem to go into the rescue block. I just see, on my console (because of puts): translation missing: some.key.that.does.not.exist. I never see Kaboom!.

How do I get this to work?

答:
IMO, it's pretty strange but in the current version of i18n (0.5.0) you should pass an exception that you want to rescue:

```<code>require 'i18n'
begin
  value = I18n.translate('some.key.that.does.not.exist', :raise => I18n::MissingTranslationData)
  puts value
  return value if value
rescue I18n::MissingTranslationData
  puts "Kaboom!"
end
</code>```

and it will be fixed in the future 0.6 release (you can test it - https://github.com/svenfuchs/i18n)

Body:
I want to be able to rescue I18n::MissingTranslationData like so:

begin
  value = I18n.t('some.key.that.does.not.exist')
  puts value
  return value if value
rescue I18n::MissingTranslationData
  puts "Kaboom!"
end

I tried the above, but it doesn't seem to go into the rescue block. I just see, on my console (because of puts): translation missing: some.key.that.does.not.exist. I never see Kaboom!.

How do I get this to work?

Body:
IMO, it's pretty strange but in the current version of i18n (0.5.0) you should pass an exception that you want to rescue:

require 'i18n'
begin
  value = I18n.translate('some.key.that.does.not.exist', :raise => I18n::MissingTranslationData)
  puts value
  return value if value
rescue I18n::MissingTranslationData
  puts "Kaboom!"
end

and it will be fixed in the future 0.6 release (you can test it - https://github.com/svenfuchs/i18n)


问:
How to delete bulk rows in Ignite's SQL table
Can someone please suggest me an efficient way to bulk delete rows from a table using SQL query?</p>

答: Why don't you use cache.removeAll(keys) from Cache API? Sometimes SQL is not the most straightforward way.


问:
How to execute a loop with sequential summation?
I have an array with this loop:

var arr = [5, 4, 9, 6, 4];

var sum = 0;

arr.forEach(function(item) {
  sum += parseInt(item);
  console.log(sum)
});```
</div>
</div>
</p>

<p>At the moment, I get this result:</p>

```5
9
18
24
28
```

<p>But how to make sure that the result always starts with 0 and ends with the penultimate digit, i.e. it should look like this:</p>

```0
5
9
18
24
```

答:
You just need to move the console.log up one line. If you want the 28 to be logged also, then add a console.log(sum) after the loop.

var arr = [5, 4, 9, 6, 4];

var sum = 0;

arr.forEach(function(item) {
  console.log(sum)
  sum += parseInt(item);
});```

Body:
I have an array with this loop:

var arr = [5, 4, 9, 6, 4];

var sum = 0;

arr.forEach(function(item) {
  sum += parseInt(item);
  console.log(sum)
});

At the moment, I get this result:

5
9
18
24
28

But how to make sure that the result always starts with 0 and ends with the penultimate digit, i.e. it should look like this:

0
5
9
18
24


问:
creating text in webpage like in the gif below
i want to create a text in a webpage like a timer goes out using js like in the gif image

my code is given below .. it show text like 12345678910...

var i;
for (i=0 ; i < 10; i++)
{
document.write(i);
}```

答:
You didn't understand loops in JavaScript. Loops are done immediately and not one loop per second. You need to have some timing. You could use window.setTimeout or window.setInterval, but I prefer requestAnimationFrame along with some Date() calculation like here

console.clear();
function startTimer(element, seconds) {
  "use strict";

  var start = new Date();
  var now, diff, eta;

  function getMinutes() {
    return Math.max(0, Math.ceil((eta - eta % 60) / 60))
  }
  function getSeconds() {
    return Math.max(0, Math.ceil(eta % 60))
  }
  function format(x) {
    return (''+x).padStart(2, '0');
  }
  function draw() {
    element.innerHTML = format(getMinutes()) + ':' + format(getSeconds())
  }
  function finished() {
    element.classList.add('finished')
  }

  function update() {
    now = new Date();

    diff = (now.getTime() - start.getTime()) / 1000
    eta = seconds - diff;
    draw()

    if (eta > 0) {
      window.requestAnimationFrame(update)
    } else {
      finished()
    }
  }
  update()
}

startTimer(document.getElementById("timer"), 720);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#timer {
  font-size: 72px;
  font-weight: bold;
  font-family: sans-serif;
  color: white;
}
#timer.finished {
  color: red;
}

html, body {
  height: 100%;
}

body {
  background-color: #000;
  display: -webkit-box;
  display: flex;
  -webkit-box-align: center;
          align-items: center;
  -webkit-box-pack: center;
          justify-content: center;
}</code>```

```

Body:
You didn't understand loops in JavaScript. Loops are done immediately and not one loop per second. You need to have some timing. You could use window.setTimeout or window.setInterval, but I prefer requestAnimationFrame along with some Date() calculation like here

console.clear();
function startTimer(element, seconds) {
  "use strict";

  var start = new Date();
  var now, diff, eta;

  function getMinutes() {
    return Math.max(0, Math.ceil((eta - eta % 60) / 60))
  }
  function getSeconds() {
    return Math.max(0, Math.ceil(eta % 60))
  }
  function format(x) {
    return (''+x).padStart(2, '0');
  }
  function draw() {
    element.innerHTML = format(getMinutes()) + ':' + format(getSeconds())
  }
  function finished() {
    element.classList.add('finished')
  }

  function update() {
    now = new Date();

    diff = (now.getTime() - start.getTime()) / 1000
    eta = seconds - diff;
    draw()

    if (eta > 0) {
      window.requestAnimationFrame(update)
    } else {
      finished()
    }
  }
  update()
}

startTimer(document.getElementById("timer"), 720);

#timer {
  font-size: 72px;
  font-weight: bold;
  font-family: sans-serif;
  color: white;
}
#timer.finished {
  color: red;
}

html, body {
  height: 100%;
}

body {
  background-color: #000;
  display: -webkit-box;
  display: flex;
  -webkit-box-align: center;
          align-items: center;
  -webkit-box-pack: center;
          justify-content: center;
}

<div id="timer"></div>


问:
Tumblr OAuth image post gives me 401/"Invalid OAuth credentials"
I've got an iOS app thats posts images to several services, including twitter and I'm trying to extend that support to tumblr. I've adapted some open source code for the OAuth 1.0a header logic and its working well enough to be successful for twitter + twitpic and for tumblr's authentication. However image posts to tumblr are failing with status 401 and string response "Invalid OAuth credentials"

To simplify, my only multipart sections are the post type and the image data.

So my simple POST is to http://www.tumblr.com/api/write, the signature base string is (roughly, as I’ve redacted my consumer key and token, and linebreaks added for readability):

```<code>POST&http%3A%2F%2Fwww.tumblr.com%2Fapi%2Fwrite&
oauth_consumer_key%3Dxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%26
oauth_nonce%3D71edd7a1224463a7e1723bb7b568060b4d69deb6%26
oauth_signature_method%3DHMAC-SHA1%26
oauth_timestamp%3D1297678418%26
oauth_token%3Dxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%26
oauth_version%3D1.0%26
type%3Dphoto
</code>```

my oauth header is (again, linebreaks added here for readability):

```<code>Authorization: OAuth realm="http://www.tumblr.com/",
oauth_consumer_key="xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
oauth_signature_method="HMAC-SHA1",
oauth_timestamp="1296445530",
oauth_nonce="71edd7a1224463a7e1723bb7b568060b4d69deb6",
oauth_version="1.0",
oauth_token="xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
oauth_signature="fWuli4eO3qVehfdeFzZN%2FDNYpFk%3D"
</code>```

the only other headers I’m adding are Content-Type (multipart/form-data) & Content-Length, and the message body is just:

```<code>--my_sorta_unique_boundary_string
Content-Disposition: form-data; name="type"

photo
--my_sorta_unique_boundary_string
Content-Disposition: form-data; name="data"
Content-Type: image/jpg
Content-Transfer-Encoding: binary

... (image data) ...
--my_sorta_unique_boundary_string--
</code>```

Can anyone tell me if I’ve done something wrong with my signature base string or auth header, or if there's some trick for getting tumblr oauth posts to work?

答:
Having exactly the same problem with my OAuth implementation in Silverlight - I've implemented the rest of the API without an issue, and this method works if you don't use OAuth and just send email/password headers as well.

Arvin's post just showed me the issue though, he's including the other non-file fields in his OAuth. I just did the same to my post, so they were in the multi-part form body but also being added to the OAuth sig - and now I'm uploading photo posts without a problem!

ContentLicense: CC BY-SA 2.5

Body:
I've got an iOS app thats posts images to several services, including twitter and I'm trying to extend that support to tumblr. I've adapted some open source code for the OAuth 1.0a header logic and its working well enough to be successful for twitter + twitpic and for tumblr's authentication. However image posts to tumblr are failing with status 401 and string response "Invalid OAuth credentials"

To simplify, my only multipart sections are the post type and the image data.

So my simple POST is to http://www.tumblr.com/api/write, the signature base string is (roughly, as I’ve redacted my consumer key and token, and linebreaks added for readability):

POST&http%3A%2F%2Fwww.tumblr.com%2Fapi%2Fwrite&
oauth_consumer_key%3Dxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%26
oauth_nonce%3D71edd7a1224463a7e1723bb7b568060b4d69deb6%26
oauth_signature_method%3DHMAC-SHA1%26
oauth_timestamp%3D1297678418%26
oauth_token%3Dxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx%26
oauth_version%3D1.0%26
type%3Dphoto

my oauth header is (again, linebreaks added here for readability):

Authorization: OAuth realm="http://www.tumblr.com/",
oauth_consumer_key="xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
oauth_signature_method="HMAC-SHA1",
oauth_timestamp="1296445530",
oauth_nonce="71edd7a1224463a7e1723bb7b568060b4d69deb6",
oauth_version="1.0",
oauth_token="xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
oauth_signature="fWuli4eO3qVehfdeFzZN%2FDNYpFk%3D"

the only other headers I’m adding are Content-Type (multipart/form-data) & Content-Length, and the message body is just:

--my_sorta_unique_boundary_string
Content-Disposition: form-data; name="type"

photo
--my_sorta_unique_boundary_string
Content-Disposition: form-data; name="data"
Content-Type: image/jpg
Content-Transfer-Encoding: binary

... (image data) ...
--my_sorta_unique_boundary_string--

Can anyone tell me if I’ve done something wrong with my signature base string or auth header, or if there's some trick for getting tumblr oauth posts to work?


答:
Just reorder some codes like this:

    var arr = [5, 4, 9, 6, 4];

    var sum = 0;

    arr.forEach(function(item) {
      console.log(sum)
      sum += parseInt(item);
    });```

Title: How to execute a loop with sequential summation?


问:
Convert dictionary's array to array of dictionary
Is there any possible ways to convert the following structure into a given structure

Input:-

```<code>var dic : [String:Array<Int>] = [
    "array1": [1,1,1],
    "array2": [2,2,2],
    "array3": [3,3,3]
]
</code>```

Expected output:-

```<code>var result = [
    [
        "array1" : 1,
        "array2" : 2,
        "array3" : 3
    ],[
        "array1" : 1,
        "array2" : 2,
        "array3" : 3
    ],[
        "array1" : 1,
        "array2" : 2,
        "array3" : 3
    ]
]
</code>```

答:
try this logic I hope it will work ... :)

```<code>var dic : [String:Array<Int>] = [
    "array1": [1,1,1],
    "array2": [2,2,2],
    "array3": [3,3,3]
]

var finalresult = Array<Any>()
var keys = Array(dic.keys)

for i in 0...dic["array1"]!.count-1{
   var arr2 = Array<Any>()
    for j in 0...keys.count-1{
        var arr1 = [String:Int]()

        arr1[keys[j]] = dic[keys[j]]![j]
        print(arr1)
        arr2.append(arr1)
    }
    print(arr2)
    finalresult.append(arr2)
}
print(finalresult)
</code>```

the final result is your output. :)

Body:
Is there any possible ways to convert the following structure into a given structure

Input:-

var dic : [String:Array<Int>] = [
    "array1": [1,1,1],
    "array2": [2,2,2],
    "array3": [3,3,3]
]

Expected output:-

var result = [
    [
        "array1" : 1,
        "array2" : 2,
        "array3" : 3
    ],[
        "array1" : 1,
        "array2" : 2,
        "array3" : 3
    ],[
        "array1" : 1,
        "array2" : 2,
        "array3" : 3
    ]
]

Body:
try this logic I hope it will work ... :)

var dic : [String:Array<Int>] = [
    "array1": [1,1,1],
    "array2": [2,2,2],
    "array3": [3,3,3]
]

var finalresult = Array<Any>()
var keys = Array(dic.keys)

for i in 0...dic["array1"]!.count-1{
   var arr2 = Array<Any>()
    for j in 0...keys.count-1{
        var arr1 = [String:Int]()

        arr1[keys[j]] = dic[keys[j]]![j]
        print(arr1)
        arr2.append(arr1)
    }
    print(arr2)
    finalresult.append(arr2)
}
print(finalresult)

the final result is your output. :)


答:
As mentioned in a comment, just move up the console log line, that gets you what you declared your desired outcome.

const arr = [5, 4, 9, 6, 4];

let sum = 0;

arr.forEach(function(item) {
  console.log(sum);
  sum += parseInt(item);
});```
</div>
</div>
</p>

<p>To achieve the same end result while logging the steps, you could also use <code>Array.prototype.reduce</code>. That would spare you to work on scoped variable, but instead simply assign the result of the reduce call to a variable.</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const arr = [5, 4, 9, 6, 4];

let sum = arr.reduce(function(accumulator, value) {
  console.log(accumulator)
  return accumulator += value
}, 0);

console.log(sum);</code>```

Body:
As mentioned in a comment, just move up the console log line, that gets you what you declared your desired outcome.

const arr = [5, 4, 9, 6, 4];

let sum = 0;

arr.forEach(function(item) {
  console.log(sum);
  sum += parseInt(item);
});

To achieve the same end result while logging the steps, you could also use Array.prototype.reduce. That would spare you to work on scoped variable, but instead simply assign the result of the reduce call to a variable.

const arr = [5, 4, 9, 6, 4];

let sum = arr.reduce(function(accumulator, value) {
  console.log(accumulator)
  return accumulator += value
}, 0);

console.log(sum);


问:
xdebug phpstorm docker linux
I can't catch any request with xdebug to my app.

xdebug.ini

```<code>zend_extension=xdebug.so
xdebug.remote_autostart = 1
xdebug.idekey=PHPSTORM
xdebug.remote_connect_back=1
xdebug.remote_enable=On
</code>```

答:
I see you've tagged this with "docker". If you use docker, you can't use xdebug.remote_connect_back=1. You need to specify xdebug.remote_host=IP-address-of-the-machine-as-reachable-by-docker-where-your-IDE-runs. This can be host.docker.internal in newer versions.

In order to further debug networking issues, please also set xdebug.remote_log=/tmp/xdebug.log in your php.ini settings, and see what it says when you initiate a debugging session (through a browser extension).

Title: xdebug phpstorm docker linux

Body:
I can't catch any request with xdebug to my app.

xdebug.ini

zend_extension=xdebug.so
xdebug.remote_autostart = 1
xdebug.idekey=PHPSTORM
xdebug.remote_connect_back=1
xdebug.remote_enable=On


答:
```<code>var arr = [5, 4, 9, 6, 4];

var sum = 0;

arr.forEach(function(item) {
  console.log(sum)
  sum += parseInt(item);
});
</code>```

Simple display your counter before you interfere with it. You result will always start with 0 though since you define sum to be 0 before your loop.

Your output now should look like what you asked.

Body:
var arr = [5, 4, 9, 6, 4];

var sum = 0;

arr.forEach(function(item) {
  console.log(sum)
  sum += parseInt(item);
});

Simple display your counter before you interfere with it. You result will always start with 0 though since you define sum to be 0 before your loop.

Your output now should look like what you asked.


问:
monospacedSystemFontOfSize:weight: Not available in iOS 12?
I'm using the method monospacedSystemFontOfSize:weight: of UIFont to get a system specific monospaced font, and according to SDK, it's available in iOS 12.0+:

https://developer.apple.com/documentation/uikit/uifont/3042484-monospacedsystemfont

however, I got a crash when running the app on iOS 12:

*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '+[UIFont monospacedSystemFontOfSize:weight:]: unrecognized selector sent to class 0x11a9547b0'

Did I miss something?

Thanks!

答: Documentation is wrong, it's only available in iOS13+. In Xcode 11.4, it's an error during compile time.</p>


答:
First log the sum value</p>

```<code>var arr = [5, 4, 9, 6, 4];

var sum = 0;

arr.forEach(function(item) {
  console.log(sum)
  sum += parseInt(item);
});
</code>```

Body:
First log the sum value

var arr = [5, 4, 9, 6, 4];

var sum = 0;

arr.forEach(function(item) {
  console.log(sum)
  sum += parseInt(item);
});


问:
Circle detection in a Image
I am trying to use HoughCircles method to detect a circle from an Image, but it looks like that this method is not useful to detect all circle with almost the same centres. For example, if I have 3 circles with almost the same centre it detects as a single circle. Please suggest if there is any way around to find all circles. Here is the source image:

I might be wrong with HoughCircle Methos assumption.

Thanks in advance.

答:
The reason is that when you call HoughCircles you should decide the minimum distance between the detected circle centerces. The same center you mentioned means that zero distance between them. So in this case you should set the minimum distance parameter almost 0.

```<code>void cv::HoughCircles   (   InputArray  image,
OutputArray     circles,
int     method,
double  dp,
double  minDist, // You should set this parameter almost zero cos 0 not accepted.
double  param1 = 100,
double  param2 = 100,
int     minRadius = 0,
int     maxRadius = 0
)
</code>```

When I tried with these parameters:

```<code>  HoughCircles( input, output, CV_HOUGH_GRADIENT, 1, 0.5, 60, 30, 1, 200 );
</code>```

I get this:

Edit: When I tried some more playing on this, I got 12 circles but the reality is 18 circles(edge circles not included). The reason could be about the image quality. Here is my code and result:

```<code>#include "opencv2/highgui/highgui.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include <iostream>
#include <stdio.h>
#include <stdlib.h>

using namespace cv;
using namespace std;

int main()
{
    /// Load source image and convert it to gray
    Mat src_gray,dst,src = imread("/ur/source/image/image.jpg", 1 );
    imshow("Source",src);
    int i = 50;
    bilateralFilter(src,dst,i,i*2,i/2);

    imshow("Output",dst);

    cvtColor( dst, src_gray, CV_BGR2GRAY );

    vector<Vec3f> circles;

    /// Apply the Hough Transform to find the circles
    HoughCircles( src_gray, circles, CV_HOUGH_GRADIENT, 1, 0.01, 80, 55, 0, 100 );

    Mat zero_mask = Mat::zeros(src.rows,src.cols,CV_8UC3);
    /// Draw the circles detected
    for( size_t i = 0; i < circles.size(); i++ )
    {
        Point center(cvRound(circles[i][0]), cvRound(circles[i][1]));
        int radius = cvRound(circles[i][2]);
        // circle center
        circle( zero_mask, center, 3, Scalar(0,255,0), -1, 8, 0 );
        // circle outline
        circle( zero_mask, center, radius, Scalar(0,0,255), 1, 8, 0 );
    }

    cout<<circles.size()<<endl;
    imshow("Output2",src_gray);
    imshow("outt",zero_mask);
    waitKey(0);
    return(0);
}
</code>```

Output:

Title: Circle detection in a Image

Body:
The reason is that when you call HoughCircles you should decide the minimum distance between the detected circle centerces. The same center you mentioned means that zero distance between them. So in this case you should set the minimum distance parameter almost 0.

void cv::HoughCircles   (   InputArray  image,
OutputArray     circles,
int     method,
double  dp,
double  minDist, // You should set this parameter almost zero cos 0 not accepted.
double  param1 = 100,
double  param2 = 100,
int     minRadius = 0,
int     maxRadius = 0
)

When I tried with these parameters:

  HoughCircles( input, output, CV_HOUGH_GRADIENT, 1, 0.5, 60, 30, 1, 200 );

I get this:

Edit: When I tried some more playing on this, I got 12 circles but the reality is 18 circles(edge circles not included). The reason could be about the image quality. Here is my code and result:

#include "opencv2/highgui/highgui.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include <iostream>
#include <stdio.h>
#include <stdlib.h>

using namespace cv;
using namespace std;

int main()
{
    /// Load source image and convert it to gray
    Mat src_gray,dst,src = imread("/ur/source/image/image.jpg", 1 );
    imshow("Source",src);
    int i = 50;
    bilateralFilter(src,dst,i,i*2,i/2);

    imshow("Output",dst);

    cvtColor( dst, src_gray, CV_BGR2GRAY );

    vector<Vec3f> circles;

    /// Apply the Hough Transform to find the circles
    HoughCircles( src_gray, circles, CV_HOUGH_GRADIENT, 1, 0.01, 80, 55, 0, 100 );

    Mat zero_mask = Mat::zeros(src.rows,src.cols,CV_8UC3);
    /// Draw the circles detected
    for( size_t i = 0; i < circles.size(); i++ )
    {
        Point center(cvRound(circles[i][0]), cvRound(circles[i][1]));
        int radius = cvRound(circles[i][2]);
        // circle center
        circle( zero_mask, center, 3, Scalar(0,255,0), -1, 8, 0 );
        // circle outline
        circle( zero_mask, center, radius, Scalar(0,0,255), 1, 8, 0 );
    }

    cout<<circles.size()<<endl;
    imshow("Output2",src_gray);
    imshow("outt",zero_mask);
    waitKey(0);
    return(0);
}

Output:


问:
What project would you recommend me to get up to speed with C++
I know that C++ is a very complex language that takes many years of practice to master.

Taking that into account do you know of a small project (around a 1k of loc) that tests all of C++ major features (inheritance, pointers, memory management, etc).

The thing is I'm a Java/Python programmer and I really want to learn C++ so I've been studying C++ for a while but haven't tested anything of what I've learned beyond small exercises.

I want to take all of that knowledge and put into practice.

答:
A memory manager. That should get you thinking about:

free store management

pointers (of course!)

inheritance (you will want your driver code to use this)

templates (another way to pass the manager around -- driver #2)

designing user defined data structures (a memory block)

efficient use of standard container(s)

algorithms (to move around, figure out empty blocks, defragment)

OwnerDisplayName: climatewarrior

OwnerDisplayName: dirkgently


问:
How to scale authorization for my resource management system
I have two systems

One Access management system where I store references of resources, users and access rights between them.

One Resource management system where I keep data about the resources and provide and an API to manage and query them.

When a request is received in the Resource management system, a query is sent to the Access management system to get a list of resource ids, to which the current user have access. This list is used as a criteria in the Resource Management PostgreSQL database when fetching data from it, so I only return results for data the user has access to.

This works fine in the small scale when a user have access up to a couple of hundred resources, but how do I scale this to work for users with access to 2000 or 20000 resources? I can't pass 20000 resource ids between my systems for every request!

答: You could possibly create a temporary table for the resource ids and make a join with the more permanent data in the db. It might be worth a try to see if it fits your use case.</p>


问:
Cross Account SNS Subscribe to Lambda in second account
I have used the below policy for the SNS topic to subscribe this SNS in Lambda with account number as 222222222222. I have also given access to my lambda with a similar policy adding it to the execution role of Lambda.

Getting the error below:

An error occurred when creating the trigger: User:
  arn:aws:sts::222222222222:assumed-role/TSI_Base_FullAccess/AXXXXXXXX
  is not authorized to perform: SNS:Subscribe on resource:
  arn:aws:sns:eu-west-1:111111111111:Story-5555 (Service: AmazonSNS;
  Status Code: 403; Error Code: AuthorizationError; Request ID:
  1321942c-25c4-52a1-bacb-c2e9bd641067)

```<code>{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "Stmt1582008007178",
      "Action": [
        "sns:GetSubscriptionAttributes",
        "sns:GetTopicAttributes",
        "sns:ListSubscriptions",
        "sns:ListSubscriptionsByTopic",
        "sns:ListTagsForResource",
        "sns:ListTopics",
        "sns:Publish",
        "sns:Subscribe"
      ],
      "Effect": "Allow",
      "Resource": "arn:aws:sns:eu-west-1:111111111111:Story-5555",
      "Condition": {
        "ArnEquals": {
          "aws:PrincipalArn": "arn:aws:lambda:eu-west-1:222222222222:function:New_Cross_SNS"
        }
      }
    }
  ]
}
</code>```

答:
According AWS Documentation you should specify principle additionally to the condition.

So your policy should resemble

```<code>{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "Stmt1582008007178",
      "Action": [
        "sns:GetSubscriptionAttributes",
        "sns:GetTopicAttributes",
        "sns:ListSubscriptions",
        "sns:ListSubscriptionsByTopic",
        "sns:ListTagsForResource",
        "sns:ListTopics",
        "sns:Publish",
        "sns:Subscribe"
      ],
      "Effect": "Allow",
      "Resource": "arn:aws:sns:eu-west-1:111111111111:Story-5555",
      "Principal": {
        "AWS": ["222222222222"]
      },
      "Condition": {
        "ArnEquals": {
          "aws:PrincipalArn": [
               "arn:aws:lambda:eu-west-1:222222222222:function:New_Cross_SNS",
               "arn:aws:sts::222222222222:assumed-role:TSI_Base_FullAccess:AXXXXXXXX"
          ]
        }
      }
    }
  ]
}
</code>```

The way to be sure which ARN to specify in the condition section of the policy is to call (and print) get-caller-identity API from your function.

Body:
I have used the below policy for the SNS topic to subscribe this SNS in Lambda with account number as 222222222222. I have also given access to my lambda with a similar policy adding it to the execution role of Lambda.

Getting the error below:

An error occurred when creating the trigger: User:
  arn:aws:sts::222222222222:assumed-role/TSI_Base_FullAccess/AXXXXXXXX
  is not authorized to perform: SNS:Subscribe on resource:
  arn:aws:sns:eu-west-1:111111111111:Story-5555 (Service: AmazonSNS;
  Status Code: 403; Error Code: AuthorizationError; Request ID:
  1321942c-25c4-52a1-bacb-c2e9bd641067)

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "Stmt1582008007178",
      "Action": [
        "sns:GetSubscriptionAttributes",
        "sns:GetTopicAttributes",
        "sns:ListSubscriptions",
        "sns:ListSubscriptionsByTopic",
        "sns:ListTagsForResource",
        "sns:ListTopics",
        "sns:Publish",
        "sns:Subscribe"
      ],
      "Effect": "Allow",
      "Resource": "arn:aws:sns:eu-west-1:111111111111:Story-5555",
      "Condition": {
        "ArnEquals": {
          "aws:PrincipalArn": "arn:aws:lambda:eu-west-1:222222222222:function:New_Cross_SNS"
        }
      }
    }
  ]
}

Body:
According AWS Documentation you should specify principle additionally to the condition.

So your policy should resemble

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "Stmt1582008007178",
      "Action": [
        "sns:GetSubscriptionAttributes",
        "sns:GetTopicAttributes",
        "sns:ListSubscriptions",
        "sns:ListSubscriptionsByTopic",
        "sns:ListTagsForResource",
        "sns:ListTopics",
        "sns:Publish",
        "sns:Subscribe"
      ],
      "Effect": "Allow",
      "Resource": "arn:aws:sns:eu-west-1:111111111111:Story-5555",
      "Principal": {
        "AWS": ["222222222222"]
      },
      "Condition": {
        "ArnEquals": {
          "aws:PrincipalArn": [
               "arn:aws:lambda:eu-west-1:222222222222:function:New_Cross_SNS",
               "arn:aws:sts::222222222222:assumed-role:TSI_Base_FullAccess:AXXXXXXXX"
          ]
        }
      }
    }
  ]
}

The way to be sure which ARN to specify in the condition section of the policy is to call (and print) get-caller-identity API from your function.


问:
Bad state: There were unclaimed errors, when create subscription in Google Play Console
I getting this error when create a subscription in Google Play Console.

Bad state: There were unclaimed errors, {global/VALIDATE_IN_APP_MESSAGE_INVALID_CURRENCY_FOR_DEFAULT_PRICE}

I try in old app and new app, but still no luck.
I have to test my subscription before release.

I send it to support but waiting for 3 days but not receive respond yet
any one have faced this problem ? Or could you please try in your account.
Thank you.

Google Play Console

答:
Looks like a bug in the console. I found an express method how to fix it.

First you need to create a price template.
Here you can find how to do it.
https://support.google.com/googleplay/android-developer/answer/6334373?p=pricing_template

And then you can use this template on the subscription page.
Good luck.


问:
How to improve font quality in SDL ttf and dynamically display text and numbers
I am building a 6502 emulator, and I wish to represent the cpu and memory states visually.

I am using SDL2 for this purpose. I have to render text on the SDL window as the 6502 cpu or memory changes states.

i.e I wish to show the entire memory content, current instruction being executed, previous cpu state, current cpu state in form of texts and numbers.

Here is my attempt to render a text using a font already present in my linux system.
Later I wish to render dynamic text and numbers instead of a static string.

```<code>#include<SDL2/SDL.h>
#include<SDL2/SDL_ttf.h>
#define SCREEN_HEIGHT 640
#define SCREEN_WIDTH 480
int quit=false;
SDL_Window *window;
SDL_Renderer *renderer;
int initializeDrawing(int argc,char** argv){
    if (SDL_Init(SDL_INIT_VIDEO) != 0){
        std::cout << "SDL_Init Error: " << SDL_GetError() << std::endl;
        return 1;
    }
    window = SDL_CreateWindow("6502 cpu display!", 100, 100, SCREEN_HEIGHT, SCREEN_WIDTH, SDL_WINDOW_SHOWN);
    if (window == nullptr){
        std::cout << "SDL_CreateWindow Error: " << SDL_GetError() << std::endl;
        SDL_Quit();
        return 1;
    }
    renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC);
    if (renderer == nullptr){
        SDL_DestroyWindow(window);
        std::cout << "SDL_CreateRenderer Error: " << SDL_GetError() << std::endl;
        SDL_Quit();
        return 1;
    }
    if (TTF_Init() != 0){
        SDL_Quit();
        return 1;
    }
    return 0;
}
void loop(){
    TTF_Font* Sans = TTF_OpenFont("./ttf/LH.ttf", 13);
    SDL_Color White = {255,255,255};
    SDL_Surface* surfaceMessage = TTF_RenderText_Solid(Sans, "0xABCEDFGHIJKLMNOPQRSTUVWXYZ", White);
    SDL_Texture* Message = SDL_CreateTextureFromSurface(renderer, surfaceMessage);

    SDL_Rect Message_rect;
    Message_rect.x = 0;
    Message_rect.y = 0;
    Message_rect.w = surfaceMessage->w;
    Message_rect.h = surfaceMessage->h;

    //loop
    SDL_Event e;
    while(!quit){
        SDL_PollEvent(&e);
        //If user closes the window
        if (e.type == SDL_QUIT){
            quit = true;
        }
        //First clear the renderer
        SDL_RenderClear(renderer);
        //Draw the texture
        SDL_RenderCopy(renderer, Message, NULL, &Message_rect);
        //Update the screen
        SDL_RenderPresent(renderer);
        //Take a quick break after all that hard work
    }
    SDL_DestroyRenderer(renderer);
    SDL_DestroyWindow(window);
    SDL_Quit();
}
</code>```

Here is the output

I wish to make the text more smaller and smoother.

I am looking for ideas on how to efficiently display numbers and text dynamically.

答:
SDL2_ttf has several different text rendering modes.

You are using the mode Solid which the documentation describes as "Quick and Dirty":

There are three modes of rendering:

Solid: Quick and Dirty

Create an 8-bit palettized surface and render the given text at fast quality with the given font and color. The pixel value of 0 is the colorkey, giving a transparent background when blitted. Pixel and colormap value 1 is set to the text foreground color. This allows you to change the color without having to render the text again. Palette index 0 is of course not drawn when blitted to another surface, since it is the colorkey, and thus transparent, though its actual color is 255 minus each of the RGB components of the foreground color. This is the fastest rendering speed of all the rendering modes. This results in no box around the text, but the text is not as smooth. The resulting surface should blit faster than the Blended one. Use this mode for FPS and other fast changing updating text displays.

Shaded: Slow and Nice, but with a Solid Box

Create an 8-bit palettized surface and render the given text at high quality with the given font and colors. The 0 pixel value is background, while other pixels have varying degrees of the foreground color from the background color. This results in a box of the background color around the text in the foreground color. The text is antialiased. This will render slower than Solid, but in about the same time as Blended mode. The resulting surface should blit as fast as Solid, once it is made. Use this when you need nice text, and can live with a box.

Blended: Slow Slow Slow, but Ultra Nice over another image

Create a 32-bit ARGB surface and render the given text at high quality, using alpha blending to dither the font with the given color. This results in a surface with alpha transparency, so you don't have a solid colored box around the text. The text is antialiased. This will render slower than Solid, but in about the same time as Shaded mode. The resulting surface will blit slower than if you had used Solid or Shaded. Use this when you want high quality, and the text isn't changing too fast.

If you want a higher quality rendering, you should try the *_Shaded or *_Blended functions.

Also note that you almost certainly want to use TTF_RenderUTF8 family of functions to make sure non-Latin characters are rendered correctly. (This may not be immediately relevant to your 6502 emulator, but it does not hurt and is good practice to do anyway.) More information: https://wiki.libsdl.org/SDL_ttf/TTF_RenderUTF8_Blended

Body:
I am building a 6502 emulator, and I wish to represent the cpu and memory states visually.

I am using SDL2 for this purpose. I have to render text on the SDL window as the 6502 cpu or memory changes states.

i.e I wish to show the entire memory content, current instruction being executed, previous cpu state, current cpu state in form of texts and numbers.

Here is my attempt to render a text using a font already present in my linux system.
Later I wish to render dynamic text and numbers instead of a static string.

#include<SDL2/SDL.h>
#include<SDL2/SDL_ttf.h>
#define SCREEN_HEIGHT 640
#define SCREEN_WIDTH 480
int quit=false;
SDL_Window *window;
SDL_Renderer *renderer;
int initializeDrawing(int argc,char** argv){
    if (SDL_Init(SDL_INIT_VIDEO) != 0){
        std::cout << "SDL_Init Error: " << SDL_GetError() << std::endl;
        return 1;
    }
    window = SDL_CreateWindow("6502 cpu display!", 100, 100, SCREEN_HEIGHT, SCREEN_WIDTH, SDL_WINDOW_SHOWN);
    if (window == nullptr){
        std::cout << "SDL_CreateWindow Error: " << SDL_GetError() << std::endl;
        SDL_Quit();
        return 1;
    }
    renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC);
    if (renderer == nullptr){
        SDL_DestroyWindow(window);
        std::cout << "SDL_CreateRenderer Error: " << SDL_GetError() << std::endl;
        SDL_Quit();
        return 1;
    }
    if (TTF_Init() != 0){
        SDL_Quit();
        return 1;
    }
    return 0;
}
void loop(){
    TTF_Font* Sans = TTF_OpenFont("./ttf/LH.ttf", 13);
    SDL_Color White = {255,255,255};
    SDL_Surface* surfaceMessage = TTF_RenderText_Solid(Sans, "0xABCEDFGHIJKLMNOPQRSTUVWXYZ", White);
    SDL_Texture* Message = SDL_CreateTextureFromSurface(renderer, surfaceMessage);

    SDL_Rect Message_rect;
    Message_rect.x = 0;
    Message_rect.y = 0;
    Message_rect.w = surfaceMessage->w;
    Message_rect.h = surfaceMessage->h;

    //loop
    SDL_Event e;
    while(!quit){
        SDL_PollEvent(&e);
        //If user closes the window
        if (e.type == SDL_QUIT){
            quit = true;
        }
        //First clear the renderer
        SDL_RenderClear(renderer);
        //Draw the texture
        SDL_RenderCopy(renderer, Message, NULL, &Message_rect);
        //Update the screen
        SDL_RenderPresent(renderer);
        //Take a quick break after all that hard work
    }
    SDL_DestroyRenderer(renderer);
    SDL_DestroyWindow(window);
    SDL_Quit();
}

Here is the output

I wish to make the text more smaller and smoother.

I am looking for ideas on how to efficiently display numbers and text dynamically.


问:
Grouping a collection with the related objects
I have a group of tasks where a task may be linked to another one via the runs_with field as shown below.

```<code><Task id: 'abc', name: 'paint the fance', progressive: 1, runs_with: nil>
<Task id: 'def', name: 'mow the lawn', progressive: 2, runs_with: 1>
<Task id: 'ghi', name: 'wash the dishes', progressive: 3, runs_with: nil>
<Task id: 'xyz', name: 'take out the trash', progressive: 4, runs_with: 3>
<Task id: 'qur', name: 'wash the car', progressive: 5, runs_with: 2>
<Task id: 'gbj', name: 'walk the dog', progressive: 6, runs_with: 3>
</code>```

Now I need to group them so all the linked ones end up in a group (an array).

```<code>[[<Task id: 'abc', name: 'paint the fance', progressive: 1, runs_with: nil>,
  <Task id: 'def', name: 'mow the lawn', progressive: 2, runs_with: 1>,
  <Task id: 'qur', name: 'wash the car', progressive: 5, runs_with: 2>],
 [<Task id: 'ghi', name: 'wash the dishes', progressive: 3, runs_with: nil>,
  <Task id: 'xyz', name: 'take out the trash', progressive: 4, runs_with: 3>,
  <Task id: 'gbj', name: 'walk the dog', progressive: 6, runs_with: 3>]]
</code>```

My initial idea is to

partition on runs_with.

create a group for each task that can run alone.

loop through the other tasks and append them to the group including the linked task.

Wondering if there is any more idiomatic way to group them.

答:
I think

```<code>tasks.group_by(&:runs_with).values
</code>```

should do it.

Basically the groups_by method will create a hash where the runs_with value is the key and the value is an array of all the tasks with that runs_with value. Then you simple call values on the hash to get an array of all values.

Body:
I have a group of tasks where a task may be linked to another one via the runs_with field as shown below.

<Task id: 'abc', name: 'paint the fance', progressive: 1, runs_with: nil>
<Task id: 'def', name: 'mow the lawn', progressive: 2, runs_with: 1>
<Task id: 'ghi', name: 'wash the dishes', progressive: 3, runs_with: nil>
<Task id: 'xyz', name: 'take out the trash', progressive: 4, runs_with: 3>
<Task id: 'qur', name: 'wash the car', progressive: 5, runs_with: 2>
<Task id: 'gbj', name: 'walk the dog', progressive: 6, runs_with: 3>

Now I need to group them so all the linked ones end up in a group (an array).

[[<Task id: 'abc', name: 'paint the fance', progressive: 1, runs_with: nil>,
  <Task id: 'def', name: 'mow the lawn', progressive: 2, runs_with: 1>,
  <Task id: 'qur', name: 'wash the car', progressive: 5, runs_with: 2>],
 [<Task id: 'ghi', name: 'wash the dishes', progressive: 3, runs_with: nil>,
  <Task id: 'xyz', name: 'take out the trash', progressive: 4, runs_with: 3>,
  <Task id: 'gbj', name: 'walk the dog', progressive: 6, runs_with: 3>]]

My initial idea is to

partition on runs_with.

create a group for each task that can run alone.

loop through the other tasks and append them to the group including the linked task.

Wondering if there is any more idiomatic way to group them.

Body:
I think

tasks.group_by(&:runs_with).values

should do it.

Basically the groups_by method will create a hash where the runs_with value is the key and the value is an array of all the tasks with that runs_with value. Then you simple call values on the hash to get an array of all values.


问:
BigQuery scheduled query: Cannot create a transfer in > JURISDICTION_US when destination dataset is located in > REGION_ASIA_SOUTHEAST_1
I am getting this error quite frequently while trying to create a scheduled query

Error creating scheduled query: Cannot create a transfer in
  JURISDICTION_US when destination dataset is located in
  REGION_ASIA_SOUTHEAST_1

I just need a scheduled query to overwrite data in a table.

答: As I tried, it may happen because I have existed table with the same id as the destination table. This happens even if the table is the result of manually running that query and saved.</p>


问:
Android Sqlite trigger operation go through

This is my first table it has 3 columns and all are entered by the user. No complication and it works fine. But there is another table and it is dependent on this table 3rd column. i.e. on room number column. Please ignore the names convention as i have not really followed any naming conventions.

This is my second table and as you can see it has its last column as room number. please ignore name convention. this room number column is foreign key it is dependent on the 1st table entry or delete
Now I have created a schema for the 2nd table. which declares that it has 5 columns and the last one is the foreign key.

```<code> private static final String DATABASE_CREATE_NOTES_ID_TABLE =
    ("CREATE TABLE "+ DATABASE_NOTES_TABLE +" ("+ KEY_ROWID +" INTEGER PRIMARY KEY AUTOINCREMENT, "+
            KEY_TIME + " TEXT, "+
            KEY_NOTES + " TEXT, "+
            KEY_DATE +  " TEXT, " +
            KEY_ROOMS + " INTEGER , FOREIGN KEY (" + KEY_ROOMS + ") REFERENCES " + DATABASE_PATIENT_TABLE +" (" +KEY_ROOM_NUMBER+ "));");
</code>```

Tables as you see is getting created successfully.
Now I have to write a TRIGGER statement, based on that when I delete a room number from the first table, then all the rows in the 2nd table which has the same room number should be deleted. And If I add a new room number in the first table then it should be added in the 2nd table.
The trigger statement for insert of new room number that I have written is as follows

```<code>    db.execSQL("CREATE TRIGGER fk_notesTable_roomNumber " +
                " BEFORE INSERT "+
                " ON "+DATABASE_NOTES_TABLE+
                " FOR EACH ROW BEGIN"+
                " SELECT CASE WHEN ((SELECT "+KEY_ROOM_NUMBER+" FROM "+DATABASE_PATIENT_TABLE+" WHERE "+KEY_ROOM_NUMBER+"=new."+KEY_ROOMS +" ) IS NULL)"+
                " THEN RAISE (ABORT,'Foreign Key Violation') END;"+
                "  END;");
</code>```

This piece of code I have added in the onCreate() of my database file. What else do I do ? Nothing is happening here.
Please kindly point me out where I am making mistake.
Thanks in tons,
Shaista

答:
You have added an INSERT trigger. This raises an error if you try and insert a row that doesn't match the constraint specified in the trigger; it does nothing about deleting rows from one table when rows from another are deleted.

You need an AFTER DELETE trigger on the first table which deletes the corresponding rows.

Body:
This is my first table it has 3 columns and all are entered by the user. No complication and it works fine. But there is another table and it is dependent on this table 3rd column. i.e. on room number column. Please ignore the names convention as i have not really followed any naming conventions.

This is my second table and as you can see it has its last column as room number. please ignore name convention. this room number column is foreign key it is dependent on the 1st table entry or delete
Now I have created a schema for the 2nd table. which declares that it has 5 columns and the last one is the foreign key.

 private static final String DATABASE_CREATE_NOTES_ID_TABLE =
    ("CREATE TABLE "+ DATABASE_NOTES_TABLE +" ("+ KEY_ROWID +" INTEGER PRIMARY KEY AUTOINCREMENT, "+
            KEY_TIME + " TEXT, "+
            KEY_NOTES + " TEXT, "+
            KEY_DATE +  " TEXT, " +
            KEY_ROOMS + " INTEGER , FOREIGN KEY (" + KEY_ROOMS + ") REFERENCES " + DATABASE_PATIENT_TABLE +" (" +KEY_ROOM_NUMBER+ "));");

Tables as you see is getting created successfully.
Now I have to write a TRIGGER statement, based on that when I delete a room number from the first table, then all the rows in the 2nd table which has the same room number should be deleted. And If I add a new room number in the first table then it should be added in the 2nd table.
The trigger statement for insert of new room number that I have written is as follows

    db.execSQL("CREATE TRIGGER fk_notesTable_roomNumber " +
                " BEFORE INSERT "+
                " ON "+DATABASE_NOTES_TABLE+
                " FOR EACH ROW BEGIN"+
                " SELECT CASE WHEN ((SELECT "+KEY_ROOM_NUMBER+" FROM "+DATABASE_PATIENT_TABLE+" WHERE "+KEY_ROOM_NUMBER+"=new."+KEY_ROOMS +" ) IS NULL)"+
                " THEN RAISE (ABORT,'Foreign Key Violation') END;"+
                "  END;");

This piece of code I have added in the onCreate() of my database file. What else do I do ? Nothing is happening here.
Please kindly point me out where I am making mistake.
Thanks in tons,
Shaista


问:
Kubernetes pods graceful shutdown with TCP connections (Spring boot)
I am hosting my services on azure cloud, sometimes I get "BackendConnectionFailure" without any apparent reason, after investigation I found a correlation between this exception and autoscale (scaling down) almost at the same second in most of the cases.

According to documentation termination grace period by default is 30 seconds, which is the case. The pod will be marked terminating and the loadbalancer will not consider it anymore, so receiving no more requests. According to this if my service takes far less time than 30 seconds, I should not need prestop hook or any special implementation in my application (please correct me if I am wrong).

If the previous paragraph is correct, why does this exception occur relatively frequent? My thought is when the pod is marked terminating and the loadbalancer does not forward anymore requests to the pod while it should do.

Edit 1:

The Architecture is simply like this

Client -> Firewall(azure) -> API(azure APIM) -> Microservices(Spring boot) -> backend(third party) or azure RDB depending on the service

I think the Exception comes from APIM, I found two patterns for this exception:

Message   The underlying connection was closed: The connection was closed unexpectedly.
Exception type  BackendConnectionFailure
Failed method   forward-request

Response time  10.0 s

Message    The underlying connection was closed: A connection that was expected to be kept alive was closed by the server.
Exception type  BackendConnectionFailure
Failed method   forward-request

Response time  3.6 ms

答: You can use a preStop sleep if needed. While the pod is removed from the service endpoints immediately, it still takes time (10-100ms) for the endpoint update to be sent to every node and for them to update iptables.</p>


问:
Check if pandas column contains only 0's or 1's
I want to know if there is a way to check whether a pandas column contains only 0's or 1's. This can be done using df.groupby('col').count() and then verifying that there are only two indices and checking if 0 and 1 are part of the index. Is there a better way?

答:
You could use unique() which would return all the unique values from a column

For e.g.

```<code>#List unique values in the df['name'] column
df.name.unique()
</code>```

This would return an array of unique values present in that column

Body:
You could use unique() which would return all the unique values from a column

For e.g.

#List unique values in the df['name'] column
df.name.unique()

This would return an array of unique values present in that column


问:
How to handle "invalid use of non-static data member" in class Implementation in c++?
I've been trying to solve a question Word Search II on LeetCode that requires use of Trie to help make the backtracking calls more efficient and basically tries are to be used, I've been trying to implement my own trie class but I'm running into a road block in my remove function, it requires a copy of root, but I'm not sure how to give it one. Here is the part I'm having trouble with:

TrieNode* crawl = root in the function remove(string word, TrieNode* crawl = root, int depth = 0)

The error: invalid use of non-static data member 'Trie::root'

I don't know the correct way to do it.

```<code>TrieNode* remove(string word, TrieNode* crawl = root, int depth = 0) {
    if(!crawl) return nullptr;

    if(depth == word.size()) {
        if(crawl->isLeaf) crawl->isLeaf = false;
        if(isEmpty(crawl)) {
            delete crawl;
            crawl = nullptr;
        }
        return crawl;
    }

    int index = word[depth] - 'a';
    crawl->arr[index] = remove(word, crawl->arr[index], depth + 1);

    if(isEmpty(crawl) && crawl->isLeaf == false) {
        delete crawl;
        crawl = nullptr;
    }

    return crawl;
}
</code>```

This is what my Trie class looks like:

```<code>class Trie {
    private:
        TrieNode* root;

    public:
        Trie() : root(new TrieNode()) {};

        void insert(const string &word) {
            auto crawl = root;
            // does it's thing
        }

        bool search(const string &word) {
            auto crawl = root;
            // does it's thing
        }

        bool isPrefix(const string &word) {
            auto crawl = root;
            // does it's thing
        }

        bool isEmpty(TrieNode* root) {
            for(int i = 0; i < 26; i++) if(root->arr[i]) return false;
            return true;
        }

        TrieNode* remove(string word, TrieNode* crawl = root, int depth = 0) {
</code>```

With this as the TrieNode:

```<code>struct TrieNode {
    bool isLeaf;
    vector<TrieNode*> arr;
    TrieNode() : isLeaf(false), arr(26, nullptr) {};
};
</code>```

Edit: Special thanks to @SPD for suggesting an improvement on the remove function

答:
You can't use member variables as default arguments.

However instead of:

```<code>TrieNode* remove(string word, TrieNode* crawl = root, int depth = 0) {
//...
</code>```

You could do

```<code>TrieNode* remove(string word, TrieNode* crawl = nullptr, int depth = 0) {
  if (!crawl) {
    crawl = root;
  }
  //...
</code>```

Body:
I've been trying to solve a question Word Search II on LeetCode that requires use of Trie to help make the backtracking calls more efficient and basically tries are to be used, I've been trying to implement my own trie class but I'm running into a road block in my remove function, it requires a copy of root, but I'm not sure how to give it one. Here is the part I'm having trouble with:

TrieNode* crawl = root in the function remove(string word, TrieNode* crawl = root, int depth = 0)

The error: invalid use of non-static data member 'Trie::root'

I don't know the correct way to do it.

TrieNode* remove(string word, TrieNode* crawl = root, int depth = 0) {
    if(!crawl) return nullptr;

    if(depth == word.size()) {
        if(crawl->isLeaf) crawl->isLeaf = false;
        if(isEmpty(crawl)) {
            delete crawl;
            crawl = nullptr;
        }
        return crawl;
    }

    int index = word[depth] - 'a';
    crawl->arr[index] = remove(word, crawl->arr[index], depth + 1);

    if(isEmpty(crawl) && crawl->isLeaf == false) {
        delete crawl;
        crawl = nullptr;
    }

    return crawl;
}

This is what my Trie class looks like:

class Trie {
    private:
        TrieNode* root;

    public:
        Trie() : root(new TrieNode()) {};

        void insert(const string &word) {
            auto crawl = root;
            // does it's thing
        }

        bool search(const string &word) {
            auto crawl = root;
            // does it's thing
        }

        bool isPrefix(const string &word) {
            auto crawl = root;
            // does it's thing
        }

        bool isEmpty(TrieNode* root) {
            for(int i = 0; i < 26; i++) if(root->arr[i]) return false;
            return true;
        }

        TrieNode* remove(string word, TrieNode* crawl = root, int depth = 0) {

With this as the TrieNode:

struct TrieNode {
    bool isLeaf;
    vector<TrieNode*> arr;
    TrieNode() : isLeaf(false), arr(26, nullptr) {};
};

Edit: Special thanks to @SPD for suggesting an improvement on the remove function

Body:
You can't use member variables as default arguments.

However instead of:

TrieNode* remove(string word, TrieNode* crawl = root, int depth = 0) {
//...

You could do

TrieNode* remove(string word, TrieNode* crawl = nullptr, int depth = 0) {
  if (!crawl) {
    crawl = root;
  }
  //...