问:
Getting Frequent org.apache.flink.runtime.jobmanager.scheduler.NoResourceAvailableException in Flink Session mode
We were facing lot of TMs timeout exception during job restart. To fix that issue we have set TM timeout to 1 hour. We started noticing that in Flink Session mode whenever we submit job with old existing TMs, it starts giving NoSlotAvaialble exception. This is specific with Flink Session mode, It is working fine with Flink Per job mode. Any input on how can we fix that?</p>
```<code>resourcemanager.taskmanager-timeout: 3600000
 akka.ask.timeout: 300s
 web.timeout: 300000

java.util.concurrent.CompletionException: java.util.concurrent.CompletionException: org.apache.flink.runtime.jobmanager.scheduler.NoResourceAvailableException: Slot request bulk is not fulfillable! Could not allocate the required slot within slot request timeout
    at org.apache.flink.runtime.scheduler.DefaultScheduler.lambda$assignResource$8(DefaultScheduler.java:515)
    at java.util.concurrent.CompletableFuture.uniHandle(CompletableFuture.java:836)
    at java.util.concurrent.CompletableFuture$UniHandle.tryFire(CompletableFuture.java:811)
    at java.util.concurrent.CompletableFuture.postComplete(CompletableFuture.java:488)
    at java.util.concurrent.CompletableFuture.completeExceptionally(CompletableFuture.java:1990)
    at org.apache.flink.runtime.scheduler.SharedSlot.cancelLogicalSlotRequest(SharedSlot.java:222)
</code>```

Body:
We were facing lot of TMs timeout exception during job restart. To fix that issue we have set TM timeout to 1 hour. We started noticing that in Flink Session mode whenever we submit job with old existing TMs, it starts giving NoSlotAvaialble exception. This is specific with Flink Session mode, It is working fine with Flink Per job mode. Any input on how can we fix that?

resourcemanager.taskmanager-timeout: 3600000
 akka.ask.timeout: 300s
 web.timeout: 300000

java.util.concurrent.CompletionException: java.util.concurrent.CompletionException: org.apache.flink.runtime.jobmanager.scheduler.NoResourceAvailableException: Slot request bulk is not fulfillable! Could not allocate the required slot within slot request timeout
    at org.apache.flink.runtime.scheduler.DefaultScheduler.lambda$assignResource$8(DefaultScheduler.java:515)
    at java.util.concurrent.CompletableFuture.uniHandle(CompletableFuture.java:836)
    at java.util.concurrent.CompletableFuture$UniHandle.tryFire(CompletableFuture.java:811)
    at java.util.concurrent.CompletableFuture.postComplete(CompletableFuture.java:488)
    at java.util.concurrent.CompletableFuture.completeExceptionally(CompletableFuture.java:1990)
    at org.apache.flink.runtime.scheduler.SharedSlot.cancelLogicalSlotRequest(SharedSlot.java:222)


来源: stackexchange

问:
Duplicate a tab across multiple workbooks in google
I'm hoping someone can help me with this?
I have multiple spreadsheets in a file all with a tab named after the week start date.
What i want to do is duplicate this tab in all the spreadsheets with one google script.

At present I have a macro linked button in each spreadsheet with the following code -

```<code>function NewWeek() {
  const sh = SpreadsheetApp.getActive();
  let ss = sh.duplicateActiveSheet();
  let name = ss.getRange("E4").getDisplayValue();

  ss.setName(name);
}
</code>```

Is there a way for me to have this run across all spreadsheets without having to open them individually and run the macro?

Any help would be most appreciated.

ContentLicense: CC BY-SA 4.0

Body:
I'm hoping someone can help me with this?
I have multiple spreadsheets in a file all with a tab named after the week start date.
What i want to do is duplicate this tab in all the spreadsheets with one google script.

At present I have a macro linked button in each spreadsheet with the following code -

function NewWeek() {
  const sh = SpreadsheetApp.getActive();
  let ss = sh.duplicateActiveSheet();
  let name = ss.getRange("E4").getDisplayValue();

  ss.setName(name);
}

Is there a way for me to have this run across all spreadsheets without having to open them individually and run the macro?

Any help would be most appreciated.


问:
How to filter by dayOfWeek in mongodb node.js
I'm new at this, I need to get all the persons from the db that matches the day of the week of the attribute createdAt (a Date) and a day of the week obtained through a parameter in the request. My data model is:

```<code>const personSchema = new mongoose.Schema({
    firstName: {
        required: true,
        type: String
    },
    lastName: {
        required: true,
        type: String
    },
    age: {
        required: true,
        type: Number
    },
    email: {
        type: String
    },
    createdAt: {
        type: Date,
        default: Date.now
    }
})
</code>```

I'm working with MongoDB and Node.js

I've tried this:

```<code>        const people = await Person.aggregate(
            [{
                $addFields: {
                    dayyOfWeek: {
                        $dayOfWeek: "$createdAt"
                    }
                }
            }, {
                $match: {
                    dayyOfWeek: {
                        $eq: req.params.weekday
                    }
                }
            }]
        )
</code>```

and tried too with $where and $function in the find function, but it goes wrong because that gives me an error, "MongoError: $where is not allowed in this atlas tier"

Body:
I'm new at this, I need to get all the persons from the db that matches the day of the week of the attribute createdAt (a Date) and a day of the week obtained through a parameter in the request. My data model is:

const personSchema = new mongoose.Schema({
    firstName: {
        required: true,
        type: String
    },
    lastName: {
        required: true,
        type: String
    },
    age: {
        required: true,
        type: Number
    },
    email: {
        type: String
    },
    createdAt: {
        type: Date,
        default: Date.now
    }
})

I'm working with MongoDB and Node.js

I've tried this:

        const people = await Person.aggregate(
            [{
                $addFields: {
                    dayyOfWeek: {
                        $dayOfWeek: "$createdAt"
                    }
                }
            }, {
                $match: {
                    dayyOfWeek: {
                        $eq: req.params.weekday
                    }
                }
            }]
        )

and tried too with $where and $function in the find function, but it goes wrong because that gives me an error, "MongoError: $where is not allowed in this atlas tier"


问:
google places -- autocomplete renturn UNKNOWN_ERROR
Description:

Occasionally, a 500 error will occur on this interface. When I make the request again with the same input parameter, it is normal and cannot be reproduced. The official document does not give an explanation, prompting UNKNOWN_ERROR

api-url: https://maps.googleapis.com/maps/api/place/autocomplete/json

```<code>request:
{
"input":"東京灣伊",
"key":"XXXXXX",
"sessiontoken":"ceabe5d0-604d-4273-b8a9-5da90b6b2960",
"location":"22.3193039,114.1693611",
"language":"zh-TW"
}
</code>```

response rawStatusCode:500
response body:

```<code>{
   "predictions" : [],
   "status" : "UNKNOWN_ERROR"
}
</code>```

Please help, thanks~

Body:
Description:

Occasionally, a 500 error will occur on this interface. When I make the request again with the same input parameter, it is normal and cannot be reproduced. The official document does not give an explanation, prompting UNKNOWN_ERROR

api-url: https://maps.googleapis.com/maps/api/place/autocomplete/json

request:
{
"input":"東京灣伊",
"key":"XXXXXX",
"sessiontoken":"ceabe5d0-604d-4273-b8a9-5da90b6b2960",
"location":"22.3193039,114.1693611",
"language":"zh-TW"
}

response rawStatusCode:500
response body:

{
   "predictions" : [],
   "status" : "UNKNOWN_ERROR"
}

Please help, thanks~


问:
How to extend YouTubeBaseActivity in a page that's already extend Fragment? - Android Studio
My application is about to produce a slide pages like tab layout and all the pages need to display a video from YouTube. When I drag YouTubePlayerView into the design page, it doesn't show the design; the design page is entirely blank. I've created the tab layout and connected the YouTube API in my project. When I search what's the problem, its showing the java file can't extend 2 classes, which is YouTubeBaseActivity and Fragment class. I'm not sure how to fix it. I need to know where to change the Fragment. And, why the view is not showing in the design of interface? It's blank.

This is my Homepage.java code

```<code>
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import androidx.viewpager.widget.ViewPager;
import com.google.android.material.tabs.TabLayout;

public class Homepage extends AppCompatActivity {

    private ViewPagerAdapter viewPagerAdapter;
    private ViewPager viewPager;
    private TabLayout tabLayout;

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

        viewPager = findViewById(R.id.viewpager);

        viewPagerAdapter = new ViewPagerAdapter(getSupportFragmentManager());

        viewPagerAdapter.add(new Page1(), "Page 1");
        viewPagerAdapter.add(new Page2(), "Page 2");
        viewPagerAdapter.add(new Page3(), "Page 3");

        viewPager.setAdapter(viewPagerAdapter);

        tabLayout = findViewById(R.id.tab_layout);
        tabLayout.setupWithViewPager(viewPager);
    }
}
</code>```

This is my ViewPagerAdapter.java page

```<code>import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentPagerAdapter;
import java.util.ArrayList;
import java.util.List;

public class ViewPagerAdapter extends FragmentPagerAdapter {

    private final List<Fragment> fragments = new ArrayList<>();
    private final List<String> fragmentTitle = new ArrayList<>();

    public ViewPagerAdapter(@NonNull FragmentManager fm) {

        super(fm);
    }

    public void add(Fragment fragment, String title) {
        fragments.add(fragment);
        fragmentTitle.add(title);
    }

    @NonNull
    @Override
    public Fragment getItem(int position) {

        return fragments.get(position);
    }

    @Override
    public int getCount() {

        return fragments.size();
    }

    @Nullable
    @Override
    public CharSequence getPageTitle(int position) {

        return fragmentTitle.get(position);
    }
}
</code>```

This is my Page 1.java page

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

import androidx.fragment.app.Fragment;

import com.google.android.youtube.player.YouTubeInitializationResult;
import com.google.android.youtube.player.YouTubePlayer;
import com.google.android.youtube.player.YouTubePlayerView;

public class Page1 extends Fragment {

    private static final String TAG = "Page1";

    YouTubePlayerView YouTube1;
    Button btnPlay1;
    YouTubePlayer.OnInitializedListener OnInitializedListener;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_page1, container, false);
        Log.d(TAG, "onCreate: Starting.");
        btnPlay1 = rootView.findViewById(R.id.btnPlay1);
        YouTube1 =  rootView.findViewById(R.id.YouTube1);

        OnInitializedListener = new YouTubePlayer.OnInitializedListener() {
            @Override
            public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer youTubePlayer, boolean b) {
                Log.d(TAG, "onClick: Done initializing.");

                youTubePlayer.loadVideo("Video ID");
            }

            @Override
            public void onInitializationFailure(YouTubePlayer.Provider provider, YouTubeInitializationResult youTubeInitializationResult) {
                Log.d(TAG, "onClick: Failed to initialize;");
            }
        };

        btnPlay1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.d(TAG, "onClick: Initializing YouTube Player.");
                YouTube1.initialize(YouTubeConfig.getApiKey(),OnInitializedListener);
            }
        });

        return rootView;
    }

}
</code>```

This is my fragment_page1.xml page

```<code><?xml version="1.0" encoding="utf-8"?>
<FrameLayout
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#FFFFFF"
    android:orientation="vertical"
    tools:context=".Page1">

    <androidx.constraintlayout.widget.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <TextView
            android:id="@+id/textView5"
            android:layout_width="330dp"
            android:layout_height="51dp"
            android:background="#000000"
            android:fontFamily="@font/aldrich"
            android:gravity="center"
            android:text="@string/daily_uploads"
            android:textColor="#F5A900"
            android:textSize="36sp"
            android:textStyle="bold"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent"
            app:layout_constraintVertical_bias="0.023" />

        <view
            android:id="@+id/YouTube1"
            class="com.google.android.youtube.player.YouTubePlayerView"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginEnd="3dp"
            android:layout_marginBottom="3dp"
            app:layout_constraintBottom_toTopOf="@+id/textView5"
            app:layout_constraintEnd_toStartOf="@+id/textView5"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent" />

        <TextView
            android:id="@+id/textView"
            android:layout_width="359dp"
            android:layout_height="52dp"
            android:fontFamily="@font/aldrich"
            android:text="@string/a_small_paragraph_about_the_video_playing"
            android:textAlignment="center"
            android:textColor="@color/black"
            android:textSize="18sp"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintHorizontal_bias="0.48"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent"
            app:layout_constraintVertical_bias="0.702" />

        <Button
            android:id="@+id/btnPlay1"
            android:layout_width="231dp"
            android:layout_height="63dp"
            android:background="#F5A900"
            android:fontFamily="@font/aldrich"
            android:text="@string/play_video"
            android:textAlignment="center"
            android:textColor="#000000"
            android:textSize="24sp"
            android:textStyle="bold"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent"
            app:layout_constraintVertical_bias="0.878" />

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

Body:
My application is about to produce a slide pages like tab layout and all the pages need to display a video from YouTube. When I drag YouTubePlayerView into the design page, it doesn't show the design; the design page is entirely blank. I've created the tab layout and connected the YouTube API in my project. When I search what's the problem, its showing the java file can't extend 2 classes, which is YouTubeBaseActivity and Fragment class. I'm not sure how to fix it. I need to know where to change the Fragment. And, why the view is not showing in the design of interface? It's blank.

This is my Homepage.java code

import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import androidx.viewpager.widget.ViewPager;
import com.google.android.material.tabs.TabLayout;

public class Homepage extends AppCompatActivity {

    private ViewPagerAdapter viewPagerAdapter;
    private ViewPager viewPager;
    private TabLayout tabLayout;

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

        viewPager = findViewById(R.id.viewpager);

        viewPagerAdapter = new ViewPagerAdapter(getSupportFragmentManager());

        viewPagerAdapter.add(new Page1(), "Page 1");
        viewPagerAdapter.add(new Page2(), "Page 2");
        viewPagerAdapter.add(new Page3(), "Page 3");

        viewPager.setAdapter(viewPagerAdapter);

        tabLayout = findViewById(R.id.tab_layout);
        tabLayout.setupWithViewPager(viewPager);
    }
}

This is my ViewPagerAdapter.java page

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentPagerAdapter;
import java.util.ArrayList;
import java.util.List;

public class ViewPagerAdapter extends FragmentPagerAdapter {

    private final List<Fragment> fragments = new ArrayList<>();
    private final List<String> fragmentTitle = new ArrayList<>();

    public ViewPagerAdapter(@NonNull FragmentManager fm) {

        super(fm);
    }

    public void add(Fragment fragment, String title) {
        fragments.add(fragment);
        fragmentTitle.add(title);
    }

    @NonNull
    @Override
    public Fragment getItem(int position) {

        return fragments.get(position);
    }

    @Override
    public int getCount() {

        return fragments.size();
    }

    @Nullable
    @Override
    public CharSequence getPageTitle(int position) {

        return fragmentTitle.get(position);
    }
}

This is my Page 1.java page

import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;

import androidx.fragment.app.Fragment;

import com.google.android.youtube.player.YouTubeInitializationResult;
import com.google.android.youtube.player.YouTubePlayer;
import com.google.android.youtube.player.YouTubePlayerView;

public class Page1 extends Fragment {

    private static final String TAG = "Page1";

    YouTubePlayerView YouTube1;
    Button btnPlay1;
    YouTubePlayer.OnInitializedListener OnInitializedListener;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_page1, container, false);
        Log.d(TAG, "onCreate: Starting.");
        btnPlay1 = rootView.findViewById(R.id.btnPlay1);
        YouTube1 =  rootView.findViewById(R.id.YouTube1);

        OnInitializedListener = new YouTubePlayer.OnInitializedListener() {
            @Override
            public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer youTubePlayer, boolean b) {
                Log.d(TAG, "onClick: Done initializing.");

                youTubePlayer.loadVideo("Video ID");
            }

            @Override
            public void onInitializationFailure(YouTubePlayer.Provider provider, YouTubeInitializationResult youTubeInitializationResult) {
                Log.d(TAG, "onClick: Failed to initialize;");
            }
        };

        btnPlay1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.d(TAG, "onClick: Initializing YouTube Player.");
                YouTube1.initialize(YouTubeConfig.getApiKey(),OnInitializedListener);
            }
        });

        return rootView;
    }

}

This is my fragment_page1.xml page

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#FFFFFF"
    android:orientation="vertical"
    tools:context=".Page1">

    <androidx.constraintlayout.widget.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <TextView
            android:id="@+id/textView5"
            android:layout_width="330dp"
            android:layout_height="51dp"
            android:background="#000000"
            android:fontFamily="@font/aldrich"
            android:gravity="center"
            android:text="@string/daily_uploads"
            android:textColor="#F5A900"
            android:textSize="36sp"
            android:textStyle="bold"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent"
            app:layout_constraintVertical_bias="0.023" />

        <view
            android:id="@+id/YouTube1"
            class="com.google.android.youtube.player.YouTubePlayerView"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginEnd="3dp"
            android:layout_marginBottom="3dp"
            app:layout_constraintBottom_toTopOf="@+id/textView5"
            app:layout_constraintEnd_toStartOf="@+id/textView5"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent" />

        <TextView
            android:id="@+id/textView"
            android:layout_width="359dp"
            android:layout_height="52dp"
            android:fontFamily="@font/aldrich"
            android:text="@string/a_small_paragraph_about_the_video_playing"
            android:textAlignment="center"
            android:textColor="@color/black"
            android:textSize="18sp"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintHorizontal_bias="0.48"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent"
            app:layout_constraintVertical_bias="0.702" />

        <Button
            android:id="@+id/btnPlay1"
            android:layout_width="231dp"
            android:layout_height="63dp"
            android:background="#F5A900"
            android:fontFamily="@font/aldrich"
            android:text="@string/play_video"
            android:textAlignment="center"
            android:textColor="#000000"
            android:textSize="24sp"
            android:textStyle="bold"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent"
            app:layout_constraintVertical_bias="0.878" />

    </androidx.constraintlayout.widget.ConstraintLayout>
</FrameLayout>


问:
Get data from table to another table adobe livecycle
Sample Image

i cant get the proper data for the "Others" row as you can see in the second table

how can i get the proper data for each rows match in same description.

here my current script for that data.

```<code>var others = FormInvoiceRequest.Subform1.Table1.Row14.Cell3.rawValue;
var rows = xfa.resolveNodes(" FormInvoiceRequest.Subform1.Table2.Row1[*]");
//this.rawValue = rows.length;

for (var i = 0; i <= rows.length; i++) {

    var row = rows.item(i);
    var rowQty = row.Cell5.rawValue;
    var rowOthers = row.Cell3.rawValue;

if (rowOthers = others) {

    this.rawValue = rowQty;
    }

</code>```

Body:
Sample Image

i cant get the proper data for the "Others" row as you can see in the second table

how can i get the proper data for each rows match in same description.

here my current script for that data.

var others = FormInvoiceRequest.Subform1.Table1.Row14.Cell3.rawValue;
var rows = xfa.resolveNodes(" FormInvoiceRequest.Subform1.Table2.Row1[*]");
//this.rawValue = rows.length;

for (var i = 0; i <= rows.length; i++) {

    var row = rows.item(i);
    var rowQty = row.Cell5.rawValue;
    var rowOthers = row.Cell3.rawValue;

if (rowOthers = others) {

    this.rawValue = rowQty;
    }


问:
Is it dangerous to use eval in this way in Python to activate the functions of a script and if so what is an alternative?
So perhaps a bit of a weird design I have and would like some critique. So the team I am working with has all of their code in github and they are running in on some in-house server through the command line. My job is to take the existing code and transpose it into a Databricks environment. In order to make the updates to their github dynamic I shell into github and give it a github token and I am able to clone the entire repo onto the Databricks environment. Now that I have access the all the scripts and data that exists in their Repo I make global variables of each script. I put all of that code into a single file call auxiliary. Then I create another file called main and in that file I call the auxiliary file by running %run ./auxiliary, and this point I now have access to all the global variables there -- but I dont have access to the functions inside the global variables. So in order to activate/initialize them I run the exec() function which I understand compiles and evaluates anything you pass in. The scripts I pass in are just a bunch of functions. My question is does this design make sense and is it dangerous to use exec() this way?

Thanks


问:
Assign_crs and assign_y_x to an xarray dataset that contains a data variable created by MetPy's interpolate_to_grid
I have an xarray dataset that contains a data variable 'tmpc_obs' that was created using the interpolate_to_grid function within MetPy. I would like to be able to interpolate specific point values from lat lon pairs using xarray.interp, but I need assign a crs and then assign x and y values. MetPy has options to do this, but I am not having much luck getting it to work.

I created map_crs using cartopy and is what I will transform my lat lon points to, and then create the interpolated field. latlon_crs is the crs for lat lon points.

```<code>
map_crs = ccrs.AlbersEqualArea(central_longitude=-79.0,
                               central_latitude=35.5,
                               standard_parallels=(34.33,36.16),
                               )

latlon_crs = ccrs.PlateCarree()
</code>```

Transform the points to the map_crs and then interpolate the point values to a grid.

```<code>xp, yp, _ = map_crs.transform_points(latlon_crs, obs['lon'], obs['lat']).T
obsx, obsy, tmpc = interpolate_to_grid(xp, yp, obs['tmpc'].values,
                                      interp_type='rbf',
                                      rbf_func='thin_plate',
                                      hres=5000)
</code>```

This turns the 3 arrays generated into an xarray dataset. x_p and y_p are x and y coordinates that are transformed to the map crs.

```<code>obs_ds = xr.Dataset(
    data_vars=dict(
        tmpc_obs=(["x", "y"], tmpc),
    ),
    coords=dict(
        x_p=(["x", "y"], obsx),
        y_p=(["x", "y"], obsy),
    ),
)
</code>```

It's not possible however to interpolate point values at this time using the following code block as it will only give you nan's.

```<code>vals = []
for x, y in zip(stat['lon'], stat['lat']):
    x_t, y_t = map_crs.transform_point(x, y, src_crs=latlon_crs)
    tmp_c = obs_ds["tmpc_obs"].interp(x=x_t, y=y_t, method='cubic').values.item()
    tmp_c = float("{:.2f}".format(tmp_c))
    vals.append(tmp_c)
</code>```

I believe you need to add y and x to the coordinates of the dataset that reference the dimensions. I am having issues doing this. I think I should use the same crs info from the mapcrs, but I don't know what to use for semi major and semi minor axis. Whether I use the axes or not, I get an error, and it doesnt attach the x and y to the coordinates, it only attaches the metpy_crs

```<code># Assign the grid mapping to be able to index specific lat/lon pairs
obs_ds = obs_ds.metpy.assign_crs({
    'semi_major_axis': ???,
    'semi_minor_axis': ???,
    'grid_mapping_name': 'albers_conical_equal_area',
    "standard_parallel": [34.33,36.16],
    "latitude_of_projection_origin": 35.5,
    "longitude_of_central_meridian": -79.0,
}).metpy.assign_y_x()
</code>```

Error:

UserWarning: No y and x coordinates assigned since horizontal coordinates were not found
warnings.warn('No y and x coordinates assigned since horizontal coordinates '

```<code><xarray.Dataset>
Dimensions:    (x: 57, y: 75)
Coordinates:
    x_p        (x, y) float64 -1.963e+05 -1.913e+05 ... 1.692e+05 1.742e+05
    y_p        (x, y) float64 -1.663e+05 -1.663e+05 ... 1.137e+05 1.137e+05
    metpy_crs  object Projection: albers_conical_equal_area
Dimensions without coordinates: x, y
Data variables:
    tmpc       (x, y) float64 0.0618 0.07065 0.07945 ... 0.08191 0.09538 0.1064
</code>```

Body:
I have an xarray dataset that contains a data variable 'tmpc_obs' that was created using the interpolate_to_grid function within MetPy. I would like to be able to interpolate specific point values from lat lon pairs using xarray.interp, but I need assign a crs and then assign x and y values. MetPy has options to do this, but I am not having much luck getting it to work.

I created map_crs using cartopy and is what I will transform my lat lon points to, and then create the interpolated field. latlon_crs is the crs for lat lon points.

map_crs = ccrs.AlbersEqualArea(central_longitude=-79.0,
                               central_latitude=35.5,
                               standard_parallels=(34.33,36.16),
                               )

latlon_crs = ccrs.PlateCarree()

Transform the points to the map_crs and then interpolate the point values to a grid.

xp, yp, _ = map_crs.transform_points(latlon_crs, obs['lon'], obs['lat']).T
obsx, obsy, tmpc = interpolate_to_grid(xp, yp, obs['tmpc'].values,
                                      interp_type='rbf',
                                      rbf_func='thin_plate',
                                      hres=5000)

This turns the 3 arrays generated into an xarray dataset. x_p and y_p are x and y coordinates that are transformed to the map crs.

obs_ds = xr.Dataset(
    data_vars=dict(
        tmpc_obs=(["x", "y"], tmpc),
    ),
    coords=dict(
        x_p=(["x", "y"], obsx),
        y_p=(["x", "y"], obsy),
    ),
)

It's not possible however to interpolate point values at this time using the following code block as it will only give you nan's.

vals = []
for x, y in zip(stat['lon'], stat['lat']):
    x_t, y_t = map_crs.transform_point(x, y, src_crs=latlon_crs)
    tmp_c = obs_ds["tmpc_obs"].interp(x=x_t, y=y_t, method='cubic').values.item()
    tmp_c = float("{:.2f}".format(tmp_c))
    vals.append(tmp_c)

I believe you need to add y and x to the coordinates of the dataset that reference the dimensions. I am having issues doing this. I think I should use the same crs info from the mapcrs, but I don't know what to use for semi major and semi minor axis. Whether I use the axes or not, I get an error, and it doesnt attach the x and y to the coordinates, it only attaches the metpy_crs

# Assign the grid mapping to be able to index specific lat/lon pairs
obs_ds = obs_ds.metpy.assign_crs({
    'semi_major_axis': ???,
    'semi_minor_axis': ???,
    'grid_mapping_name': 'albers_conical_equal_area',
    "standard_parallel": [34.33,36.16],
    "latitude_of_projection_origin": 35.5,
    "longitude_of_central_meridian": -79.0,
}).metpy.assign_y_x()

Error:

UserWarning: No y and x coordinates assigned since horizontal coordinates were not found
warnings.warn('No y and x coordinates assigned since horizontal coordinates '

<xarray.Dataset>
Dimensions:    (x: 57, y: 75)
Coordinates:
    x_p        (x, y) float64 -1.963e+05 -1.913e+05 ... 1.692e+05 1.742e+05
    y_p        (x, y) float64 -1.663e+05 -1.663e+05 ... 1.137e+05 1.137e+05
    metpy_crs  object Projection: albers_conical_equal_area
Dimensions without coordinates: x, y
Data variables:
    tmpc       (x, y) float64 0.0618 0.07065 0.07945 ... 0.08191 0.09538 0.1064


问:
Update/downgrade containerd version on a swarm cluster
In our server architecture, we have a preprod and production server. We realized the production server containerd and the preprod versions are not the same. It falls in a version that had a known bug. Since then, a new version was released that fixed this issue. Our problem is that (idealy) we would like to keep the services running.

Is that possible? I can't find any documentation or procedure in the official documentations, the only thing I found was this question, but it's from 6 years ago.

Any new light on this would be really appreciated.


问:
How to Create VueJs App With WebSocket Server on Same Port
I'm a bit of a JS and Vue noob and I'm trying to figure out how to run my Vue app and a websocket server for that app on the same port 80 (to later be put behind a reverse proxy). I am able to get this working as a simple http server with express, but I can't figure out how to do it with my Vue use case.

My goal is to run a single main.js with npm run serve and bind the websocket server and routes I'm setting up with the vue router all in one application, on the same port.

Here is the example for the simple HTTP case:
server.js

'use strict';

let fs = require('fs');
let express = require('express');
let app = express();
let bodyParser = require('body-parser');
let WSServer = require('ws').Server;
let server = require('http').createServer();
let PORT = 8080

app.use(bodyParser.json());

// regular HTTP request and response
app.get('/', function(req, res) {
  console.log('Get index');
  fs.createReadStream('./index.html').pipe(res);
});

app.post('/', function(req, res) {
  let message = req.body.message;
  console.log('Regular POST message: ', message);
  return res.json({ answer: 42 });
});

module.exports = app;

// Create web socket server on top of a regular http server
let wss = new WSServer({ server: server });

// Also mount the app here
server.on('request', app);

wss.on('connection', function connection(ws) {

  ws.on('message', function incoming(message) {
    console.log(`received: ${message}`);
    ws.send(JSON.stringify({ answer: 42 }));
  });
});

server.listen(PORT, function() {
  console.log(`http/ws server listening on ${PORT}`);
});
```
<p>But my question is how can I modify the default main.js vue file to do this?</p>
<pre class="lang-js prettyprint-override"><code>import { createApp } from 'vue';
import App from './App.vue';

---

import router from './router';
import store from './store';

createApp(App).use(store).use(router).mount('#app');
</code>```

Body:
I'm a bit of a JS and Vue noob and I'm trying to figure out how to run my Vue app and a websocket server for that app on the same port 80 (to later be put behind a reverse proxy). I am able to get this working as a simple http server with express, but I can't figure out how to do it with my Vue use case.

My goal is to run a single main.js with npm run serve and bind the websocket server and routes I'm setting up with the vue router all in one application, on the same port.

Here is the example for the simple HTTP case:
server.js

'use strict';

let fs = require('fs');
let express = require('express');
let app = express();
let bodyParser = require('body-parser');
let WSServer = require('ws').Server;
let server = require('http').createServer();
let PORT = 8080

app.use(bodyParser.json());

// regular HTTP request and response
app.get('/', function(req, res) {
  console.log('Get index');
  fs.createReadStream('./index.html').pipe(res);
});

app.post('/', function(req, res) {
  let message = req.body.message;
  console.log('Regular POST message: ', message);
  return res.json({ answer: 42 });
});

module.exports = app;

// Create web socket server on top of a regular http server
let wss = new WSServer({ server: server });

// Also mount the app here
server.on('request', app);

wss.on('connection', function connection(ws) {

  ws.on('message', function incoming(message) {
    console.log(`received: ${message}`);
    ws.send(JSON.stringify({ answer: 42 }));
  });
});

server.listen(PORT, function() {
  console.log(`http/ws server listening on ${PORT}`);
});

But my question is how can I modify the default main.js vue file to do this?

import { createApp } from 'vue';
import App from './App.vue';

---

import router from './router';
import store from './store';

createApp(App).use(store).use(router).mount('#app');


问:
Is there a way to make a button element download a file other than using an anchor tag on React?
I wanted to make two buttons in a div, one doing something unrelated, and the other would've downloaded a pdf file. But from what I found, the only solution was using an anchor tag, which was pretty disappointing, since it messed up the styling I was going with. Is there any way to use a button element in react/html to download a file?

Here's the code I have at the moment using an anchor tag, but I'm :

```<code>        <div className="aboutMeButtons">
          <button className="button btn-1">Hire Me</button>
          <a href={resume} download className="button">
            Download Resume
          </a>
        </div>
</code>```

Here's the css, in case that is important:

```<code>.aboutMeButtons {
  margin-top: 50px;
  padding-bottom: 100px;
  text-align: center;
  box-shadow: none;

}

.btn-1 {
  margin-right: 30px;
}

.button {
  background-color: #37D4AF;
  border-color: #37D4AF;
  border-radius: 5px;
  box-shadow: none;
  outline: none;
  padding: 10px;
  color: #fff;
  font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
  font-weight: bold;
  font-size: 20px;
  min-width: 220px;
  height: 70px;
  text-decoration: none;
}
</code>```

Body:
I wanted to make two buttons in a div, one doing something unrelated, and the other would've downloaded a pdf file. But from what I found, the only solution was using an anchor tag, which was pretty disappointing, since it messed up the styling I was going with. Is there any way to use a button element in react/html to download a file?

Here's the code I have at the moment using an anchor tag, but I'm :

          <button className="button btn-1">Hire Me</button>

            Download Resume

Here's the css, in case that is important:

.aboutMeButtons {
  margin-top: 50px;
  padding-bottom: 100px;
  text-align: center;
  box-shadow: none;

}

.btn-1 {
  margin-right: 30px;
}

.button {
  background-color: #37D4AF;
  border-color: #37D4AF;
  border-radius: 5px;
  box-shadow: none;
  outline: none;
  padding: 10px;
  color: #fff;
  font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
  font-weight: bold;
  font-size: 20px;
  min-width: 220px;
  height: 70px;
  text-decoration: none;
}


问:
Detect exponential value in a dataframe and replace with 10000
I have a dataframe

```<code>value
5
5.67E+54
10
1.04E+26

</code>```

My expected output is

```<code>value
5
10000
10
10000

</code>```

I would like to detect exponential value in a dataframe and replace with 10000. Thanks!

Body:
I have a dataframe

value
5
5.67E+54
10
1.04E+26

My expected output is

value
5
10000
10
10000

I would like to detect exponential value in a dataframe and replace with 10000. Thanks!


问:
I need help in order to create a program using the dart language to print all divisors of a( 2^63 - 1) number in crescent order
hope everyone is good.
I'm a student and I'm having a really bad time with a homework.
My teacher asked me to create a program to print every divisor of a number in crescent order in less than 10 seconds using the dart language.
The problem is: He wants the divisor to be a number of about 14 characters, more precisely the number: 21,001,713,200,000.
I'm having overflow issues because this is a large number.
I really appreciate if someone could help me.

`

```<code>void main(){
    int a = 40;
    int aux = 0;
    for (int i = 2; i < a; i++) {
        if (a % i == 0) {
            ++aux;
        }
    }
    List<int> diva = [];
    int k = 0;
    aux = 1;
    for (int i = 0; i < a; i++) {
        ++aux;
        if (a % aux == 0) {
            diva.insert(k++, aux);
        }
    }
  print('${diva}');
}
</code>```

`

Body:
hope everyone is good.
I'm a student and I'm having a really bad time with a homework.
My teacher asked me to create a program to print every divisor of a number in crescent order in less than 10 seconds using the dart language.
The problem is: He wants the divisor to be a number of about 14 characters, more precisely the number: 21,001,713,200,000.
I'm having overflow issues because this is a large number.
I really appreciate if someone could help me.

`

void main(){
    int a = 40;
    int aux = 0;
    for (int i = 2; i < a; i++) {
        if (a % i == 0) {
            ++aux;
        }
    }
    List<int> diva = [];
    int k = 0;
    aux = 1;
    for (int i = 0; i < a; i++) {
        ++aux;
        if (a % aux == 0) {
            diva.insert(k++, aux);
        }
    }
  print('${diva}');
}

`


问:
extract value from a list netmiko , python3, f5
Please could someone help me to guide how to extract value from the below OUTPUT.

```<code>**print(k)**
HOST-ABC01
['1']
['1']
['2']
['3']
['4']

</code>```

I need to store last digit in the last line of the output. Example from above , I need to have 4 store in slotnum.

slotnum = 4

My code is here below:

```<code>import re
from netmiko import Netmiko
from multiprocessing.dummy import Pool as ThreadPool
import time

f_2 = open("f5ips.txt","r") # You should open a notepad with this name and add all the IPs one under the other.
multiple_device_list = f_2.readlines()
#print(multiple_device_list)

# create lists
name = []

def _slot_(nodeip):
    try:
        switch = {
            'device_type': 'f5_ltm', 'ip': nodeip, 'username':
            'user', 'password':"pass", "conn_timeout": 2}
        switch_connect = Netmiko(**switch)
        print(nodeip.strip() + " " + "is reachable")
        prompt_sw_axa = switch_connect.find_prompt()
        slice1 = (prompt_sw_axa.split(')')[0])
        slice2 = [slice1.split("(")[1]]
        name = [(slice2[0])]
        print(name)

    except Exception as e:
        print (e)
        'f_2.write(nodeip.strip() + "\n")'
        return

    output = switch_connect.send_command ("show sys cluster field-fmt")
    print(name[0])
    LINES = output.split("\n")
    #print(LINES)
    search_strg1 = "slot-id"

    for l1 in LINES:
        if re.search(r'\b{}\b'.format(search_strg1), l1):
            k = [([l1][0][-1])]
            print(k)
        # I need to store last digit in the last line of the output **(NEED HELP HERE)**

    switch_connect.disconnect()

myPool = ThreadPool(100) # you can increase or decrease this value

</code>```

OUTPUT of above script as below:

```<code>
10.10.10.1 is reachable
10.10.10.2 is reachable
['HOST-ABC01']
['HOST-ABC01']
HOST-ABC01
['1']
['1']
['2']
['3']
['4']
HOST-ABC02
['1']
['1']
['2']
['3']
['4']

</code>```

Trying to extract value from K , using re module in python and list to extract but unable to do so.

Body:
Please could someone help me to guide how to extract value from the below OUTPUT.

**print(k)**
HOST-ABC01
['1']
['1']
['2']
['3']
['4']

I need to store last digit in the last line of the output. Example from above , I need to have 4 store in slotnum.

slotnum = 4

My code is here below:

import re
from netmiko import Netmiko
from multiprocessing.dummy import Pool as ThreadPool
import time

f_2 = open("f5ips.txt","r") # You should open a notepad with this name and add all the IPs one under the other.
multiple_device_list = f_2.readlines()
#print(multiple_device_list)

# create lists
name = []

def _slot_(nodeip):
    try:
        switch = {
            'device_type': 'f5_ltm', 'ip': nodeip, 'username':
            'user', 'password':"pass", "conn_timeout": 2}
        switch_connect = Netmiko(**switch)
        print(nodeip.strip() + " " + "is reachable")
        prompt_sw_axa = switch_connect.find_prompt()
        slice1 = (prompt_sw_axa.split(')')[0])
        slice2 = [slice1.split("(")[1]]
        name = [(slice2[0])]
        print(name)

    except Exception as e:
        print (e)
        'f_2.write(nodeip.strip() + "\n")'
        return

    output = switch_connect.send_command ("show sys cluster field-fmt")
    print(name[0])
    LINES = output.split("\n")
    #print(LINES)
    search_strg1 = "slot-id"

    for l1 in LINES:
        if re.search(r'\b{}\b'.format(search_strg1), l1):
            k = [([l1][0][-1])]
            print(k)
        # I need to store last digit in the last line of the output **(NEED HELP HERE)**

    switch_connect.disconnect()

myPool = ThreadPool(100) # you can increase or decrease this value

OUTPUT of above script as below:

10.10.10.1 is reachable
10.10.10.2 is reachable
['HOST-ABC01']
['HOST-ABC01']
HOST-ABC01
['1']
['1']
['2']
['3']
['4']
HOST-ABC02
['1']
['1']
['2']
['3']
['4']

Trying to extract value from K , using re module in python and list to extract but unable to do so.


问:
pipe3 error Could not find a suitable TLS CA certificate bundle
I'm trying to install a python module but I'm getting the following error:

➜  pip3 install instapy
ERROR: Could not install packages due to an EnvironmentError: Could not find a suitable TLS CA certificate bundle, invalid path: /etc/ssl/certs/ca-certificates.crt

I'm new to python, does anyone know how I can fix this problem?
Thanks all!!


问:
hey i want to get the teams of the particular repo in github so im using the github api's GET
link for the docs is here and the curl command is:

```<code>curl \
  -H "Accept: application/vnd.github+json" \
  -H "Authorization: Bearer <YOUR-TOKEN>"\
  -H "X-GitHub-Api-Version: 2022-11-28" \
  https://api.github.com/repos/OWNER/REPO/teams
</code>```

I've given personal access token as my Authorization but it throws as not found.
Any suggestions on how to get it? My repo was assigned to 3 teams even tho it throws not found

i'm the owner of the org and trued to hit with my PAC even tho its giving me the same 404 statusCode.
for example :
this is the link for getting the contributors but for teams i've this but it is giving me 404

Body:
link for the docs is here and the curl command is:

curl \
  -H "Accept: application/vnd.github+json" \
  -H "Authorization: Bearer <YOUR-TOKEN>"\
  -H "X-GitHub-Api-Version: 2022-11-28" \
  https://api.github.com/repos/OWNER/REPO/teams

I've given personal access token as my Authorization but it throws as not found.
Any suggestions on how to get it? My repo was assigned to 3 teams even tho it throws not found

i'm the owner of the org and trued to hit with my PAC even tho its giving me the same 404 statusCode.
for example :
this is the link for getting the contributors but for teams i've this but it is giving me 404


问:
django annotate based on another annotate create a duplicate query
I want to calculate number of group members (no_members), sum of the points of the group members(point) and average point per person(avg_point) for each group with annotation:

```<code>groups = StudyGroup.objects.filter(group_filter).select_related('parent').annotate(
        no_members=Count('student', distinct=True),
        point=Sum('student__point__point', filter=point_filter),
        avg_point=ExpressionWrapper(F('point') / F('no_members'), output_field=FloatField()))
</code>```

but when I check query (groups.query) in avg_point instead of use point/no_members query is SUM(study_league_point.point) / COUNT(DISTINCT users_student.user_id) (point and no_members calculate again). query is:

```<code>SELECT
    `study_league_studygroup`.`id`,
    `study_league_studygroup`.`name`,
    `study_league_studygroup`.`parent_id`,
    COUNT(DISTINCT `users_student`.`user_id`) AS `no_members`,
    SUM(`study_league_point`.`point`) AS `point`,
    (
        SUM(`study_league_point`.`point`) / COUNT(DISTINCT `users_student`.`user_id`)
    ) AS `avg_point`,
    `layers_layer`.`id`,
    `layers_layer`.`name`,
    `layers_layer`.`type_id`,
    `layers_layer`.`parent_id`,
    `layers_layer`.`created`,
    `layers_layer`.`default`,
    `layers_layer`.`lft`,
    `layers_layer`.`rght`,
    `layers_layer`.`tree_id`,
    `layers_layer`.`level`
FROM
    `study_league_studygroup`
    LEFT OUTER JOIN `users_student` ON (
        `study_league_studygroup`.`id` = `users_student`.`study_group_id`
    )
    LEFT OUTER JOIN `study_league_point` ON (
        `users_student`.`user_id` = `study_league_point`.`student_id`
    )
    INNER JOIN `layers_layer` ON (
        `study_league_studygroup`.`parent_id` = `layers_layer`.`id`
    )
GROUP BY
    `study_league_studygroup`.`id`
</code>```

but I want use (point / no_members) AS avg_point instead of (SUM(study_league_point.point) / COUNT(DISTINCT users_student.user_id)) AS avg_point

Body:
I want to calculate number of group members (no_members), sum of the points of the group members(point) and average point per person(avg_point) for each group with annotation:

groups = StudyGroup.objects.filter(group_filter).select_related('parent').annotate(
        no_members=Count('student', distinct=True),
        point=Sum('student__point__point', filter=point_filter),
        avg_point=ExpressionWrapper(F('point') / F('no_members'), output_field=FloatField()))

but when I check query (groups.query) in avg_point instead of use point/no_members query is SUM(study_league_point.point) / COUNT(DISTINCT users_student.user_id) (point and no_members calculate again). query is:

SELECT
    `study_league_studygroup`.`id`,
    `study_league_studygroup`.`name`,
    `study_league_studygroup`.`parent_id`,
    COUNT(DISTINCT `users_student`.`user_id`) AS `no_members`,
    SUM(`study_league_point`.`point`) AS `point`,
    (
        SUM(`study_league_point`.`point`) / COUNT(DISTINCT `users_student`.`user_id`)
    ) AS `avg_point`,
    `layers_layer`.`id`,
    `layers_layer`.`name`,
    `layers_layer`.`type_id`,
    `layers_layer`.`parent_id`,
    `layers_layer`.`created`,
    `layers_layer`.`default`,
    `layers_layer`.`lft`,
    `layers_layer`.`rght`,
    `layers_layer`.`tree_id`,
    `layers_layer`.`level`
FROM
    `study_league_studygroup`
    LEFT OUTER JOIN `users_student` ON (
        `study_league_studygroup`.`id` = `users_student`.`study_group_id`
    )
    LEFT OUTER JOIN `study_league_point` ON (
        `users_student`.`user_id` = `study_league_point`.`student_id`
    )
    INNER JOIN `layers_layer` ON (
        `study_league_studygroup`.`parent_id` = `layers_layer`.`id`
    )
GROUP BY
    `study_league_studygroup`.`id`

but I want use (point / no_members) AS avg_point instead of (SUM(study_league_point.point) / COUNT(DISTINCT users_student.user_id)) AS avg_point


问:
Change an AsyncImage into a bitmap
I'm currently using jetpack compose to code a pokemon GO like game. I have my markers on my map and I use AsyncImages to get images from the PokeAPI. The problem is I need to give bitmaps to my markers but I don't know how to do. I'd appreciate any help.

Code Screenshot

I tried to change the Async image as you can see in the screenshot but it's not working like this.

Full code :

```<code>    class MainActivity : ComponentActivity(){
        override fun onCreate(savedInstanceState: Bundle?) {
            super.onCreate(savedInstanceState)

        setContent {
            val height = 200
            val width = 100
            val loader = ImageLoader(this)
            val bitmapdraw = BitmapFactory.decodeResource(applicationContext.resources, R.drawable.charac)
            val smallMarker = Bitmap.createScaledBitmap(bitmapdraw, width, height, false)
            val location = LatLng(47.394144, 0.68484)
            Column() {

                MapScreen(location)

                Row(
                    modifier = Modifier
                        .fillMaxWidth()
                        .height(50.dp)
                        .background(Color.Green.copy(alpha = 0.1f))
                        .weight(1f, true),
                    horizontalArrangement = Arrangement.SpaceAround,
                    verticalAlignment = Alignment.CenterVertically
                ) {

                    Image(painter = painterResource(id = R.drawable.pokedex),
                        contentDescription = "Pokeball",
                        modifier = Modifier
                            .size(50.dp)
                            .clickable {
                                val navigate =
                                    Intent(this@MainActivity, PokedexActivity::class.java)
                                startActivity(navigate)
                            }
                    )

                    Image(painter = painterResource(id = R.drawable.fight),
                        contentDescription = "Pokeball",
                        modifier = Modifier
                            .size(50.dp)
                            .clickable {

                            }
                    )

                    Image(painter = painterResource(id = R.drawable.pokeball),
                        contentDescription = "Pokeball",
                        modifier = Modifier
                            .size(50.dp)
                            .clickable {

                            }
                    )

                }

            }

        }
    }
}

@Composable
fun MapScreen(localisation: LatLng){
    val context = LocalContext.current
    val locationState = (MarkerState(position= localisation))
    val liste = mutableListOf<Int>(1, 2, 3, 4, 3, 2, 3, 5, 3, 3, 2, 3, 2)
    GoogleMap(
        cameraPositionState = CameraPositionState(CameraPosition(localisation, 18f, 0f, 0f)),
        modifier = Modifier
            .fillMaxHeight(0.9f)
    ) {
        AddPokemons(localisation = localisation, pokemons = liste)
    }
}

@Composable
fun AddPokemons(localisation: LatLng, pokemons: MutableList<Int>)
{
    val context = LocalContext.current
    val url = "https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/132.png"
    pokemons.forEach(){

        val randLat = Random.nextDouble(-1.0, 1.0) / 500
        val randLong = Random.nextDouble(-1.0, 1.0) / 500
        val randomLocation = LatLng(localisation.latitude + randLat, localisation.longitude + randLong)
        val locationState = (MarkerState(position= randomLocation))
        val image = AsyncImage(model = url, contentDescription = "pokemon")

        Marker(
            state = locationState,
            onClick = {
                val navigate = Intent(context, Combat::class.java)
                startActivity(context, navigate, null)
                false
            },
            icon = BitmapDescriptorFactory.fromBitmap((image as BitmapDrawable).bitmap.copy(Bitmap.Config.ARGB_8888, true))

        )
    }
}

@Composable
fun Greeting(name: String) {
    Text(
        text = "Hello $name!"
    )
}

@Preview(showBackground = true)
@Composable
fun GreetingPreview() {
    Greeting("Mathis")
}
</code>```

Title: Change an AsyncImage into a bitmap

Body:
I'm currently using jetpack compose to code a pokemon GO like game. I have my markers on my map and I use AsyncImages to get images from the PokeAPI. The problem is I need to give bitmaps to my markers but I don't know how to do. I'd appreciate any help.

Code Screenshot

I tried to change the Async image as you can see in the screenshot but it's not working like this.

Full code :

    class MainActivity : ComponentActivity(){
        override fun onCreate(savedInstanceState: Bundle?) {
            super.onCreate(savedInstanceState)

        setContent {
            val height = 200
            val width = 100
            val loader = ImageLoader(this)
            val bitmapdraw = BitmapFactory.decodeResource(applicationContext.resources, R.drawable.charac)
            val smallMarker = Bitmap.createScaledBitmap(bitmapdraw, width, height, false)
            val location = LatLng(47.394144, 0.68484)
            Column() {

                MapScreen(location)

                Row(
                    modifier = Modifier
                        .fillMaxWidth()
                        .height(50.dp)
                        .background(Color.Green.copy(alpha = 0.1f))
                        .weight(1f, true),
                    horizontalArrangement = Arrangement.SpaceAround,
                    verticalAlignment = Alignment.CenterVertically
                ) {

                    Image(painter = painterResource(id = R.drawable.pokedex),
                        contentDescription = "Pokeball",
                        modifier = Modifier
                            .size(50.dp)
                            .clickable {
                                val navigate =
                                    Intent(this@MainActivity, PokedexActivity::class.java)
                                startActivity(navigate)
                            }
                    )

                    Image(painter = painterResource(id = R.drawable.fight),
                        contentDescription = "Pokeball",
                        modifier = Modifier
                            .size(50.dp)
                            .clickable {

                            }
                    )

                    Image(painter = painterResource(id = R.drawable.pokeball),
                        contentDescription = "Pokeball",
                        modifier = Modifier
                            .size(50.dp)
                            .clickable {

                            }
                    )

                }

            }

        }
    }
}

@Composable
fun MapScreen(localisation: LatLng){
    val context = LocalContext.current
    val locationState = (MarkerState(position= localisation))
    val liste = mutableListOf<Int>(1, 2, 3, 4, 3, 2, 3, 5, 3, 3, 2, 3, 2)
    GoogleMap(
        cameraPositionState = CameraPositionState(CameraPosition(localisation, 18f, 0f, 0f)),
        modifier = Modifier
            .fillMaxHeight(0.9f)
    ) {
        AddPokemons(localisation = localisation, pokemons = liste)
    }
}

@Composable
fun AddPokemons(localisation: LatLng, pokemons: MutableList<Int>)
{
    val context = LocalContext.current
    val url = "https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/132.png"
    pokemons.forEach(){

        val randLat = Random.nextDouble(-1.0, 1.0) / 500
        val randLong = Random.nextDouble(-1.0, 1.0) / 500
        val randomLocation = LatLng(localisation.latitude + randLat, localisation.longitude + randLong)
        val locationState = (MarkerState(position= randomLocation))
        val image = AsyncImage(model = url, contentDescription = "pokemon")

        Marker(
            state = locationState,
            onClick = {
                val navigate = Intent(context, Combat::class.java)
                startActivity(context, navigate, null)
                false
            },
            icon = BitmapDescriptorFactory.fromBitmap((image as BitmapDrawable).bitmap.copy(Bitmap.Config.ARGB_8888, true))

        )
    }
}

@Composable
fun Greeting(name: String) {
    Text(
        text = "Hello $name!"
    )
}

@Preview(showBackground = true)
@Composable
fun GreetingPreview() {
    Greeting("Mathis")
}


问:
No change detection in Angular when change is in switchMap
I have two components Parent and child.

In parent there is HTTP call and there is a switchMap operator. Inside the loading status has changed as above:

```<code>
this.subscriptions.add(this.personService.updatePerson(this.personId, personobject.list)
      .pipe(
        switchMap(() => {
          this.setPersonUploadStatus(UploadStatus.FinishedSuccessfully);
          this.setPersonsHierarchyUploadStatus(UploadStatus.InProgress);

          return this.personService.updatePersonHierarchy(this.personId, personobject.list).pipe(share());
        }),
        finalize(() => {
          this.setPersonUploadStatus(UploadStatus.NotStarted);
          this.setPersonsHierarchyUploadStatus(UploadStatus.NotStarted);
        })
      ).subscribe(
        () => {
          this.setPersonUploadStatus(UploadStatus.FinishedSuccessfully);
          this.toastr.success(this.Translations['success']);
        },
        (response) => {
          this.toastr.error(response.error.message, this.Translations['shared.error']);
        }
      ));

</code>```
```<code>private setPersonUploadStatus(uploadStatus: UploadStatus){
    this.personUploadStatus = uploadStatus;
  }

  private setPersonsHierarchyUploadStatus(uploadStatus: UploadStatus) {
    this.personHierarchyUploadStatus = uploadStatus;
  }
</code>```

below values are inputted to child component where is ngOnChanges method, which not call any change...

```<code>personHierarchyUploadStatus
personUploadStatus
</code>```

Body:
I have two components Parent and child.

In parent there is HTTP call and there is a switchMap operator. Inside the loading status has changed as above:

this.subscriptions.add(this.personService.updatePerson(this.personId, personobject.list)
      .pipe(
        switchMap(() => {
          this.setPersonUploadStatus(UploadStatus.FinishedSuccessfully);
          this.setPersonsHierarchyUploadStatus(UploadStatus.InProgress);

          return this.personService.updatePersonHierarchy(this.personId, personobject.list).pipe(share());
        }),
        finalize(() => {
          this.setPersonUploadStatus(UploadStatus.NotStarted);
          this.setPersonsHierarchyUploadStatus(UploadStatus.NotStarted);
        })
      ).subscribe(
        () => {
          this.setPersonUploadStatus(UploadStatus.FinishedSuccessfully);
          this.toastr.success(this.Translations['success']);
        },
        (response) => {
          this.toastr.error(response.error.message, this.Translations['shared.error']);
        }
      ));

private setPersonUploadStatus(uploadStatus: UploadStatus){
    this.personUploadStatus = uploadStatus;
  }

  private setPersonsHierarchyUploadStatus(uploadStatus: UploadStatus) {
    this.personHierarchyUploadStatus = uploadStatus;
  }

below values are inputted to child component where is ngOnChanges method, which not call any change...

personHierarchyUploadStatus
personUploadStatus


问:
Failed to load linux kernel module in Android
I build boot image and vendor boot image with the same Linux kernel version for Android.
But when the device boots, it fails to load modules.

```<code>[    8.384474][  T340] modprobe: Failed to insmod '/system_dlkm/lib/modules/5.15.41//kernel/mm/zsmalloc.ko' with args '': Exec format error
[    8.397090][  T340] modprobe: LoadWithAliases was unable to load kernel/mm/zsmalloc.ko
</code>```

Except the Linux kernel version, what might be the reason for the failure?

Body:
I build boot image and vendor boot image with the same Linux kernel version for Android.
But when the device boots, it fails to load modules.

[    8.384474][  T340] modprobe: Failed to insmod '/system_dlkm/lib/modules/5.15.41//kernel/mm/zsmalloc.ko' with args '': Exec format error
[    8.397090][  T340] modprobe: LoadWithAliases was unable to load kernel/mm/zsmalloc.ko

Except the Linux kernel version, what might be the reason for the failure?


问:
Mocking React higher-order components (HOC) with Jest
i am trying to run a unit testing for my react-native component. My component seems complex. i tired all possible ways to get it done.

My CheckBox component wrapped with HOC withTheme

```<code>import { View, Text, Pressable, StyleSheet } from 'react-native'
import React, { useState } from 'react'
import { scale } from 'react-native-size-matters'
import MaterialIcons from 'react-native-vector-icons/dist/MaterialIcons'
import withTheme from 'Theme/withTheme'
import Label from 'Components/Label'
import testID from 'Utils/common'

function CheckBox({ theme: { colors }, label }) {
    const styles = style(colors)
    const [checked, setChecked] = useState(false)
    const onPress = () => {
        setChecked(!checked)
    }
    return (
        <Pressable onPress={onPress} style={styles.wrapper} {...testID(`CheckBox wrapper`)}>
            <View style={styles.iconWrapper} {...testID(`CheckBox wrapper check`)}>
                {checked && <MaterialIcons name="done" size={scale(15)} color={colors.black} />}
            </View>
            <View style={{ paddingHorizontal: scale(10) }} {...testID(`CheckBox Label Wrapper`)}>
                <Label text={label} style={{ fontSize: scale(14) }}  {...testID(`CheckBox label ${label}`)}/>
            </View>
        </Pressable>
    )
}

export default withTheme(CheckBox)
const style = StyleSheet.create((colors) => ({
    wrapper: {
        flexDirection: 'row',
        alignItems: 'center'
    },
    iconWrapper: {
        backgroundColor: colors.primary,
        height: scale(25),
        width: scale(25), borderRadius: scale(4),
        justifyContent: "center",
        alignItems: 'center'
    }

}))
</code>```

withTheme HOC Code

withTheme has hook useTheme

```<code>import React, { forwardRef } from 'react';
import { useTheme } from './ThemeProvider';

function withTheme(WrappedComponent, props) {

  return forwardRef(function (someProps, ref) {
    const { theme  } = useTheme();
    return (
      <WrappedComponent ref={ref} {...someProps} {...props} theme={theme} />
    );
  });
}

export default withTheme;

</code>```

What i tried
Tried mockcing HOC
Tried mockcing withTheme hook
Refered this Blog

test written

```<code>/* ---------- Packages Import ---------- */
import React from 'react';
import {render, cleanup, fireEvent} from '@testing-library/react-native';
import CheckBox from '../index';
import testID from 'Utils/common';

/* ---------- Components Import ---------- */
jest.mock('@react-native-async-storage/async-storage', () =>
  require('@react-native-async-storage/async-storage/jest/async-storage-mock'),
);
jest.mock('react-native/Libraries/EventEmitter/NativeEventEmitter');
jest.mock('Theme/__mock__/withTheme');
jest.mock('Theme/__mock__/useTheme');

afterEach(cleanup);

describe('<CheckBox />', () => {
  it('should match the snapshot', () => {
    const rendered = render(<CheckBox  />).toJSON();
    expect(rendered).toMatchSnapshot();
  });

});

</code>```

Error i am getting

Any help would be appricated, Thank in advance

Body:
i am trying to run a unit testing for my react-native component. My component seems complex. i tired all possible ways to get it done.

My CheckBox component wrapped with HOC withTheme

import { View, Text, Pressable, StyleSheet } from 'react-native'
import React, { useState } from 'react'
import { scale } from 'react-native-size-matters'
import MaterialIcons from 'react-native-vector-icons/dist/MaterialIcons'
import withTheme from 'Theme/withTheme'
import Label from 'Components/Label'
import testID from 'Utils/common'

function CheckBox({ theme: { colors }, label }) {
    const styles = style(colors)
    const [checked, setChecked] = useState(false)
    const onPress = () => {
        setChecked(!checked)
    }
    return (
        <Pressable onPress={onPress} style={styles.wrapper} {...testID(`CheckBox wrapper`)}>
            <View style={styles.iconWrapper} {...testID(`CheckBox wrapper check`)}>
                {checked && <MaterialIcons name="done" size={scale(15)} color={colors.black} />}
            </View>
            <View style={{ paddingHorizontal: scale(10) }} {...testID(`CheckBox Label Wrapper`)}>
                <Label text={label} style={{ fontSize: scale(14) }}  {...testID(`CheckBox label ${label}`)}/>
            </View>
        </Pressable>
    )
}

export default withTheme(CheckBox)
const style = StyleSheet.create((colors) => ({
    wrapper: {
        flexDirection: 'row',
        alignItems: 'center'
    },
    iconWrapper: {
        backgroundColor: colors.primary,
        height: scale(25),
        width: scale(25), borderRadius: scale(4),
        justifyContent: "center",
        alignItems: 'center'
    }

}))

withTheme HOC Code

withTheme has hook useTheme

import React, { forwardRef } from 'react';
import { useTheme } from './ThemeProvider';

function withTheme(WrappedComponent, props) {

  return forwardRef(function (someProps, ref) {
    const { theme  } = useTheme();
    return (
      <WrappedComponent ref={ref} {...someProps} {...props} theme={theme} />
    );
  });
}

export default withTheme;

What i tried
Tried mockcing HOC
Tried mockcing withTheme hook
Refered this Blog

test written

/* ---------- Packages Import ---------- */
import React from 'react';
import {render, cleanup, fireEvent} from '@testing-library/react-native';
import CheckBox from '../index';
import testID from 'Utils/common';

/* ---------- Components Import ---------- */
jest.mock('@react-native-async-storage/async-storage', () =>
  require('@react-native-async-storage/async-storage/jest/async-storage-mock'),
);
jest.mock('react-native/Libraries/EventEmitter/NativeEventEmitter');
jest.mock('Theme/__mock__/withTheme');
jest.mock('Theme/__mock__/useTheme');

afterEach(cleanup);

describe('<CheckBox />', () => {
  it('should match the snapshot', () => {
    const rendered = render(<CheckBox  />).toJSON();
    expect(rendered).toMatchSnapshot();
  });

});

Error i am getting

Any help would be appricated, Thank in advance


问:
How do I fade out text but display it if it's visible in the viewport?
I know I can fade out text with

```<code>mask-image: linear-gradient(to bottom, black calc(100% - 2rem), transparent 100%);
</code>```

and I use this to indicate that the text is overflown/scrollable, but once the user scrolls to see the rest of the text, I want the fade to be disabled.

Body:
I know I can fade out text with

mask-image: linear-gradient(to bottom, black calc(100% - 2rem), transparent 100%);

and I use this to indicate that the text is overflown/scrollable, but once the user scrolls to see the rest of the text, I want the fade to be disabled.


问:
ImportError DLL load failed while importing fasttext_corpusfile
When I try to import gensim, I get the below error:

```<code>Traceback (most recent call last):
  File "C:\Users\Administrator\AppData\Local\Programs\Python\Python38\lib\site-packages\gensim\models\fasttext.py", line 264, in <module>
    from gensim.models.fasttext_corpusfile import train_epoch_sg, train_epoch_cbow
ImportError: DLL load failed while importing fasttext_corpusfile: The specified module could not be found.

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Users\Administrator\AppData\Local\Programs\Python\Python38\lib\site-packages\gensim\__init__.py", line 11, in <module>
    from gensim import parsing, corpora, matutils, interfaces, models, similarities, utils  # noqa:F401
  File "C:\Users\Administrator\AppData\Local\Programs\Python\Python38\lib\site-packages\gensim\models\__init__.py", line 22, in <module>
    from .fasttext import FastText  # noqa:F401
  File "C:\Users\Administrator\AppData\Local\Programs\Python\Python38\lib\site-packages\gensim\models\fasttext.py", line 266, in <module>
    raise utils.NO_CYTHON
RuntimeError: Compiled extensions are unavailable. If you've installed from a package, ask the package maintainer to include compiled extensions. If you're building Gensim from source yourself, install Cython and a C compiler, and then run `python setup.py build_ext --inplace` to retry.
</code>```

My computer is Windows Server 2022 Data Center, python is 3.8.10, gensim is 4.2.0.

How can I solve this problem? Thank you for your help.

I re-installed gensim (gensim-4.2.0-cp39-cp39-win_amd64.whl) from https://pypi.org/project/gensim/#files, but still had the above problem.

Body:
When I try to import gensim, I get the below error:

Traceback (most recent call last):
  File "C:\Users\Administrator\AppData\Local\Programs\Python\Python38\lib\site-packages\gensim\models\fasttext.py", line 264, in <module>
    from gensim.models.fasttext_corpusfile import train_epoch_sg, train_epoch_cbow
ImportError: DLL load failed while importing fasttext_corpusfile: The specified module could not be found.

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Users\Administrator\AppData\Local\Programs\Python\Python38\lib\site-packages\gensim\__init__.py", line 11, in <module>
    from gensim import parsing, corpora, matutils, interfaces, models, similarities, utils  # noqa:F401
  File "C:\Users\Administrator\AppData\Local\Programs\Python\Python38\lib\site-packages\gensim\models\__init__.py", line 22, in <module>
    from .fasttext import FastText  # noqa:F401
  File "C:\Users\Administrator\AppData\Local\Programs\Python\Python38\lib\site-packages\gensim\models\fasttext.py", line 266, in <module>
    raise utils.NO_CYTHON
RuntimeError: Compiled extensions are unavailable. If you've installed from a package, ask the package maintainer to include compiled extensions. If you're building Gensim from source yourself, install Cython and a C compiler, and then run `python setup.py build_ext --inplace` to retry.

My computer is Windows Server 2022 Data Center, python is 3.8.10, gensim is 4.2.0.

How can I solve this problem? Thank you for your help.

I re-installed gensim (gensim-4.2.0-cp39-cp39-win_amd64.whl) from https://pypi.org/project/gensim/#files, but still had the above problem.


问:
How to cleanly turn a ResultPropertyValueCollection of bytes back into a string
I'm running a query against an openlap instance to pull some SSH keys, but they're coming back as byte arrays wrapped in System.DirectoryServices.ResultPropertyValueCollection objects, which I'm having trouble finding a clean way to decode.

The query I'm running is simple enough:

```<code>$domain = 'LDAP://ldap.local:636/dc=local'
$auth = [System.DirectoryServices.AuthenticationTypes]::Anonymous
$root = new-object -Typename System.DirectoryServices.DirectoryEntry($domain,$null,$null,$auth)
$query = new-object System.DirectoryServices.DirectorySearcher($root, "uid=$uid", @("uid","sshPublicKey"))
$results = $query.findall()
</code>```

But when I take the results and try to feed them into a converter, it gets unhappy:

```<code>$enc = [system.text.encoding]::UTF8
$enc.GetString($results.properties.sshpublickey)

Cannot convert argument "bytes", with value: "System.DirectoryServices.ResultPropertyValueCollection", for "GetString" to type "System.Byte[]": "Cannot convert value "System.DirectoryServices.ResultPropertyValueCollection" to type
"System.Byte[]". Error: "Cannot convert the "System.Byte[]" value of type "System.Byte[]" to type "System.Byte".""
At line:1 char:1
+ $enc.GetString($results.properties.sshpublickey)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], MethodException
    + FullyQualifiedErrorId : MethodArgumentConversionInvalidCastArgument
</code>```

Unless I feed it the individual bytes one at a time:

```<code>foreach ($byte in $results.properties.sshpublickey) {$enc.getstring($byte)}
</code>```

...and that just feels ugly - is there a better way of doing this that I'm missing, or is this just the madness of powershell?  Also, does anyone know why these SSH keys are being returned as arrays of bytes rather than just text?  Is there a setting I could change with my query or within the openldap instance I'm querying to just force it to provide the text in the first place?

Thanks!

Body:
I'm running a query against an openlap instance to pull some SSH keys, but they're coming back as byte arrays wrapped in System.DirectoryServices.ResultPropertyValueCollection objects, which I'm having trouble finding a clean way to decode.

The query I'm running is simple enough:

$domain = 'LDAP://ldap.local:636/dc=local'
$auth = [System.DirectoryServices.AuthenticationTypes]::Anonymous
$root = new-object -Typename System.DirectoryServices.DirectoryEntry($domain,$null,$null,$auth)
$query = new-object System.DirectoryServices.DirectorySearcher($root, "uid=$uid", @("uid","sshPublicKey"))
$results = $query.findall()

But when I take the results and try to feed them into a converter, it gets unhappy:

$enc = [system.text.encoding]::UTF8
$enc.GetString($results.properties.sshpublickey)

Cannot convert argument "bytes", with value: "System.DirectoryServices.ResultPropertyValueCollection", for "GetString" to type "System.Byte[]": "Cannot convert value "System.DirectoryServices.ResultPropertyValueCollection" to type
"System.Byte[]". Error: "Cannot convert the "System.Byte[]" value of type "System.Byte[]" to type "System.Byte".""
At line:1 char:1
+ $enc.GetString($results.properties.sshpublickey)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], MethodException
    + FullyQualifiedErrorId : MethodArgumentConversionInvalidCastArgument

Unless I feed it the individual bytes one at a time:

foreach ($byte in $results.properties.sshpublickey) {$enc.getstring($byte)}

...and that just feels ugly - is there a better way of doing this that I'm missing, or is this just the madness of powershell?  Also, does anyone know why these SSH keys are being returned as arrays of bytes rather than just text?  Is there a setting I could change with my query or within the openldap instance I'm querying to just force it to provide the text in the first place?

Thanks!


问:
How to get data from two different collections with same data structure in mongodb using nodejs?
I have two different collections with same data structure. Both collection have same data the only difference is collection name. How to search between this two collection based on dateReceived as you see in the below code. We create a new collection each month, I want to search between two months. Exampele from 2022-10-15 to  2022-11-15. Which will 2 collection report_202210 and report_202211.

First Collection Name: report_202210

```<code>{
"_id" : ObjectId("6392a26e4e3209b2bb23a250"),
"customerId" : "CUST0002",
"content" : "This is a test message",
"dateReceived" : "2022-10-22",
"sentStatus" : "Passed"
}
</code>```

Second Collection Name: report_202211

```<code>{
"_id" : ObjectId("6392a26e4e3209b2bb23a198"),
"customerId" : "CUST0003",
"content" : "This is a test message",
"dateReceived" : "2022-11-11",
"sentStatus" : "Passed"
}
</code>```

Body:
I have two different collections with same data structure. Both collection have same data the only difference is collection name. How to search between this two collection based on dateReceived as you see in the below code. We create a new collection each month, I want to search between two months. Exampele from 2022-10-15 to  2022-11-15. Which will 2 collection report_202210 and report_202211.

First Collection Name: report_202210

{
"_id" : ObjectId("6392a26e4e3209b2bb23a250"),
"customerId" : "CUST0002",
"content" : "This is a test message",
"dateReceived" : "2022-10-22",
"sentStatus" : "Passed"
}

Second Collection Name: report_202211

{
"_id" : ObjectId("6392a26e4e3209b2bb23a198"),
"customerId" : "CUST0003",
"content" : "This is a test message",
"dateReceived" : "2022-11-11",
"sentStatus" : "Passed"
}


问:
Scratch API websocket with rust
I am trying to create a rust program that can read and change cloud variables in scratch. I have tried reading through the various python libraries for this. These send request headers when connecting to the clouddata.scratch.mit.edu websocket. Does anyone know how to do this with rust tungstenite?

I have tried using http request builder for this but have only gotten errors. I need a way to connect and send requests to the scratch cloud variable websocket.I have tried using this method: How to set origin header to websocket client in Rust? but it has not worked.

Title: Scratch API websocket with rust


问:
Grouping IDs so they don't duplicate when queried
I'm trying to create a kind of contacts list based on whether the user has a message from them or not.
I am trying this:

```<code>        SELECT *
                FROM chat
                INNER JOIN user_info ON user_info.userID = chat.senderID
                INNER JOIN user_login ON user_login.userID = chat.senderID
                WHERE receiverID = :senderID
                GROUP BY receiverID
                ORDER BY chat.messageID ASC
</code>```

What I would like to happen is having all the IDs that are the same grouped together so when I use a foreach loop it doesn't return the same ID multiple times.

However I receive this error from my code:

Syntax error or access violation: 1055 Expression #1 of SELECT list is not in GROUP BY clause and contains nonaggregated column 'username.chat.messageID' which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by in"

I have tried searching it up and I found a few people saying to remove "only_full_group_by" in the sql mode variable. I cannot do this it gives me an error saying "#1227 - Access denied; you need (at least one of) the SUPER privilege(s) for this operation"

Any help on solving this would be great.

Body:
I'm trying to create a kind of contacts list based on whether the user has a message from them or not.
I am trying this:

        SELECT *
                FROM chat
                INNER JOIN user_info ON user_info.userID = chat.senderID
                INNER JOIN user_login ON user_login.userID = chat.senderID
                WHERE receiverID = :senderID
                GROUP BY receiverID
                ORDER BY chat.messageID ASC

What I would like to happen is having all the IDs that are the same grouped together so when I use a foreach loop it doesn't return the same ID multiple times.

However I receive this error from my code:

Syntax error or access violation: 1055 Expression #1 of SELECT list is not in GROUP BY clause and contains nonaggregated column 'username.chat.messageID' which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by in"

I have tried searching it up and I found a few people saying to remove "only_full_group_by" in the sql mode variable. I cannot do this it gives me an error saying "#1227 - Access denied; you need (at least one of) the SUPER privilege(s) for this operation"

Any help on solving this would be great.


问:
Inconsistency with ValidityState API between Chrome and Firefox
I have a super simple component with some inputs and some textareas. Using the ValidityState API I'm capable of consistently validating any input tag. However, I've found that textarea tags are unresponsive to the minlength attribute in a weird way.

For example, given the following element:

<textarea id="description" maxlength="200" minlength="20" required rows="5"/>
```
<p>I ran the following script:</p>
<pre class="lang-js prettyprint-override"><code>document.querySelector('#description').validity
</code>```

Before any interaction the it prints the following:

{
  badInput: false
  customError: false
  patternMismatch: false
  rangeOverflow: false
  rangeUnderflow: false
  stepMismatch: false
  tooLong: false
  tooShort: false
  typeMismatch: false
  valid: false
  valueMissing: true
}
```
<p>As soon as I type any character then the field is marked as valid when the <code>tooShort</code> property should be true.</p>
<p>I started to think I was wrong using the minlength property on a textarea tag but the specification says it is correct. I assumed maybe Chrome disagreed but the following CSS is correctly applied to the textarea element when the minlength attribute is not fulfilled.</p>
<pre class="lang-css prettyprint-override"><code>textarea:invalid  {
  outline: 1px solid red;
}
</code>```

In Firefox and Safari everything works as expected and the tooShort property has the value true. Am I missing something? Is this a bug in Chrome? Is there any documentation that explains this?

UPDATE:
So I found out it was because I was using the textarea as a self-closing tag. As soon as I changed it to:

<textarea id="description" maxlength="200" minlength="20" required rows="5"></textarea>
```
<p>Then everything started working normally and consistently between different browsers. However if you do this in react and pass a value as children then you get a warning saying:</p>
```Warning: Use the `defaultValue` or `value` props instead of setting children on <textarea>.
```

If you obey the warning and use the defaultValue or value attributes then the validation stops working only on Chrome again. I've reached a deadend here.

Body:
I have a super simple component with some inputs and some textareas. Using the ValidityState API I'm capable of consistently validating any input tag. However, I've found that textarea tags are unresponsive to the minlength attribute in a weird way.

For example, given the following element:

<textarea id="description" maxlength="200" minlength="20" required rows="5"/>

I ran the following script:

document.querySelector('#description').validity

Before any interaction the it prints the following:

{
  badInput: false
  customError: false
  patternMismatch: false
  rangeOverflow: false
  rangeUnderflow: false
  stepMismatch: false
  tooLong: false
  tooShort: false
  typeMismatch: false
  valid: false
  valueMissing: true
}

As soon as I type any character then the field is marked as valid when the tooShort property should be true.

I started to think I was wrong using the minlength property on a textarea tag but the specification says it is correct. I assumed maybe Chrome disagreed but the following CSS is correctly applied to the textarea element when the minlength attribute is not fulfilled.

textarea:invalid  {
  outline: 1px solid red;
}

In Firefox and Safari everything works as expected and the tooShort property has the value true. Am I missing something? Is this a bug in Chrome? Is there any documentation that explains this?

UPDATE:
So I found out it was because I was using the textarea as a self-closing tag. As soon as I changed it to:

<textarea id="description" maxlength="200" minlength="20" required rows="5"></textarea>

Then everything started working normally and consistently between different browsers. However if you do this in react and pass a value as children then you get a warning saying:

Warning: Use the `defaultValue` or `value` props instead of setting children on <textarea>.

If you obey the warning and use the defaultValue or value attributes then the validation stops working only on Chrome again. I've reached a deadend here.


问:
Uniformly distribute points in 4D
I am trying to distribute points onto a 4D surface. I have an implementation that evenly distributes data points onto a 3D surface octant.

```<code>n_samples = 100
N = int(np.floor(np.sqrt(0.25+2*n_samples) -0.5))

phis = np.linspace(start=0, stop=0.25*np.pi, num=N)

# points = np.empty((int(N*(N+1)/2), 3))
points = []
for n in range(1,N+1):
    phi = phis[n-1]
    for theta in np.linspace(start=0, stop=0.5*np.pi, num=n):
        x = np.sin(phi)*np.cos(theta)
        y = np.sin(phi)*np.sin(theta)
        z = np.cos(phi)
        points.append([x,y,z])

points = np.array(points)

df = pd.DataFrame(points, columns=['x', 'y', 'z'])
fig = px.scatter_3d(df, x='x', y='y', z='z')
fig.show()
</code>```

I am having difficulties in extending this to a 4D surface and visualizing it. Am I thinking about this correct? I need all my points evenly distributed in an octant. For 3D, I am leveraging the quadratic equation to distribute the points, for 4D, I am leveraging the cubic equation for the same.

```<code>n_samples = 100
poly = [1, 1.5, 0.5, 3*n_samples]
N = int(np.floor(-np.real(np.roots(poly)[0])) - 1)

phi_1s = np.linspace(start=0, stop=0.25*np.pi, num=N)

# points = np.empty((int(N*(N+1)/2), 3))
points = []
for n in range(1,N+1):
    phi_1 = phi_1s[n-1]
    for phi_2 in np.linspace(start=0, stop=0.25*np.pi, num=n):
        for phi_3 in np.linspace(start=0, stop=0.5*np.pi, num=n):
            x1 = np.cos(phi_1)
            x2 = np.sin(phi_1)*np.cos(phi_2)
            x3 = np.sin(phi_1)*np.sin(phi_2)*np.cos(phi_3)
            x4 = np.sin(phi_1)*np.sin(phi_2)*np.sin(phi_3)
            points.append([x1, x2, x3, x4])

points = np.array(points)

df = pd.DataFrame(points, columns=['x', 'y', 'z', 'c'])
fig = px.scatter_3d(df, x='x', y='y', z='z', color='c')
</code>```

Any thoughts on this is appreciated..

Title: Uniformly distribute points in 4D

Body:
I am trying to distribute points onto a 4D surface. I have an implementation that evenly distributes data points onto a 3D surface octant.

n_samples = 100
N = int(np.floor(np.sqrt(0.25+2*n_samples) -0.5))

phis = np.linspace(start=0, stop=0.25*np.pi, num=N)

# points = np.empty((int(N*(N+1)/2), 3))
points = []
for n in range(1,N+1):
    phi = phis[n-1]
    for theta in np.linspace(start=0, stop=0.5*np.pi, num=n):
        x = np.sin(phi)*np.cos(theta)
        y = np.sin(phi)*np.sin(theta)
        z = np.cos(phi)
        points.append([x,y,z])

points = np.array(points)

df = pd.DataFrame(points, columns=['x', 'y', 'z'])
fig = px.scatter_3d(df, x='x', y='y', z='z')
fig.show()

I am having difficulties in extending this to a 4D surface and visualizing it. Am I thinking about this correct? I need all my points evenly distributed in an octant. For 3D, I am leveraging the quadratic equation to distribute the points, for 4D, I am leveraging the cubic equation for the same.

n_samples = 100
poly = [1, 1.5, 0.5, 3*n_samples]
N = int(np.floor(-np.real(np.roots(poly)[0])) - 1)

phi_1s = np.linspace(start=0, stop=0.25*np.pi, num=N)

# points = np.empty((int(N*(N+1)/2), 3))
points = []
for n in range(1,N+1):
    phi_1 = phi_1s[n-1]
    for phi_2 in np.linspace(start=0, stop=0.25*np.pi, num=n):
        for phi_3 in np.linspace(start=0, stop=0.5*np.pi, num=n):
            x1 = np.cos(phi_1)
            x2 = np.sin(phi_1)*np.cos(phi_2)
            x3 = np.sin(phi_1)*np.sin(phi_2)*np.cos(phi_3)
            x4 = np.sin(phi_1)*np.sin(phi_2)*np.sin(phi_3)
            points.append([x1, x2, x3, x4])

points = np.array(points)

df = pd.DataFrame(points, columns=['x', 'y', 'z', 'c'])
fig = px.scatter_3d(df, x='x', y='y', z='z', color='c')

Any thoughts on this is appreciated..


问:
glPolygonOffset equivalent in Javafx
I'm trying to plot two MeshView at exact same location, one rendered with FILL and the other with LINE in order to give it wireframe looks. But unfortunately the wireframe only appears on the backside of the mesh as shown below.

In Java3D I fixed this problem using glPolygonOffset. Is there an equivalent to that in javafx?

Title: glPolygonOffset equivalent in Javafx


问:
Android RxJava Schedulers.computation() make the app laggy
currently I am using RxJava to do some heavy background work, unfortunately it seems like the work is quite heavy for some devices making the app "laggy" on these (for example animations).
I would like to hear any ideas of how I can improve (if possible) my RxJava code:

```<code>        Observable.create(emitter -> {
             // Do some heavy work, such as reading, parsing and saving a big XML file to a database
             emitter.doOnNext(); // To update the UI
             //Eventually emitter.onComplete() when job is down

            })
            .subscribeOn(Schedulers.computation())
            .observeOn(AndroidSchedulers.mainThread())
            .doOnNext(s1 -> {
                //Update the UI here (nothing heavy, just a textview)
            })
            .observeOn(AndroidSchedulers.mainThread())
            .doOnComplete(() -> {
                //Show a message to the user that the job is done
            })
            .subscribe();
</code>```

The heavy work inside the computation thread has already been optimized during a long period of time and we believe it cannot be optimized anymore (drastically at least..)

Body:
currently I am using RxJava to do some heavy background work, unfortunately it seems like the work is quite heavy for some devices making the app "laggy" on these (for example animations).
I would like to hear any ideas of how I can improve (if possible) my RxJava code:

        Observable.create(emitter -> {
             // Do some heavy work, such as reading, parsing and saving a big XML file to a database
             emitter.doOnNext(); // To update the UI
             //Eventually emitter.onComplete() when job is down

            })
            .subscribeOn(Schedulers.computation())
            .observeOn(AndroidSchedulers.mainThread())
            .doOnNext(s1 -> {
                //Update the UI here (nothing heavy, just a textview)
            })
            .observeOn(AndroidSchedulers.mainThread())
            .doOnComplete(() -> {
                //Show a message to the user that the job is done
            })
            .subscribe();

The heavy work inside the computation thread has already been optimized during a long period of time and we believe it cannot be optimized anymore (drastically at least..)


问:
How to add lengend to Sea Born plot
I have some trouble to add lengend to my seaborn plot. In the example I trying to let 0 represent "Not First Time". Let 1 represent "First Time".

enter image description here

Title: How to add lengend to Sea Born plot


问:
windows.h program compiles but doesnt run
I am writing a program with the windows API and it has two files. The first program is a function to draw a pixel, and the second program handles the window. I'm compiling using  g++ main.cpp graphics.cpp -o main -lgdi32, it will compile but when I try to run it nothing happens, there are no errors.
Graphics.cpp

```<code>#include <windows.h>
#include <time.h>

LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM);
static HWND hwnd { 0 };
void DrawPixel(HWND hwnd, int x, int y);

int WINAPI
WinMain (HINSTANCE hInstance, HINSTANCE hPrevInst, LPTSTR lpCmdLine, int nShowCmd) {

    MSG  msg;
    WNDCLASSW wc = {0};

    wc.style = CS_HREDRAW | CS_VREDRAW;
    wc.lpszClassName = L"Pixels";
    wc.hInstance     = hInstance;
    wc.hbrBackground = GetSysColorBrush(COLOR_3DFACE);
    wc.lpfnWndProc   = WndProc;
    wc.hCursor       = LoadCursor(0, IDC_ARROW);

    RegisterClassW(&wc);
    CreateWindowW(wc.lpszClassName, L"Pixels",
                WS_OVERLAPPEDWINDOW | WS_VISIBLE,
                100, 100, 300, 250, NULL, NULL, hInstance, NULL);

    while (GetMessage(&msg, NULL, 0, 0)) {

        TranslateMessage(&msg);
        DispatchMessage(&msg);
    }

    srand(time(NULL));

    return (int) msg.wParam;
}

LRESULT CALLBACK WndProc(HWND hwnd, UINT msg,
    WPARAM wParam, LPARAM lParam) {

    switch(msg) {

        case WM_PAINT:

            break;

        case WM_DESTROY:

            PostQuitMessage(0);
            return 0;
    }

    return DefWindowProcW(hwnd, msg, wParam, lParam);
}

void DrawPixel(int x, int y) {

    PAINTSTRUCT ps;
    RECT r;

    GetClientRect(hwnd, &r);

    if (r.bottom == 0) {

        return;
    }

    HDC hdc = BeginPaint(hwnd, &ps);

    SetPixel(hdc, x, y, RGB(255, 0, 0));

    EndPaint(hwnd, &ps);
}
</code>```

main.cpp

```<code>#include <iostream>
#include <windows.h>
#include <windef.h>

void DrawPixel(int x, int y);

int main(){
    DrawPixel(100, 100);
}
</code>```

I am pretty sure it has something to do with the windows handle and how I am retrieving it but no matter how I refactor my code it wont work.
Edit: It turns out the issue is that the WinMain function isnt running.

Body:
I am writing a program with the windows API and it has two files. The first program is a function to draw a pixel, and the second program handles the window. I'm compiling using  g++ main.cpp graphics.cpp -o main -lgdi32, it will compile but when I try to run it nothing happens, there are no errors.
Graphics.cpp

#include <windows.h>
#include <time.h>

LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM);
static HWND hwnd { 0 };
void DrawPixel(HWND hwnd, int x, int y);

int WINAPI
WinMain (HINSTANCE hInstance, HINSTANCE hPrevInst, LPTSTR lpCmdLine, int nShowCmd) {

    MSG  msg;
    WNDCLASSW wc = {0};

    wc.style = CS_HREDRAW | CS_VREDRAW;
    wc.lpszClassName = L"Pixels";
    wc.hInstance     = hInstance;
    wc.hbrBackground = GetSysColorBrush(COLOR_3DFACE);
    wc.lpfnWndProc   = WndProc;
    wc.hCursor       = LoadCursor(0, IDC_ARROW);

    RegisterClassW(&wc);
    CreateWindowW(wc.lpszClassName, L"Pixels",
                WS_OVERLAPPEDWINDOW | WS_VISIBLE,
                100, 100, 300, 250, NULL, NULL, hInstance, NULL);

    while (GetMessage(&msg, NULL, 0, 0)) {

        TranslateMessage(&msg);
        DispatchMessage(&msg);
    }

    srand(time(NULL));

    return (int) msg.wParam;
}

LRESULT CALLBACK WndProc(HWND hwnd, UINT msg,
    WPARAM wParam, LPARAM lParam) {

    switch(msg) {

        case WM_PAINT:

            break;

        case WM_DESTROY:

            PostQuitMessage(0);
            return 0;
    }

    return DefWindowProcW(hwnd, msg, wParam, lParam);
}

void DrawPixel(int x, int y) {

    PAINTSTRUCT ps;
    RECT r;

    GetClientRect(hwnd, &r);

    if (r.bottom == 0) {

        return;
    }

    HDC hdc = BeginPaint(hwnd, &ps);

    SetPixel(hdc, x, y, RGB(255, 0, 0));

    EndPaint(hwnd, &ps);
}

main.cpp

#include <iostream>
#include <windows.h>
#include <windef.h>

void DrawPixel(int x, int y);

int main(){
    DrawPixel(100, 100);
}

I am pretty sure it has something to do with the windows handle and how I am retrieving it but no matter how I refactor my code it wont work.
Edit: It turns out the issue is that the WinMain function isnt running.