问:
Android studio how can I only select one checkbox in 2 recycler views
On my Activity I got 2 recyclerviews above each other. Each recyclerview got items with a checkbox.
How can I implement that if a checkbox is selected in the upper recyclerview, all checkboxes in the lower recyclerview are no longer selected?

The same procedure should also work the other way around, if a checkbox is selected in the lower recycler view, all checkboxes in the upper recycler view should no longer be selected.

Can someone tell me how it could work? Could it work, for example, with a broadcast?

My code isn't working. If I check the upper Checkbox, the checkbox in the under recycler view stays checked.

Here my code from my first recycler view:

```<code>@Override
public void onBindViewHolder(@NonNull ViewHolder holder, @SuppressLint("RecyclerView") int position) {
    LocalBroadcastManager.getInstance(context).registerReceiver(mNameReceiver, new IntentFilter("checkbox_adapter2"));
    selectHolder = holder;
    Name name = nameArrayList.get(position);
    holder.nameView.setText(name.getName());
    holder.checkBox.setVisibility(View.VISIBLE);

    if (isCheckBoxChecked) {
        holder.checkBox.setChecked(false);
    }

    holder.checkBox.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            rowIndex = position;
            notifyDataSetChanged();

            sendBroadCast(group);
            sendCheckBoxBroadCast();
            isClicked = true;
        }
    });

    if (!isClicked) {
        if (selectedName != null) {
            if (name.getName().equals(selectedName.getName())){
                holder.checkBox.setChecked(true);
                sendBroadCast(group);
                sendCheckBoxBroadCast();
            }
        }
    } else {
        if (rowIndex == position) {
            holder.checkBox.setChecked(true);
        } else {
            holder.checkBox.setChecked(false);
        }
    }
}

private void sendCheckBoxBroadCast() {
        Intent intent = new Intent("checkbox_adapter1");
        intent.putExtra("isCheckBoxChecked", true);
        LocalBroadcastManager.getInstance(context).sendBroadcast(intent);
    }
</code>```

And here my 2. Adapter

```<code>@Override
public void onBindViewHolder(@NonNull RecentlyNameViewHolder holder, @SuppressLint("RecyclerView") int position) {
    LocalBroadcastManager.getInstance(context).registerReceiver(mNameReceiver, new IntentFilter("checkbox_adapter1"));
    String name = nameArrayList.get(((nameArrayList.size() - 1) - position));

    holder.nameView.setText(name);
    holder.checkBox.setVisibility(View.VISIBLE);

    if (isCheckBoxChecked) {
        holder.checkBox.setChecked(false);
    }

    holder.checkBox.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            rowIndex = position;
            notifyDataSetChanged();
            sendGroupBroadcast(name);
            sendCheckBoxBroadCast();

            isClicked = true;
        }
    });

    if (!isClicked) {
        if (selectedName != null) {
            if (name.equals(selectedName.getName())){
                holder.checkBox.setChecked(true);
                sendGroupBroadcast(groupName);
                sendCheckBoxBroadCast();
            }
        }
    } else {
        if (rowIndex == position) {
            holder.checkBox.setChecked(true);
        } else {
            holder.checkBox.setChecked(false);
        }
    }

}

 private void sendCheckBoxBroadCast() {
        Intent intent = new Intent("checkbox_adapter2");
        intent.putExtra("isCheckBoxChecked", true);
        LocalBroadcastManager.getInstance(context).sendBroadcast(intent);
    }
</code>```

Body:
On my Activity I got 2 recyclerviews above each other. Each recyclerview got items with a checkbox.
How can I implement that if a checkbox is selected in the upper recyclerview, all checkboxes in the lower recyclerview are no longer selected?

The same procedure should also work the other way around, if a checkbox is selected in the lower recycler view, all checkboxes in the upper recycler view should no longer be selected.

Can someone tell me how it could work? Could it work, for example, with a broadcast?

My code isn't working. If I check the upper Checkbox, the checkbox in the under recycler view stays checked.

Here my code from my first recycler view:

@Override
public void onBindViewHolder(@NonNull ViewHolder holder, @SuppressLint("RecyclerView") int position) {
    LocalBroadcastManager.getInstance(context).registerReceiver(mNameReceiver, new IntentFilter("checkbox_adapter2"));
    selectHolder = holder;
    Name name = nameArrayList.get(position);
    holder.nameView.setText(name.getName());
    holder.checkBox.setVisibility(View.VISIBLE);

    if (isCheckBoxChecked) {
        holder.checkBox.setChecked(false);
    }

    holder.checkBox.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            rowIndex = position;
            notifyDataSetChanged();

            sendBroadCast(group);
            sendCheckBoxBroadCast();
            isClicked = true;
        }
    });

    if (!isClicked) {
        if (selectedName != null) {
            if (name.getName().equals(selectedName.getName())){
                holder.checkBox.setChecked(true);
                sendBroadCast(group);
                sendCheckBoxBroadCast();
            }
        }
    } else {
        if (rowIndex == position) {
            holder.checkBox.setChecked(true);
        } else {
            holder.checkBox.setChecked(false);
        }
    }
}

private void sendCheckBoxBroadCast() {
        Intent intent = new Intent("checkbox_adapter1");
        intent.putExtra("isCheckBoxChecked", true);
        LocalBroadcastManager.getInstance(context).sendBroadcast(intent);
    }

And here my 2. Adapter

@Override
public void onBindViewHolder(@NonNull RecentlyNameViewHolder holder, @SuppressLint("RecyclerView") int position) {
    LocalBroadcastManager.getInstance(context).registerReceiver(mNameReceiver, new IntentFilter("checkbox_adapter1"));
    String name = nameArrayList.get(((nameArrayList.size() - 1) - position));

    holder.nameView.setText(name);
    holder.checkBox.setVisibility(View.VISIBLE);

    if (isCheckBoxChecked) {
        holder.checkBox.setChecked(false);
    }

    holder.checkBox.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            rowIndex = position;
            notifyDataSetChanged();
            sendGroupBroadcast(name);
            sendCheckBoxBroadCast();

            isClicked = true;
        }
    });

    if (!isClicked) {
        if (selectedName != null) {
            if (name.equals(selectedName.getName())){
                holder.checkBox.setChecked(true);
                sendGroupBroadcast(groupName);
                sendCheckBoxBroadCast();
            }
        }
    } else {
        if (rowIndex == position) {
            holder.checkBox.setChecked(true);
        } else {
            holder.checkBox.setChecked(false);
        }
    }

}

 private void sendCheckBoxBroadCast() {
        Intent intent = new Intent("checkbox_adapter2");
        intent.putExtra("isCheckBoxChecked", true);
        LocalBroadcastManager.getInstance(context).sendBroadcast(intent);
    }


来源: stackexchange

问:
Restricting users on Azure Graph API
Microsoft Graph Api for Calendars defines requirement
to add permission to app:

Calendars.ReadWrite - Read and write calendars in all mailboxes

see:
https://learn.microsoft.com/en-us/graph/api/calendar-post-events

Is there a way to restrict it further on Azure?

For example:
restrict the app to only be able to read calendars from a user john@bestpirnt.com, not a ceo@bestprint.com

I Looked through documentation
https://learn.microsoft.com/en-us/azure/api-management/api-management-access-restriction-policies

It's seems to miss this type of functionality.

ContentLicense: CC BY-SA 4.0

Title: Restricting users on Azure Graph API


问:
Connecting a user's MongoDB account to store their data
I'm a beginner, so I'm sorry if this sounds dumb but I want to make a website using django and React where I want to store sensitive information about a user. I want the user to be the only one who can see/access the data entered by them, I do not want to store everyone's data on a MongoDB account made by me. Is it possible to link a MongoDB account specified by the user so that their data is saved into their private MongoDB account? Complete privacy is the goal here. How else can I go about this problem?

I tried to look for connecting multiple MongoDB accounts but I didn't find anything related to what I'm looking for. I might have been looking in the wrong direction. Would really appreciate any help!


问:
Log4j2 configuration on Weblogic server
I want to know how to configure log4j2.xml file in my application. I'm deploying the application in WebLogic server.
What is happening is the EAR file is getting deployed but it fails to generate the logs.

I tried keeping the log4j2.xml file inside WEB-INF , but still no luck

Title: Log4j2 configuration on Weblogic server


问:
Webpack using define plugin with compiled output
I'm looking to use webpack's DefinePlugin to provide a json resource inside my application

However this JSON resource is itself the output of a plugin which is being written to the output directory. I.e. the plugin creates a JSON file based on the application code

I can't use the DefinePlugin as I normally would, as the file doesn't exist yet at the point of usage

Here's my current webpack configuration, note that this is using angular's custom-webpack builder, so it's expanding Angular's default webpack configuration:

```<code>var CycloneDxWebpackPlugin = require('@cyclonedx/webpack-plugin').CycloneDxWebpackPlugin
var webpack = require('webpack')

module.exports = function(config) {
  if (config.plugins == null)
    config.plugins = []

  config.plugins.push(
    new CycloneDxWebpackPlugin({
      specVersion: '1.4',
      outputLocation: './sbom'
    })
  )

  /*
  * Here I'm not able to use the DefinePlugin, as the file doesn't exist yet
  config.plugins.push(
    new webpack.DefinePlugin({
      sbom: JSON.stringify(
        require(config.output.path + '/sbom/bom.json')
      )
    })
  )
  */

  return config
}
</code>```

Any ideas for workarounds? I'd like to avoid loading the json async afterwards, as this application is meant to be a PWA, and should work offline

Body:
I'm looking to use webpack's DefinePlugin to provide a json resource inside my application

However this JSON resource is itself the output of a plugin which is being written to the output directory. I.e. the plugin creates a JSON file based on the application code

I can't use the DefinePlugin as I normally would, as the file doesn't exist yet at the point of usage

Here's my current webpack configuration, note that this is using angular's custom-webpack builder, so it's expanding Angular's default webpack configuration:

var CycloneDxWebpackPlugin = require('@cyclonedx/webpack-plugin').CycloneDxWebpackPlugin
var webpack = require('webpack')

module.exports = function(config) {
  if (config.plugins == null)
    config.plugins = []

  config.plugins.push(
    new CycloneDxWebpackPlugin({
      specVersion: '1.4',
      outputLocation: './sbom'
    })
  )

  /*
  * Here I'm not able to use the DefinePlugin, as the file doesn't exist yet
  config.plugins.push(
    new webpack.DefinePlugin({
      sbom: JSON.stringify(
        require(config.output.path + '/sbom/bom.json')
      )
    })
  )
  */

  return config
}

Any ideas for workarounds? I'd like to avoid loading the json async afterwards, as this application is meant to be a PWA, and should work offline


问:
Can't see collections in VS2022 debugger in Blazor
I'm debugging a BlazorWASM application in VS2022 - all works well except if I place a breakpoint in the code.

The Autos window will populate with the local variables (including collections) but when I attempt to drill into a collection (a list in my case) I merely see 'Capacity' and 'Count' and no details of the items in the list itself.

I think this only started with VS2022 - v17.4.

Not sure what I'm missing here.  More detail:

Runtime: .net 7.0.0
Nuget packages:  all v7.0.0


问:
How to reduce a multi-index pandas dataframe to single-index?
I ave acquired a pandas dataframe that has a multi-index via the code below:

```<code>price_data = yf.dpwnload(tickers = tickers_str, period = "2y", interval = "1wk", group_by = 'ticker')
</code>```

The acquired dataframe is shown in the image below.

How can I turn this dataframe into single-index?

Columns of dataset:

```<code>        ( 'SOKM.IS',   'Open'),
        ( 'SOKM.IS',   'Close'),
        ('EGEEN.IS',   'Open'),
        ('EGEEN.IS',  'Close'),...
</code>```

Desired output:

Column name must be the first index (i.e. "SOKM.IS", "EGEEN.IS", etc.)

value must be the value at "Close" index of 2nd index

Body:
I ave acquired a pandas dataframe that has a multi-index via the code below:

price_data = yf.dpwnload(tickers = tickers_str, period = "2y", interval = "1wk", group_by = 'ticker')

The acquired dataframe is shown in the image below.

How can I turn this dataframe into single-index?

Columns of dataset:

        ( 'SOKM.IS',   'Open'),
        ( 'SOKM.IS',   'Close'),
        ('EGEEN.IS',   'Open'),
        ('EGEEN.IS',  'Close'),...

Desired output:

Column name must be the first index (i.e. "SOKM.IS", "EGEEN.IS", etc.)

value must be the value at "Close" index of 2nd index


问:
Gradient indicator color in com.google.android.material.progressindicator.CircularProgressIndicator
I write code for material.progressindicator.CircularProgressIndicator as below.

    <com.google.android.material.progressindicator.CircularProgressIndicator
            android:id="@+id/cpFront"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:rotation="180"
            android:progress="10"
            app:indicatorColor="@color/black"
            app:indicatorDirectionCircular="counterclockwise"
            app:indicatorSize="200dp"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent"
            app:trackColor="#00555555"
            app:trackCornerRadius="10dp"
            app:trackThickness="60dp" />
```

Now, I need to set gradient color instead of black color in indicator color. Please suggest me how can to achieve this? Thanks in advance.

Body:
I write code for material.progressindicator.CircularProgressIndicator as below.

    <com.google.android.material.progressindicator.CircularProgressIndicator
            android:id="@+id/cpFront"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:rotation="180"
            android:progress="10"
            app:indicatorColor="@color/black"
            app:indicatorDirectionCircular="counterclockwise"
            app:indicatorSize="200dp"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent"
            app:trackColor="#00555555"
            app:trackCornerRadius="10dp"
            app:trackThickness="60dp" />

Now, I need to set gradient color instead of black color in indicator color. Please suggest me how can to achieve this? Thanks in advance.


问:
Scala match on generic type
I am trying to do a match on a value based on its type, and there is a case where the expected type is a generic, like below:

def foo(bar: Matchable) = bar match
    case (bar: Vector[String]) => println(bar.mkString(","))
```

However, I get the following warning at runtime:

the type test for Vector[String] cannot be checked at runtime

Why cannot it be checked and how could I overcome this?

Title: Scala match on generic type

Body:
I am trying to do a match on a value based on its type, and there is a case where the expected type is a generic, like below:

def foo(bar: Matchable) = bar match
    case (bar: Vector[String]) => println(bar.mkString(","))

However, I get the following warning at runtime:

the type test for Vector[String] cannot be checked at runtime

Why cannot it be checked and how could I overcome this?


问:
how to send confirmation mail after sign up in rails
in my rails application i have registration_controller, session_controller and confirmation_controller.now i want to send the email after user signing up.so how can i do this.if anyone know the process please kindly share your code so that i can understand,how mailer work.please help me.

```<code>registration_controller.rb

class Users::RegistrationsController < Devise::RegistrationsController

  private

  def respond_with(resource, options={})
     if resource.persisted?
       render json: {
          status: { code: 200, message: 'Signed up successfully', data: resource }
       }, status: :ok
       else
        render json: {
          status: { message: 'user could not be created successfull',
            errors: resource.errors.full_messages }, status: :unprocessable_entity
        }
     end
  end

end
</code>```
```<code>session_controller.rb

class Users::SessionsController < Devise::SessionsController
  respond_to :json

  private

   def respond_with(resource, options={})
     if resource.persisted?
      render json: {
       status: { code: 200, message: "Signed in successfully",
         data: current_user }
     },status: :ok
       else
         render json: {
           status: 401,
           message: "check your credential"
         }
     end
   end

   def respond_to_on_destroy
     jwt_payload = JWT.decode(request.headers['Authorization'].split(' ')[1], Rails.application.credentials.fetch(:secret_key_base)).first
    current_user =  User.find(jwt_payload['sub'])
     if current_user
       render json: {
         status: 200,
         message: "Signed out successfully"
       }, status: :ok
       else
         render json: {
           status: 401,
           message: "user has no active sessaion"
         }, status: :unauthorized
     end
   end
end

</code>```
```<code>routes.rb

Rails.application.routes.draw do
  resources :books
  # resources :userforms
  get 'book/', to: 'books#showImages';
  devise_for :users, controllers: {
    sessions: 'users/sessions',
    registrations: 'users/registrations',
    confirmations: 'users/confirmations',
  }
  # resources :userforms
  resources :userforms, only: [:show ,:index,:create,:showUsers]

  get 'userform/', to: 'userforms#showUsers';

end

</code>```

above are my registrationcontroller, session_controller and my routes.rb.so now i want to send email how can i do this.

Thanks in advance.

Body:
in my rails application i have registration_controller, session_controller and confirmation_controller.now i want to send the email after user signing up.so how can i do this.if anyone know the process please kindly share your code so that i can understand,how mailer work.please help me.

registration_controller.rb

class Users::RegistrationsController < Devise::RegistrationsController

  private

  def respond_with(resource, options={})
     if resource.persisted?
       render json: {
          status: { code: 200, message: 'Signed up successfully', data: resource }
       }, status: :ok
       else
        render json: {
          status: { message: 'user could not be created successfull',
            errors: resource.errors.full_messages }, status: :unprocessable_entity
        }
     end
  end

end

session_controller.rb

class Users::SessionsController < Devise::SessionsController
  respond_to :json

  private

   def respond_with(resource, options={})
     if resource.persisted?
      render json: {
       status: { code: 200, message: "Signed in successfully",
         data: current_user }
     },status: :ok
       else
         render json: {
           status: 401,
           message: "check your credential"
         }
     end
   end

   def respond_to_on_destroy
     jwt_payload = JWT.decode(request.headers['Authorization'].split(' ')[1], Rails.application.credentials.fetch(:secret_key_base)).first
    current_user =  User.find(jwt_payload['sub'])
     if current_user
       render json: {
         status: 200,
         message: "Signed out successfully"
       }, status: :ok
       else
         render json: {
           status: 401,
           message: "user has no active sessaion"
         }, status: :unauthorized
     end
   end
end

routes.rb

Rails.application.routes.draw do
  resources :books
  # resources :userforms
  get 'book/', to: 'books#showImages';
  devise_for :users, controllers: {
    sessions: 'users/sessions',
    registrations: 'users/registrations',
    confirmations: 'users/confirmations',
  }
  # resources :userforms
  resources :userforms, only: [:show ,:index,:create,:showUsers]

  get 'userform/', to: 'userforms#showUsers';

end

above are my registrationcontroller, session_controller and my routes.rb.so now i want to send email how can i do this.

Thanks in advance.


问:
Facebook Login API Disabled -- Unable to Test Flow
My app access to the Facebook API has been disabled, now I cannot get the app approved because Facebook says the login process does not work. How am I supposed to have Facebook Login API work if they disable access to it? It's a very frustrating issue, because they will not re-enable access until it works and it will not work until they re-enable access.

Has anyone else dealt with this circular loop?

"We've disabled this app for violating the Facebook Platform Policies. You can continue to use it in development mode. Read more or appeal"

I've updated the app and it is working fine, the same exact code has been used before and is working. But i cannot test the login flow until the API is re-enabled.

Edit: This is the message that appears when i use Facebook login  "FirebaseAuthInvalidCredentialsException: The supplied auth credential is malformed or has expired. [ Invalid access_token, error code 43 ]"


问:
Confusion over Closure - Pyspark
I am new to spark and i have read several articles about Closure but I am unable to understand the logic can someone please clarify.

For counters we should use accumulators coz executer cant see the counter variable on driver side in cluster mode and works on local copy...the isnt this the same with any operation, transformation...since executors reside on different nodes then they cant see whats on driver node. What is the difference if I do a collect() then also executors are not able to view driver node variables what happens then?

I thought the executors work on its own partitions and send their data to driver & driver combines all output. Is my understanding wrong?

Title: Confusion over Closure - Pyspark


问:
Firebase Crashlytics not generating crash report for release APKs Android
After integrating Firebase Crashlytics in app, am not receiving the crash report in Firebase Crashlytics dashboard for release builds. For debug builds I am restricting to generate the report and only generating the report for release builds.

App level build.gradle file

```<code>plugins {
    id 'com.android.application'
    id 'com.google.gms.google-services'
    id 'com.google.firebase.crashlytics'
}

  buildTypes {
        def enableCrashlyticsInDebugBuild = false
        def enableCrashlyticsInReleaseBuild = true

        debug {
            minifyEnabled false
            testCoverageEnabled = true
            manifestPlaceholders = [crashlyticsEnabled:"${enableCrashlyticsInDebugBuild}"]
        }
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
            signingConfig signingConfigs.debug_signing
            manifestPlaceholders = [crashlyticsEnabled:"${enableCrashlyticsInReleaseBuild}"]
        }
    }

dependencies {
        implementation platform('com.google.firebase:firebase-bom:30.3.1')
        implementation 'com.google.firebase:firebase-crashlytics-ktx'
        implementation 'com.google.firebase:firebase-analytics-ktx'
}
</code>```

Project level build.gradle file

```<code> repositories {
        google()
        jcenter()
        maven {
            url "https://plugins.gradle.org/m2/"
        }
        mavenCentral()
    }

    dependencies {
        classpath "com.google.firebase:firebase-crashlytics-gradle:2.9.2"
                 }
</code>```

AndroidManifest.xml

```<code> <meta-data
            android:name="firebase_crashlytics_collection_enabled"
            android:value="${crashlyticsEnabled}" />
</code>```

Can anyone please suggest me where I am wrong? After checked all the SO answers didn't find out any solution.

Body:
After integrating Firebase Crashlytics in app, am not receiving the crash report in Firebase Crashlytics dashboard for release builds. For debug builds I am restricting to generate the report and only generating the report for release builds.

App level build.gradle file

plugins {
    id 'com.android.application'
    id 'com.google.gms.google-services'
    id 'com.google.firebase.crashlytics'
}

  buildTypes {
        def enableCrashlyticsInDebugBuild = false
        def enableCrashlyticsInReleaseBuild = true

        debug {
            minifyEnabled false
            testCoverageEnabled = true
            manifestPlaceholders = [crashlyticsEnabled:"${enableCrashlyticsInDebugBuild}"]
        }
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
            signingConfig signingConfigs.debug_signing
            manifestPlaceholders = [crashlyticsEnabled:"${enableCrashlyticsInReleaseBuild}"]
        }
    }

dependencies {
        implementation platform('com.google.firebase:firebase-bom:30.3.1')
        implementation 'com.google.firebase:firebase-crashlytics-ktx'
        implementation 'com.google.firebase:firebase-analytics-ktx'
}

Project level build.gradle file

 repositories {
        google()
        jcenter()
        maven {
            url "https://plugins.gradle.org/m2/"
        }
        mavenCentral()
    }

    dependencies {
        classpath "com.google.firebase:firebase-crashlytics-gradle:2.9.2"
                 }

AndroidManifest.xml

 <meta-data
            android:name="firebase_crashlytics_collection_enabled"
            android:value="${crashlyticsEnabled}" />

Can anyone please suggest me where I am wrong? After checked all the SO answers didn't find out any solution.


问:
Why is R only extracting a shapefile field values for certain points?
Apologies if this belongs in GIS stackexchange, I'm happy to be redirected there, but I have a feeling it's something in my code that is the problem.

I have a shapefile of the Terrestrial Ecoregions of the World that contains fields such as Ecoregion Name, Biome, and, Realm, that I want to extract for a range of ~50,000 lat/long points. An example of the data would be

ID
ddlat
ddlong

221784
6.133
37.700

221814
26.450
74.700

221826
-17.716
-63.633

221827
47.933
8.083

221830
-24.283
131.600

My code (sample from within a much larger script) currently looks like the following:

```<code>teow <- shapefile("~/wwf_terr_ecos.shp")
teowlltest <- read.csv(file="~/teow_csv.csv",stringsAsFactors=FALSE)
teowlltest <- na.omit(teowlltest)
teowlltestSPT <- SpatialPoints(teowlltest, proj4string = CRS(proj4string(teow)))
overteow <- over(teowlltestSPT, teow)
bindtest <- cbind(teowlltest,overteow)
</code>```

My problem is that the code works ... but only for 15 of the latlong points. I'm not expecting a 100% success rate, as I know the shapefile isn't perfect in coastline areas etc, but when mapped, far more than 15 points lie within the TEOW shapefile. The 15 that are being extracted are also incorrect when compared to maps of the biomes/realms etc. How do I get it to extract the field data for all the points and do it correctly? I've tried renaming/reorganising the csv (for example Y,X or Latitude, Longitude instead of ddlat, ddlong, and placing longitude as the first field), and subsetting the data, but only the same 15 keep extracting. I can't separate the Lat/Long information from the ID either, so I'm hoping that's not the problem here, but I can't see why it would be, if some of the points extract fine. Any help will be much appreciated, and I'm happy to answer any questions/supply more information if needed. Thanks!

Example output currently:

Showing that some have extracted (but not correctly) and all the others have just refused. Duplicate lat/longs removed for brevity.

Body:
Apologies if this belongs in GIS stackexchange, I'm happy to be redirected there, but I have a feeling it's something in my code that is the problem.

I have a shapefile of the Terrestrial Ecoregions of the World that contains fields such as Ecoregion Name, Biome, and, Realm, that I want to extract for a range of ~50,000 lat/long points. An example of the data would be

ID
ddlat
ddlong

221784
6.133
37.700

221814
26.450
74.700

221826
-17.716
-63.633

221827
47.933
8.083

221830
-24.283
131.600

My code (sample from within a much larger script) currently looks like the following:

teow <- shapefile("~/wwf_terr_ecos.shp")
teowlltest <- read.csv(file="~/teow_csv.csv",stringsAsFactors=FALSE)
teowlltest <- na.omit(teowlltest)
teowlltestSPT <- SpatialPoints(teowlltest, proj4string = CRS(proj4string(teow)))
overteow <- over(teowlltestSPT, teow)
bindtest <- cbind(teowlltest,overteow)

My problem is that the code works ... but only for 15 of the latlong points. I'm not expecting a 100% success rate, as I know the shapefile isn't perfect in coastline areas etc, but when mapped, far more than 15 points lie within the TEOW shapefile. The 15 that are being extracted are also incorrect when compared to maps of the biomes/realms etc. How do I get it to extract the field data for all the points and do it correctly? I've tried renaming/reorganising the csv (for example Y,X or Latitude, Longitude instead of ddlat, ddlong, and placing longitude as the first field), and subsetting the data, but only the same 15 keep extracting. I can't separate the Lat/Long information from the ID either, so I'm hoping that's not the problem here, but I can't see why it would be, if some of the points extract fine. Any help will be much appreciated, and I'm happy to answer any questions/supply more information if needed. Thanks!

Example output currently:

Showing that some have extracted (but not correctly) and all the others have just refused. Duplicate lat/longs removed for brevity.


问:
Template Pattern how to update each method status in Main Method c# Windows App
Template Pattern how to update each method status in Main Method c# Windows App

```<code>using System;
namespace TemplateMethodDesignPattern
{
    public abstract class HouseTemplate
    {
        // Template method defines the sequence for building a house
        public void BuildHouse()
        {
            BuildFoundation();
            BuildPillars();
            BuildWalls();
            BuildWindows();
            Console.WriteLine("House is built");
        }

        // Methods to be implemented by subclasses
        protected abstract void BuildFoundation();
        protected abstract void BuildPillars();
        protected abstract void BuildWalls();
        protected abstract void BuildWindows();
    }
}
</code>```

on Main method i wanted to show each method status/output based on progress in listbox c#

tried with delegates but didn't succeeded.

Body:
Template Pattern how to update each method status in Main Method c# Windows App

using System;
namespace TemplateMethodDesignPattern
{
    public abstract class HouseTemplate
    {
        // Template method defines the sequence for building a house
        public void BuildHouse()
        {
            BuildFoundation();
            BuildPillars();
            BuildWalls();
            BuildWindows();
            Console.WriteLine("House is built");
        }

        // Methods to be implemented by subclasses
        protected abstract void BuildFoundation();
        protected abstract void BuildPillars();
        protected abstract void BuildWalls();
        protected abstract void BuildWindows();
    }
}

on Main method i wanted to show each method status/output based on progress in listbox c#

tried with delegates but didn't succeeded.


问:
Strapi: How to investigate Strapi startup slowness
I have a server at work based on Strapi v3.6.3. Over time, I am seeing that the server startup (npm run develop) time has gone up from <1 minute to ~4 minutes at present. I want to investigate this more to see what task(s) are performed during Strapi startup and how much time do they consume.

How can I go about this analysis? Unfortunately, I'm unable to find helpful documentation to help with this.

Is there a logging system where Strapi maintains startup logs that I could switch on to check further?

I've tried setting STRAPI_LOG_LEVEL to trace (as documented in https://strapi.gitee.io/documentation/3.0.0-beta.x/concepts/logging.html) and bootup strapi but it is not helping.


问:
Error while importing CSV to sql using powershell
The below variable alone is not working during the import. I am new into entire coding area and I think this is some basics which I don't understand.

```<code>$csvPath =$(Get-Date).AddMonths(-1) Get-Item \\SMC01702.WWG00M.ROOTDOM.NET\PROG_D$\1200000024\FSSL-ACCOUNTING\TCCS\*.csv* | where { $_.LastWriteTime -gt $csvPath} | Foreach {“File Name: ” + $_.Name}
</code>```

When I try with the direct path as below it does work, however when $csvpath is applied it fails. can someone please help.

Other variables are:

```<code>#Variables
$csvDelimiter = ";"
$serverName = "sm024591.wwg00m.rootdom.net"
$databaseName = "FSSL-Accounting"
$tableName = "TCCS"
$tableSchema = "import"

#Truncate the Table that has older data
Invoke-Sqlcmd -ServerInstance $serverName -Database $databaseName -Query "TRUNCATE TABLE $tableschema.$tableName"

#Import the CSV and Delimit the data for ';' / Validate the input
$data = Import-Csv -Path '\\SMC01702.WWG00M.ROOTDOM.NET\PROG_D$\1200000024\FSSL-ACCOUNTING\TCCS\TCCS_122022.csv' -Delimiter $csvDelimiter
</code>```

$data | select -first 10

```<code>#Write the data to SQL Server
Write-SqlTableData -DatabaseName $databaseName -TableName TCCS -SchemaName import -ServerInstance $serverName -InputData $data
</code>```

But when I try with the variable

```<code>#Variables
$csvDelimiter = ";"
$serverName = "sm024591.wwg00m.rootdom.net"
$databaseName = "FSSL-Accounting"
$tableName = "TCCS"
$tableSchema = "import"

#Truncate the Table that has older data
Invoke-Sqlcmd -ServerInstance $serverName -Database $databaseName -Query "TRUNCATE TABLE     $tableschema.$tableName"

#Import the CSV and Delimit the data for ';' / Validate the input
$data = Import-Csv -Path $csvPat**h -Delimiter $csvDelimiter
$data | select -first 10

#Write the data to SQL Server
Write-SqlTableData -DatabaseName $databaseName -TableName TCCS -SchemaName import -ServerInstance   $serverName -InputData $data
</code>```

Body:
The below variable alone is not working during the import. I am new into entire coding area and I think this is some basics which I don't understand.

$csvPath =$(Get-Date).AddMonths(-1) Get-Item \\SMC01702.WWG00M.ROOTDOM.NET\PROG_D$\1200000024\FSSL-ACCOUNTING\TCCS\*.csv* | where { $_.LastWriteTime -gt $csvPath} | Foreach {“File Name: ” + $_.Name}

When I try with the direct path as below it does work, however when $csvpath is applied it fails. can someone please help.

Other variables are:

#Variables
$csvDelimiter = ";"
$serverName = "sm024591.wwg00m.rootdom.net"
$databaseName = "FSSL-Accounting"
$tableName = "TCCS"
$tableSchema = "import"

#Truncate the Table that has older data
Invoke-Sqlcmd -ServerInstance $serverName -Database $databaseName -Query "TRUNCATE TABLE $tableschema.$tableName"

#Import the CSV and Delimit the data for ';' / Validate the input
$data = Import-Csv -Path '\\SMC01702.WWG00M.ROOTDOM.NET\PROG_D$\1200000024\FSSL-ACCOUNTING\TCCS\TCCS_122022.csv' -Delimiter $csvDelimiter

$data | select -first 10

#Write the data to SQL Server
Write-SqlTableData -DatabaseName $databaseName -TableName TCCS -SchemaName import -ServerInstance $serverName -InputData $data

But when I try with the variable

#Variables
$csvDelimiter = ";"
$serverName = "sm024591.wwg00m.rootdom.net"
$databaseName = "FSSL-Accounting"
$tableName = "TCCS"
$tableSchema = "import"

#Truncate the Table that has older data
Invoke-Sqlcmd -ServerInstance $serverName -Database $databaseName -Query "TRUNCATE TABLE     $tableschema.$tableName"

#Import the CSV and Delimit the data for ';' / Validate the input
$data = Import-Csv -Path $csvPat**h -Delimiter $csvDelimiter
$data | select -first 10

#Write the data to SQL Server
Write-SqlTableData -DatabaseName $databaseName -TableName TCCS -SchemaName import -ServerInstance   $serverName -InputData $data


问:
Concatenate asp-validation-for result with an Icon
I have an ASP MVC view that contains only a Textbox that takes a string, and a submit button to submit the value.
I want to add the validation error message with an Icon before it as in the following snippet:

```<code><div class="form-group row">
    <label class="col-sm-4 col-form-label">Check User Id</label>
    <div class="col-sm-8">
        <input asp-for="@Model.userId" type="text" class="form-control" />
    </div>
</div>
<div class="form-group row">
    <label class="col-sm-4 col-form-label"></label>
    <div class="col-sm-8">
        <input type="submit" class="btn btn-primary" value="Check" asp-action="Index" asp-controller="UserController" />
        <div class="col-sm-8">
            <i asp-validation-for="userId" class="fa fa-info-circle"></i>
            <span asp-validation-for="userId" class="text-dark"></span>
        </div>
    </div>
</div>
</code>```

My Problem now is that the info Icon is always showing, and I want it to show ONLY if there is an error/validation message. Is there a way to achieve that from the view only with no changes to the Business logic?

Body:
I have an ASP MVC view that contains only a Textbox that takes a string, and a submit button to submit the value.
I want to add the validation error message with an Icon before it as in the following snippet:

    Check User Id

        <input asp-for="@Model.userId" type="text" class="form-control" />

        <input type="submit" class="btn btn-primary" value="Check" asp-action="Index" asp-controller="UserController" />

My Problem now is that the info Icon is always showing, and I want it to show ONLY if there is an error/validation message. Is there a way to achieve that from the view only with no changes to the Business logic?


问:
In python project(with page object) conftest file doesn't get driver from pages
I try to create the project with page object(python 3.9) and my conftest.py file doesn't receive any driver from its pages.
Any page has _init constructors,but in the conftest.py file we can see that no driver is given.
I will be glad if you have any conclusions...

Functions of conftest.py

```<code>import time

import pytest as pytest
from selenium import webdriver

from src.pom import settings
from src.pom.pages.BasePage import BasePage
from src.pom.pages.LoginPage import LoginPage

# from pytest_lazyfixture import lazy_fixture

driver = None

def pytest_addoption(parser):
    # parser.addoption("--browser", action="store", default="chrome")
    parser.addoption("--browser", action="store", default=settings.browser)
    parser.addoption("--env", action="store", default=settings.env)

@pytest.fixture()
# @lazy_fixture
def getBrowser(request):
    _browser = request.config.getoption("--browser")
    return _browser

@pytest.fixture()
def getDriver(request, getBrowser):
    global driver
    print("browser from getBrowser method - " + getBrowser)
    if getBrowser == "chrome":
        driver = webdriver.Chrome("C:\\Tools\\chromedriver\\chromedriver.exe")

    driver.get(settings.url)
    driver.implicitly_wait(20)
    driver.maximize_window()
    request.cls.basePage = BasePage(driver)
    request.cls.loginPage = LoginPage(driver)
    request.cls.driver = driver
    # yield request.cls.driver
    yield driver
    time.sleep(2)
    driver.quit()
</code>```

Functions from BasePage(as example):

```<code>class BasePage:
    def __int__(self,driver):
        self.driver = driver
        self.wait = WebDriverWait(self.driver, 10)

    def do_click(self, by_locator):
        # self.wait.until(EC.visibility_of_element_located(by_locator)).click()
        self.wait.until(EC.presence_of_element_located(by_locator)).click()
</code>```

Functions from LoginPage(as example):

```<code>from selenium.webdriver.common.by import By

from src.pom.pages.BasePage import BasePage

class LoginPage(BasePage):

    def __int__(self, driver):
        super().__int__(driver)
        self.driver = driver

    EMAIL = (By.ID, "login-email")
    PASSWORD = (By.ID, "login-password")
    LOGIN_BUTTON = (By.CSS_SELECTOR, "div [type='submit']")
    CAMPUS_LOGO = (By.CSS_SELECTOR, ".logo")
</code>```

Eventually I get the error:

```<code>  request.cls.basePage = BasePage(driver)
</code>```

E       TypeError: BasePage() takes no arguments

I have tried to work with this structure of page object in python but I failed. I have expected to run tests that began to write.

Body:
I try to create the project with page object(python 3.9) and my conftest.py file doesn't receive any driver from its pages.
Any page has _init constructors,but in the conftest.py file we can see that no driver is given.
I will be glad if you have any conclusions...

Functions of conftest.py

import time

import pytest as pytest
from selenium import webdriver

from src.pom import settings
from src.pom.pages.BasePage import BasePage
from src.pom.pages.LoginPage import LoginPage

# from pytest_lazyfixture import lazy_fixture

driver = None

def pytest_addoption(parser):
    # parser.addoption("--browser", action="store", default="chrome")
    parser.addoption("--browser", action="store", default=settings.browser)
    parser.addoption("--env", action="store", default=settings.env)

@pytest.fixture()
# @lazy_fixture
def getBrowser(request):
    _browser = request.config.getoption("--browser")
    return _browser

@pytest.fixture()
def getDriver(request, getBrowser):
    global driver
    print("browser from getBrowser method - " + getBrowser)
    if getBrowser == "chrome":
        driver = webdriver.Chrome("C:\\Tools\\chromedriver\\chromedriver.exe")

    driver.get(settings.url)
    driver.implicitly_wait(20)
    driver.maximize_window()
    request.cls.basePage = BasePage(driver)
    request.cls.loginPage = LoginPage(driver)
    request.cls.driver = driver
    # yield request.cls.driver
    yield driver
    time.sleep(2)
    driver.quit()

Functions from BasePage(as example):

class BasePage:
    def __int__(self,driver):
        self.driver = driver
        self.wait = WebDriverWait(self.driver, 10)

    def do_click(self, by_locator):
        # self.wait.until(EC.visibility_of_element_located(by_locator)).click()
        self.wait.until(EC.presence_of_element_located(by_locator)).click()

Functions from LoginPage(as example):

from selenium.webdriver.common.by import By

from src.pom.pages.BasePage import BasePage

class LoginPage(BasePage):

    def __int__(self, driver):
        super().__int__(driver)
        self.driver = driver

    EMAIL = (By.ID, "login-email")
    PASSWORD = (By.ID, "login-password")
    LOGIN_BUTTON = (By.CSS_SELECTOR, "div [type='submit']")
    CAMPUS_LOGO = (By.CSS_SELECTOR, ".logo")

Eventually I get the error:

  request.cls.basePage = BasePage(driver)

E       TypeError: BasePage() takes no arguments

I have tried to work with this structure of page object in python but I failed. I have expected to run tests that began to write.


问:
SwiftUI sharing application data using pasteboard
I have a phone / iPad application. It would be useful to export text, images, or other data to other apps or other devices.

I can export the colour data as text using UIpasteboard.general.string. This works nicely. The Universal pasteboard lets me paste into other devices.

I can export an image using UIpasteboard.general.image. I have a PNG image in my bundle resources. I can the paste it into Preview or some other image viewer. I would like to be able to paste it as a file but I can't see how to do that at the other end.

I have also a PDF manual in the Bundle. It would be nice to export that too. Like the previous image, it would be nice to paste it as a file but I cannot see how this is done.

Before I get into the code, is UIpasteboard the right way to do this? Or is there some other approach I ought to be using rather than trying to fix this. What do other apps do?

```<code> Grid(horizontalSpacing: 3, verticalSpacing:3) {
        GridRow {
            Text("Text: ").gridColumnAlignment(.trailing).foregroundColor(.gray)
            Button {
                let pasteboard = UIPasteboard.general
                pasteboard.string = toString(sw: sd.mySwatch)
            } label: {
                Text("Current swatch").lineLimit(1).frame(width:buttonW)
            }.buttonStyle(.bordered)
        }
        GridRow {
            Text("Text: ").gridColumnAlignment(.trailing).foregroundColor(.gray)
            Button {
                var reply: String = ""
                for sw in sd.swatches {
                    reply = reply + toString(sw: sw)
                }
                UIPasteboard.general.string = reply
            } label: {
                Text("All swatches").lineLimit(1).frame(width:buttonW)
            }.buttonStyle(.bordered)
        }
        GridRow {
            Text("Image: ").gridColumnAlignment(.trailing).foregroundColor(.gray)
            Button {
                UIPasteboard.general.image = UIImage(contentsOfFile: Bundle.main.path(forResource: "Macbeth", ofType: "png")!)
            } label: {
                Text("Macbeth.png").lineLimit(1).frame(width:buttonW)
            }.buttonStyle(.bordered)
        }
        GridRow {
            Text("PDF: ").gridColumnAlignment(.trailing).foregroundColor(.gray)
            Button {
                UIPasteboard.general.url = Bundle.main.url(forResource: "ByEye", withExtension: "pdf")!
            } label: {
                Text("ByEye.pdf").lineLimit(1).frame(width:buttonW)
            }.buttonStyle(.bordered)
        }
    }
</code>```

That is my code. The first three options work. The last one does not because the URL is a private one for the application. I might be able to copy the file to a public directory so the URL worked but that seems like the wrong way to go about it.

Postscript:

This actually works well enough for now. I can copy stuff to the pasteboard, then paste it into an e-mail or other message to myself. This lets me get stuff out of the app without creating temporary files the I have to clean up.

I did not find a solution for the PDF or other files. I was hoping for something like this...

```<code>UIPasteboard.general.file = UIImage(contentsOfFile: Bundle.main.path(forResource: "manual", ofType: "pdf")!)
</code>```

...but nothing like that exists as far as I can tell.

Body:
I have a phone / iPad application. It would be useful to export text, images, or other data to other apps or other devices.

I can export the colour data as text using UIpasteboard.general.string. This works nicely. The Universal pasteboard lets me paste into other devices.

I can export an image using UIpasteboard.general.image. I have a PNG image in my bundle resources. I can the paste it into Preview or some other image viewer. I would like to be able to paste it as a file but I can't see how to do that at the other end.

I have also a PDF manual in the Bundle. It would be nice to export that too. Like the previous image, it would be nice to paste it as a file but I cannot see how this is done.

Before I get into the code, is UIpasteboard the right way to do this? Or is there some other approach I ought to be using rather than trying to fix this. What do other apps do?

 Grid(horizontalSpacing: 3, verticalSpacing:3) {
        GridRow {
            Text("Text: ").gridColumnAlignment(.trailing).foregroundColor(.gray)
            Button {
                let pasteboard = UIPasteboard.general
                pasteboard.string = toString(sw: sd.mySwatch)
            } label: {
                Text("Current swatch").lineLimit(1).frame(width:buttonW)
            }.buttonStyle(.bordered)
        }
        GridRow {
            Text("Text: ").gridColumnAlignment(.trailing).foregroundColor(.gray)
            Button {
                var reply: String = ""
                for sw in sd.swatches {
                    reply = reply + toString(sw: sw)
                }
                UIPasteboard.general.string = reply
            } label: {
                Text("All swatches").lineLimit(1).frame(width:buttonW)
            }.buttonStyle(.bordered)
        }
        GridRow {
            Text("Image: ").gridColumnAlignment(.trailing).foregroundColor(.gray)
            Button {
                UIPasteboard.general.image = UIImage(contentsOfFile: Bundle.main.path(forResource: "Macbeth", ofType: "png")!)
            } label: {
                Text("Macbeth.png").lineLimit(1).frame(width:buttonW)
            }.buttonStyle(.bordered)
        }
        GridRow {
            Text("PDF: ").gridColumnAlignment(.trailing).foregroundColor(.gray)
            Button {
                UIPasteboard.general.url = Bundle.main.url(forResource: "ByEye", withExtension: "pdf")!
            } label: {
                Text("ByEye.pdf").lineLimit(1).frame(width:buttonW)
            }.buttonStyle(.bordered)
        }
    }

That is my code. The first three options work. The last one does not because the URL is a private one for the application. I might be able to copy the file to a public directory so the URL worked but that seems like the wrong way to go about it.

Postscript:

This actually works well enough for now. I can copy stuff to the pasteboard, then paste it into an e-mail or other message to myself. This lets me get stuff out of the app without creating temporary files the I have to clean up.

I did not find a solution for the PDF or other files. I was hoping for something like this...

UIPasteboard.general.file = UIImage(contentsOfFile: Bundle.main.path(forResource: "manual", ofType: "pdf")!)

...but nothing like that exists as far as I can tell.


问:
Webpack: include css and svg to html
Sorry for this question, but I really cant't understand.
Svg and styles not loaded in projects. Svg in Network console loaded on this adress:  http://localhost:9000/%7B'./images/Browser.svg'%7D

I see extra character..

My webpack conf:

```<code>{
mode: 'development',
entry: __dirname + '/IE/index.js',
output: {
    filename: '[name].js',
    path: path.resolve(__dirname, './dist'),
},
target: ['web', 'es5'],
plugins: [
    new HtmlWebpackPlugin({
        template: path.resolve(__dirname, './IE/ieMock.html'),
    }),
],

module: {
    rules: [
        { test: /\.html$/i, loader: 'html-loader' },
        {
            test: /\.s?css$/i,
            use: ['style-loader', 'css-loader'],
        },

        { test: /\.svg$/, loader: 'svg-inline-loader' },
        {
            test: /\.js$/,
            exclude: /(node_modules|bower_components)/,
            use: {
                loader: 'babel-loader',
                options: {
                    presets: [
                        [
                            '@babel/preset-env',
                            {
                                // targets: {
                                //     ie: '11',
                                // },
                            },
                        ],
                    ],
                },
            },
        },
    ],
},
</code>```

};

ieMock.html:

```<code> <!doctype html>
   <html xmlns="http://www.w3.org/1999/html" lang="en">
   <head>
    <title>Предупреждение</title>
    <meta charset="utf-8">
    <link rel="stylesheet" href="IE/index.css">
    <link href="./src/assets/styles/normalize.css" rel="stylesheet">
    <link href="./src/assets/styles/font-awesome.css" rel="stylesheet">
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <meta name="viewport" content="width=device-width,initial-scale=1.0">
</head>
<body>
<main>
<div className="ie-support-container">
    <div className="ie-support-container__el">

        <p>
            Переходите на ЯндексБраузер.

        </p>
    </div>

    <div className="ie-support-container__el">
    <div className="browser_label">
        <img src={'./images/Browser.svg'} />
        <span>Браузер</span>
    </div>
    <div className="browser_label">
        <img src={'./images/YandexBrowser.svg'} />
        <span>Яндекс Браузер</span>
    </div>
</div>
</div>

</main>
</body>
</html>
</code>```

index.js

```<code>import './ieMock.html';
import './index.css';
</code>```

What am I doing wrong? Why svg loaded with extra character?

Title: Webpack: include css and svg to html

Body:
Sorry for this question, but I really cant't understand.
Svg and styles not loaded in projects. Svg in Network console loaded on this adress:  http://localhost:9000/%7B'./images/Browser.svg'%7D

I see extra character..

My webpack conf:

{
mode: 'development',
entry: __dirname + '/IE/index.js',
output: {
    filename: '[name].js',
    path: path.resolve(__dirname, './dist'),
},
target: ['web', 'es5'],
plugins: [
    new HtmlWebpackPlugin({
        template: path.resolve(__dirname, './IE/ieMock.html'),
    }),
],

module: {
    rules: [
        { test: /\.html$/i, loader: 'html-loader' },
        {
            test: /\.s?css$/i,
            use: ['style-loader', 'css-loader'],
        },

        { test: /\.svg$/, loader: 'svg-inline-loader' },
        {
            test: /\.js$/,
            exclude: /(node_modules|bower_components)/,
            use: {
                loader: 'babel-loader',
                options: {
                    presets: [
                        [
                            '@babel/preset-env',
                            {
                                // targets: {
                                //     ie: '11',
                                // },
                            },
                        ],
                    ],
                },
            },
        },
    ],
},

};

ieMock.html:

 <!doctype html>

    <title>Предупреждение</title>
    <meta charset="utf-8">
    <link rel="stylesheet" href="IE/index.css">
    <link href="./src/assets/styles/normalize.css" rel="stylesheet">
    <link href="./src/assets/styles/font-awesome.css" rel="stylesheet">
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <meta name="viewport" content="width=device-width,initial-scale=1.0">

            Переходите на ЯндексБраузер.

        Браузер

        Яндекс Браузер

index.js

import './ieMock.html';
import './index.css';

What am I doing wrong? Why svg loaded with extra character?


问:
How to retrieve value from array and present in the field in admin orded data?
I have a question. I have plugin Furgonetka installed on woocommerce. Package numbers are collected from Furgonetka service in meta_key tracking_info like:

```<code>Array
(
    [520000016902796077744528] => Array
        (
            [courierService] => inpostkurier
        )

)
</code>```

In data base it is presented like: a:1:{s:24:"520000016902796077744528";a:1:{s:14:"courierService";s:12:"inpostkurier";}}
I have added the function in functions.php to show field tracking_info in admin order data:

```<code>add_action( 'woocommerce_admin_order_data_after_order_details', 'add_admin_order_field' );
function add_admin_order_field( $order ){
 woocommerce_wp_text_input(
 array(
 'id'            => 'tracking_info',
 'label'         => __( 'Tracking number', 'your-text-domain' ),
 'value'         => get_post_meta( $order->get_id() , 'tracking_info', true ),
 'wrapper_class' => 'form-field-wide',
 )
 );
}
</code>```

But field presents only value "Array".
Do you know how to retrieve package number (which is for example 520000016902796077744528) and present in the field tracking_info?

I want to show package number in the field tracking_info.

Body:
I have a question. I have plugin Furgonetka installed on woocommerce. Package numbers are collected from Furgonetka service in meta_key tracking_info like:

Array
(
    [520000016902796077744528] => Array
        (
            [courierService] => inpostkurier
        )

)

In data base it is presented like: a:1:{s:24:"520000016902796077744528";a:1:{s:14:"courierService";s:12:"inpostkurier";}}
I have added the function in functions.php to show field tracking_info in admin order data:

add_action( 'woocommerce_admin_order_data_after_order_details', 'add_admin_order_field' );
function add_admin_order_field( $order ){
 woocommerce_wp_text_input(
 array(
 'id'            => 'tracking_info',
 'label'         => __( 'Tracking number', 'your-text-domain' ),
 'value'         => get_post_meta( $order->get_id() , 'tracking_info', true ),
 'wrapper_class' => 'form-field-wide',
 )
 );
}

But field presents only value "Array".
Do you know how to retrieve package number (which is for example 520000016902796077744528) and present in the field tracking_info?

I want to show package number in the field tracking_info.


问:
Using Gsap Scrolltrigger and Tweenmax conflict
I have Problems using greensocks gsap Core 3 with tweenmax. When I include the gsap core, tweenmax is not working anymore.

```<code><script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.11.3/gsap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.11.3/ScrollTrigger.min.js"></script>

<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/gsap/2.1.3/TweenMax.min.js"></script>
<script>
    $(document).ready(function (){

       var tl = new TimelineLite({paused:true});

            tl.set(navigation, {"z-index":12})
               .to(panel1, 0, {width: panel1_width})
               .to(html, 0, {overflow: 'hidden'}, "-=0.5");

       open_btn.on('click', function (e){
           e.preventDefault();
           tl.play();
       });

       close_btn.on('click', function (e){
           e.preventDefault();
           tl.reverse();
       });

        var images = gsap.utils.toArray(".ce_bgimage-image");
        images.forEach((image, i) => {
          gsap.fromTo(
            image,
            { scale: 0.9 },
            {
              scale: 1,
              ease: "none",
              force3D: true,
              scrollTrigger: {
                //pin:jQuery(image).children(".ce_bgimage-outer"),
                trigger: jQuery(image).parent(),
                start: "top bottom",
                end: "bottom top",
                //pinType: isTouch ? "fixed" : "transform",
                scrub: 0,
                markers: true
              }
            }
          );
        });
    });
</script>
</code>```

When I remove the gsap core - tweenlite working fine and scrolltrigger is not working anymore. I think there is a conflict between the libaries.

thank you for your help

Body:
I have Problems using greensocks gsap Core 3 with tweenmax. When I include the gsap core, tweenmax is not working anymore.

When I remove the gsap core - tweenlite working fine and scrolltrigger is not working anymore. I think there is a conflict between the libaries.

thank you for your help


问:
getting error while using variable in jenkins pipeline for escape character
In my Jenkins declarative pipeline, I am using a global variable below

```<code>def ingress_path = "/${helmDeploymentName}(/|\$)(.*)"
</code>```

It is giving the below error :

```<code>syntax error near unexpected token `('
</code>```

It seems some characters need to be escaped while using this variable. I have only escaped "$"

Which other characters need to be escaped here?

Body:
In my Jenkins declarative pipeline, I am using a global variable below

def ingress_path = "/${helmDeploymentName}(/|\$)(.*)"

It is giving the below error :

syntax error near unexpected token `('

It seems some characters need to be escaped while using this variable. I have only escaped "$"

Which other characters need to be escaped here?


问:
Draw Pathpatch with gradient fill in Python
I'd like to draw path patches in python with a gradient fill to better visualize the start and end of a path connection. I know that I can use FanyArrowPatch to have an arrow to indicate the direction but I'd prefer to use gradient colors (e.g. Blue to red).
Is there a way to define the color of a patch using something simple like just idnicating color = "RdBu"?

For wedge patches I used a not so convient way (for loop) by plotting small segements of it seperatly with adapting the colors. However, in my end plot I will have all lot of connections using patches.PathPatch and I need a more efficient way to define a gradient color. Also, I would not know how the apply the for-loop trick on Paths patches...

Do you have any suggestions how to plot pathes with gradient colors? Are there any other packages I could try?

```<code>import numpy as np
import matplotlib.patches as mpatches
from matplotlib.collections import PatchCollection
import matplotlib.pyplot as plt
import seaborn as sns

#---------------------------------------------
# Drawing example
#---------------------------------------------
fig, ax = plt.subplots(figsize=(8,8))
plt.title('matplotlib mpatch / path does not accept gradient colors directly')
ring = mpatches.Wedge((0,0), 0.7, 190, 350, color='r',width=0.2, label = 'wedge with only one color, no direction')
ax.add_patch(ring)

# drawing desired output with easy fix using for-loop, whcih is not working for mpatches.FancyArrowPatch
total_deg = 170
n_steps = 100
d_deg = total_deg / n_steps
colors = sns.color_palette("vlag", n_steps)
for i in range(n_steps-1):
    ring = mpatches.Wedge((0,0), 0.7, i*d_deg, (i+1)*d_deg, color=colors[i],width=0.2)
    ax.add_patch(ring)
i = i+1
ring = mpatches.Wedge((0,0), 0.7, i*d_deg, (i+1)*d_deg, color=colors[i],width=0.2, label = 'wedge with gradient color using for-loop')
ax.add_patch(ring)

# drawing desired output with easy fix using for-loop, whcih is not working for mpatches.FancyArrowPatch

verts = [[0.8,0.2],[0,1.4],[-0.9, 0.2]]
codes = [Path.MOVETO, Path.CURVE3, Path.CURVE3]
lw = 5
path = Path(verts, codes)
patch = mpatches.FancyArrowPatch(path=path,arrowstyle="-|>,head_length=10,head_width=10", lw=lw, color='b', zorder=1, label = 'path that should have gradient color')
ax.add_patch(patch)

plt.xlim([-1.5,1.5])
plt.ylim([-1.5,1.5])
plt.legend()
plt.axis('off')
plt.show()
</code>```

Body:
I'd like to draw path patches in python with a gradient fill to better visualize the start and end of a path connection. I know that I can use FanyArrowPatch to have an arrow to indicate the direction but I'd prefer to use gradient colors (e.g. Blue to red).
Is there a way to define the color of a patch using something simple like just idnicating color = "RdBu"?

For wedge patches I used a not so convient way (for loop) by plotting small segements of it seperatly with adapting the colors. However, in my end plot I will have all lot of connections using patches.PathPatch and I need a more efficient way to define a gradient color. Also, I would not know how the apply the for-loop trick on Paths patches...

Do you have any suggestions how to plot pathes with gradient colors? Are there any other packages I could try?

import numpy as np
import matplotlib.patches as mpatches
from matplotlib.collections import PatchCollection
import matplotlib.pyplot as plt
import seaborn as sns

#---------------------------------------------
# Drawing example
#---------------------------------------------
fig, ax = plt.subplots(figsize=(8,8))
plt.title('matplotlib mpatch / path does not accept gradient colors directly')
ring = mpatches.Wedge((0,0), 0.7, 190, 350, color='r',width=0.2, label = 'wedge with only one color, no direction')
ax.add_patch(ring)

# drawing desired output with easy fix using for-loop, whcih is not working for mpatches.FancyArrowPatch
total_deg = 170
n_steps = 100
d_deg = total_deg / n_steps
colors = sns.color_palette("vlag", n_steps)
for i in range(n_steps-1):
    ring = mpatches.Wedge((0,0), 0.7, i*d_deg, (i+1)*d_deg, color=colors[i],width=0.2)
    ax.add_patch(ring)
i = i+1
ring = mpatches.Wedge((0,0), 0.7, i*d_deg, (i+1)*d_deg, color=colors[i],width=0.2, label = 'wedge with gradient color using for-loop')
ax.add_patch(ring)

# drawing desired output with easy fix using for-loop, whcih is not working for mpatches.FancyArrowPatch

verts = [[0.8,0.2],[0,1.4],[-0.9, 0.2]]
codes = [Path.MOVETO, Path.CURVE3, Path.CURVE3]
lw = 5
path = Path(verts, codes)
patch = mpatches.FancyArrowPatch(path=path,arrowstyle="-|>,head_length=10,head_width=10", lw=lw, color='b', zorder=1, label = 'path that should have gradient color')
ax.add_patch(patch)

plt.xlim([-1.5,1.5])
plt.ylim([-1.5,1.5])
plt.legend()
plt.axis('off')
plt.show()


问:
Close a card typescript mui material card
I'm new to typescript and I have a problem with my app.

I have a CardActions and a button in it. When we click on the button, a function is called.
I would like the card to disappear when the action is finished...
Is there a way to do that ?

Thank you for your help !

I tried to add a boolean : if the function is not done, you can show the CardActions else don't show it. But it didn't work ...


问:
Unable to install truffle unboxmetacoin in VScode editor
```<code>Starting unbox...
=================

✓ Preparing to download box
✖ Downloading
Unbox failed!
Error: connect ECONNREFUSED 127.0.0.1:80
    at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1247:16)
Truffle v5.6.9 (core: 5.6.9)
Node v16.17.0
</code>```

truffle unbox metacoin should be installed , and it create respective folders

Body:
Starting unbox...
=================

✓ Preparing to download box
✖ Downloading
Unbox failed!
Error: connect ECONNREFUSED 127.0.0.1:80
    at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1247:16)
Truffle v5.6.9 (core: 5.6.9)
Node v16.17.0

truffle unbox metacoin should be installed , and it create respective folders


问:
How to access reference in reusable workflow
Context

A reusable workflow in public repos may be called by appending a reference which can be a SHA, a release tag, or a branch name, as for example:
{owner}/{repo}/.github/workflows/{filename}@{ref}

Githubs documentation states:

When a reusable workflow is triggered by a caller workflow, the github context is always associated with the caller workflow.

The problem

Since the github context is always associated with the caller workflow, the reusable workflow cannot access the reference, for example the tag v1.0.0. However, knowing the reference is important when the reusable workflow needs to checkout the repository in order to make use of composite actions.

Example

Assume that the caller workflow is being executed from within the main branch and calls the ref v1.0.0. of a reusable workflow:

```<code>name: Caller workflow
on:
  workflow_dispatch:

jobs:
  caller:
    uses: owner/public-repo/.github/workflows/reusable-workflow.yml@v1.0.0

</code>```

Here is the reusable workflow that uses a composite action:

```<code>name: reusable workflows
on:
  workflow_call:

jobs:
  first-job:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3.1.0
        with:
          repository: owner/public-repo
          ref: ${{ github.ref_name }}

      - name: composite action
        uses: ./actions/my-composite-action
</code>```

In the above code snippet, ${{ github.ref_name }} is main instead of v1.0.0 because github context is always associated with the caller workflow. Therefore, the composite actions code is based on main and not on v1.0.0. However, the caller wanted v1.0.0.
Hence my question: how is the reusable workflow able to access the reference given by the caller?

Body:
Context

A reusable workflow in public repos may be called by appending a reference which can be a SHA, a release tag, or a branch name, as for example:
{owner}/{repo}/.github/workflows/{filename}@{ref}

Githubs documentation states:

When a reusable workflow is triggered by a caller workflow, the github context is always associated with the caller workflow.

The problem

Since the github context is always associated with the caller workflow, the reusable workflow cannot access the reference, for example the tag v1.0.0. However, knowing the reference is important when the reusable workflow needs to checkout the repository in order to make use of composite actions.

Example

Assume that the caller workflow is being executed from within the main branch and calls the ref v1.0.0. of a reusable workflow:

name: Caller workflow
on:
  workflow_dispatch:

jobs:
  caller:
    uses: owner/public-repo/.github/workflows/reusable-workflow.yml@v1.0.0

Here is the reusable workflow that uses a composite action:

name: reusable workflows
on:
  workflow_call:

jobs:
  first-job:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3.1.0
        with:
          repository: owner/public-repo
          ref: ${{ github.ref_name }}

      - name: composite action
        uses: ./actions/my-composite-action

In the above code snippet, ${{ github.ref_name }} is main instead of v1.0.0 because github context is always associated with the caller workflow. Therefore, the composite actions code is based on main and not on v1.0.0. However, the caller wanted v1.0.0.
Hence my question: how is the reusable workflow able to access the reference given by the caller?


问:
403 :Permission denied while hitting google developer reporting API
i am trying to hit https://playdeveloperreporting.googleapis.com/v1alpha1/apps/com.example/anrRateMetricSet.

It returns 403: permission denied

```<code>Here i am trying to capture the health metrics for my android app from Google console.

Reference:https://developers.google.com/play/developer/reporting/reference/rest/v1alpha1/vitals.anrrate/get?hl=en_GB

So i have Service account created on google console under "I AM and Admin"

I am trying to hit "https://playdeveloperreporting.googleapis.com/v1alpha1/apps/com.example/anrRateMetricSet"
By using access token created from key.JSON downloaded from linked Service account to the project.

But i am getting

{
    "error": {
        "code": 403,
        "message": "The caller does not have permission",
        "status": "PERMISSION_DENIED"
    }
}

Could n't understand what might be the issue. Since the Service account is linked to project.
 Your help is highly appreciated . Thank you
</code>```

Body:
i am trying to hit https://playdeveloperreporting.googleapis.com/v1alpha1/apps/com.example/anrRateMetricSet.

It returns 403: permission denied

Here i am trying to capture the health metrics for my android app from Google console.

Reference:https://developers.google.com/play/developer/reporting/reference/rest/v1alpha1/vitals.anrrate/get?hl=en_GB

So i have Service account created on google console under "I AM and Admin"

I am trying to hit "https://playdeveloperreporting.googleapis.com/v1alpha1/apps/com.example/anrRateMetricSet"
By using access token created from key.JSON downloaded from linked Service account to the project.

But i am getting

{
    "error": {
        "code": 403,
        "message": "The caller does not have permission",
        "status": "PERMISSION_DENIED"
    }
}

Could n't understand what might be the issue. Since the Service account is linked to project.
 Your help is highly appreciated . Thank you


问:
CSRF token for interservice communication
I have disabled CSRF token for all the APIs (url pattern - /api/..) that is called only from other microservice.

```<code>@Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http.csrf(csrf -> {
            csrf.ignoringAntMatchers("/api/**");
            csrf.csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse());
        }).authorizeHttpRequests(authz -> {
            try {
                authz.antMatchers("/authenticate").permitAll()
                        .anyRequest().authenticated().and().exceptionHandling()
                        .authenticationEntryPoint(jwtAuthenticationEntryPoint).and().sessionManagement()
                        .sessionCreationPolicy(SessionCreationPolicy.STATELESS);
            } catch (Exception e) {
                LOGGER.error("Exception in filterChain..");
            }
        }).httpBasic();
        http.addFilterBefore(jwtRequestFilter, UsernamePasswordAuthenticationFilter.class);
        return http.build();
    }
</code>```

All works fine. But it shows sonarqube security bug for using csrf.ignoringAntMatchers("/api/**")
How could i safely turn off csrf for interservice communication.

Using spring boot version 2.6.6

Body:
I have disabled CSRF token for all the APIs (url pattern - /api/..) that is called only from other microservice.

@Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http.csrf(csrf -> {
            csrf.ignoringAntMatchers("/api/**");
            csrf.csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse());
        }).authorizeHttpRequests(authz -> {
            try {
                authz.antMatchers("/authenticate").permitAll()
                        .anyRequest().authenticated().and().exceptionHandling()
                        .authenticationEntryPoint(jwtAuthenticationEntryPoint).and().sessionManagement()
                        .sessionCreationPolicy(SessionCreationPolicy.STATELESS);
            } catch (Exception e) {
                LOGGER.error("Exception in filterChain..");
            }
        }).httpBasic();
        http.addFilterBefore(jwtRequestFilter, UsernamePasswordAuthenticationFilter.class);
        return http.build();
    }

All works fine. But it shows sonarqube security bug for using csrf.ignoringAntMatchers("/api/**")
How could i safely turn off csrf for interservice communication.

Using spring boot version 2.6.6


问:
Is there a way to get a Promise to return a result before reaching the view?
I am developing a Node app on my home server to be a simple project tracker. I am pretty OK with javascript but have never written anything that encountered issues with asynchronous requests, until now. The concept of Promise is new to me and, although I have found several examples that all work in some way, I still can't get the expected output. Here is the scenario:

I login as admin

I click a List Projects button

Node routes this to the listProjects function

If admin then get a list of clients from database (knex)

Here's where things get unexpected.
I want to see

```<code>A
{client_id: 1, client_name: 'Robert'},{...}
B
{client_id: 1, client_name: 'Robert'},{...}
C
{client_id: 1, client_name: 'Robert'},{...}
</code>```

Instead I get

```<code>B
{}
C
Promise {\<pending\>}
A
{client_id: 1, client_name: 'Robert'},{...}
</code>```

The code below includes the example answer from this question
When using db.then I get

```<code>B
{}
A
{client_id: 1, client_name: 'Robert'},{...}
C
{client_id: 1, client_name: 'Robert'},{...}
</code>```

which was my original approach and much better than the example I found using async/await but it still means that the code might reach the render before the Promise of for clients has been fulfilled
I want the clientList to be avilable before reaching the res.render in every case. What am I doing wrong?

```<code>async function wrapper() {
    async function getClients() {
        return db(client_table)
    }
    const clients = await getClients()
    console.log('A')
    console.table(clients)
    return clients
}
var listProjects = function(req, res) {
    var clients
    let projects = {}
    let whereClause = {}
    if (loggedIn) {
        if (isAdmin) {
            // Get a list of clients
            /*db(client_table).then((rows) => {
                    clients = rows
                                console.log('A')
                                console.table(clients)
                })*/
            clients = wrapper()
            console.log('B')
            console.table(clients)
        } else {
            // add where clause to filter get only this user's projects
            whereClause['c.user_id'] = req.session.user_id
        }
        db(project_table).innerJoin(project2client.target, project2client.condition).innerJoin(user2client.target, user2client.condition).where(whereClause).then((rows) => {
            console.log('C')
            console.log(clients)
            res.render('project', {
                title: 'List of projects',
                clientList: clients,
                recordset: rows
            })
        })
    } else {
        res.render('project', {
            title: 'List of projects',
            messages: {
                warning: 'Login to see your projects'
            }
        })
    }
}
</code>```

Initially I had my code nested in db.then calls but that made too many nested functions (maybe right now that isn't a problem but as I add more database retrievals then could get messy)

Body:
I am developing a Node app on my home server to be a simple project tracker. I am pretty OK with javascript but have never written anything that encountered issues with asynchronous requests, until now. The concept of Promise is new to me and, although I have found several examples that all work in some way, I still can't get the expected output. Here is the scenario:

I login as admin

I click a List Projects button

Node routes this to the listProjects function

If admin then get a list of clients from database (knex)

Here's where things get unexpected.
I want to see

A
{client_id: 1, client_name: 'Robert'},{...}
B
{client_id: 1, client_name: 'Robert'},{...}
C
{client_id: 1, client_name: 'Robert'},{...}

Instead I get

B
{}
C
Promise {\<pending\>}
A
{client_id: 1, client_name: 'Robert'},{...}

The code below includes the example answer from this question
When using db.then I get

B
{}
A
{client_id: 1, client_name: 'Robert'},{...}
C
{client_id: 1, client_name: 'Robert'},{...}

which was my original approach and much better than the example I found using async/await but it still means that the code might reach the render before the Promise of for clients has been fulfilled
I want the clientList to be avilable before reaching the res.render in every case. What am I doing wrong?

async function wrapper() {
    async function getClients() {
        return db(client_table)
    }
    const clients = await getClients()
    console.log('A')
    console.table(clients)
    return clients
}
var listProjects = function(req, res) {
    var clients
    let projects = {}
    let whereClause = {}
    if (loggedIn) {
        if (isAdmin) {
            // Get a list of clients
            /*db(client_table).then((rows) => {
                    clients = rows
                                console.log('A')
                                console.table(clients)
                })*/
            clients = wrapper()
            console.log('B')
            console.table(clients)
        } else {
            // add where clause to filter get only this user's projects
            whereClause['c.user_id'] = req.session.user_id
        }
        db(project_table).innerJoin(project2client.target, project2client.condition).innerJoin(user2client.target, user2client.condition).where(whereClause).then((rows) => {
            console.log('C')
            console.log(clients)
            res.render('project', {
                title: 'List of projects',
                clientList: clients,
                recordset: rows
            })
        })
    } else {
        res.render('project', {
            title: 'List of projects',
            messages: {
                warning: 'Login to see your projects'
            }
        })
    }
}

Initially I had my code nested in db.then calls but that made too many nested functions (maybe right now that isn't a problem but as I add more database retrievals then could get messy)


问:
Pandas replace with regex
I'm trying to remove a ¹ symbol from a string using pandas replace with regex. How I do that?

From:
Some string¹

To:Some string

Something like that?
df.replace({"column":{'*¹':''}},  regex=True)

Title: Pandas replace with regex


问:
SOAP to Rest Conversion
I have a rest api which need to be hit through soap request.I have created wsdl and endpoint for soap web service but when i am hitting the rest web service using apache camel routing it giving error of Request is not authorized for given resource access

rest api is access token based so i am passing the access token in exchange headers while converting soap request to rest

Title: SOAP to Rest Conversion


问:
Unexpected close of tokio mpsc channel
I am trying to use tokio::mpsc::channel to send data from a synchronous function to tokio thread to handle it asynchronously.

Since tokio::mpsc::channel is an async function, I spawn a runtime from the sync function to create rx and tx and return tx after moving rx to the newly spawned task in it.

However, it does not work as I expected and I have conducted some debugging and found out the followings.

The channel is not closed right after the creation.

The channel reported itself to be closed right after the rx moved into a separate task.

Right at the moment the channel reported itself to be closed, the spawned thread, which holds the moved rx seems does not even start. Hence couldn't be dropped, I guess.

https://docs.rs/tokio/latest/tokio/sync/mpsc/struct.Sender.html.
The documentation says that the tx report itself is closed only when rx handle gets dropped or explicitly calls the close function. It seems neither in this case.

```<code> fn websocket(base: &Url, id: &str) -> Result<(Sender<String>, Stream<String>), BoxErr> {

        ...

        let ws_reciver_sink = Sink::new();
        let ws_receiver_stream = ws_reciver_sink.stream();

        let (ws_sender_tx, mut ws_sender_rx) = mpsc::channel(100);
        debug!("ws_sender_channel is closed 1: {}", ws_sender_tx.is_closed());

        runtime::Builder::new_current_thread()
            .enable_all()
            .build()?
            .block_on(async move {
                let (ws_stream, _res) = connect_async(url).await?;

                let (mut ws_sender_inner, mut ws_receiver_inner) = ws_stream.split();

                debug!("spawning ws_recv_task");
                let ws_recv_task = tokio::spawn(async move {
                    while let Some(Ok(Message::Text(msg))) = ws_receiver_inner.next().await {
                        ws_reciver_sink.send(msg);
                    }
                });
                debug!("spawning ws_send_task");

                let ws_send_task = tokio::spawn(async move {
                    debug!("moving ws_sender_rx handle");
                    while let Some(msg) = ws_sender_rx.recv().await {
                        if ws_sender_inner.send(Message::Text(msg)).await.is_err() {
                            ws_recv_task.abort();
                        }
                        debug!("dropping ws_sender_rx handle");
                    }
                });
                Ok::<(), BoxErr>(())
            })?;
            debug!("ws_sender_channel is closed 2: {}", ws_sender_tx.is_closed());
        Ok((ws_sender_tx, ws_receiver_stream))
    }
</code>```

Output

```<code>[2022-12-13T11:58:45Z DEBUG reqwest::connect] starting new connection: http://127.0.0.1:8000/
[2022-12-13T11:58:45Z DEBUG iot] connecting to websocket ws://127.0.0.1:8000/node/test-a
[2022-12-13T11:58:45Z DEBUG iot] ws_sender_channel is closed 1: false
[2022-12-13T11:58:45Z DEBUG tungstenite::handshake::client] Client handshake done.
[2022-12-13T11:58:45Z DEBUG iot] spawning ws_recv_task
[2022-12-13T11:58:45Z DEBUG iot] spawning ws_send_task
[2022-12-13T11:58:45Z DEBUG iot] ws_sender_channel is closed 2: true
[2022-12-13T11:58:45Z DEBUG reqwest::connect] starting new connection: http://127.0.0.1:8000/
[2022-12-13T11:58:45Z DEBUG iot] ws_sender_channel is closed: true
thread 'tests::test_connect' panicked at 'called `Result::unwrap()` on an `Err` value: SendError("Some nights")', iot/src/lib.rs:199:50
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
</code>```

What am I missing? Please enlighten me.

Title: Unexpected close of tokio mpsc channel

Body:
I am trying to use tokio::mpsc::channel to send data from a synchronous function to tokio thread to handle it asynchronously.

Since tokio::mpsc::channel is an async function, I spawn a runtime from the sync function to create rx and tx and return tx after moving rx to the newly spawned task in it.

However, it does not work as I expected and I have conducted some debugging and found out the followings.

The channel is not closed right after the creation.

The channel reported itself to be closed right after the rx moved into a separate task.

Right at the moment the channel reported itself to be closed, the spawned thread, which holds the moved rx seems does not even start. Hence couldn't be dropped, I guess.

https://docs.rs/tokio/latest/tokio/sync/mpsc/struct.Sender.html.
The documentation says that the tx report itself is closed only when rx handle gets dropped or explicitly calls the close function. It seems neither in this case.

 fn websocket(base: &Url, id: &str) -> Result<(Sender<String>, Stream<String>), BoxErr> {

        ...

        let ws_reciver_sink = Sink::new();
        let ws_receiver_stream = ws_reciver_sink.stream();

        let (ws_sender_tx, mut ws_sender_rx) = mpsc::channel(100);
        debug!("ws_sender_channel is closed 1: {}", ws_sender_tx.is_closed());

        runtime::Builder::new_current_thread()
            .enable_all()
            .build()?
            .block_on(async move {
                let (ws_stream, _res) = connect_async(url).await?;

                let (mut ws_sender_inner, mut ws_receiver_inner) = ws_stream.split();

                debug!("spawning ws_recv_task");
                let ws_recv_task = tokio::spawn(async move {
                    while let Some(Ok(Message::Text(msg))) = ws_receiver_inner.next().await {
                        ws_reciver_sink.send(msg);
                    }
                });
                debug!("spawning ws_send_task");

                let ws_send_task = tokio::spawn(async move {
                    debug!("moving ws_sender_rx handle");
                    while let Some(msg) = ws_sender_rx.recv().await {
                        if ws_sender_inner.send(Message::Text(msg)).await.is_err() {
                            ws_recv_task.abort();
                        }
                        debug!("dropping ws_sender_rx handle");
                    }
                });
                Ok::<(), BoxErr>(())
            })?;
            debug!("ws_sender_channel is closed 2: {}", ws_sender_tx.is_closed());
        Ok((ws_sender_tx, ws_receiver_stream))
    }

Output

[2022-12-13T11:58:45Z DEBUG reqwest::connect] starting new connection: http://127.0.0.1:8000/
[2022-12-13T11:58:45Z DEBUG iot] connecting to websocket ws://127.0.0.1:8000/node/test-a
[2022-12-13T11:58:45Z DEBUG iot] ws_sender_channel is closed 1: false
[2022-12-13T11:58:45Z DEBUG tungstenite::handshake::client] Client handshake done.
[2022-12-13T11:58:45Z DEBUG iot] spawning ws_recv_task
[2022-12-13T11:58:45Z DEBUG iot] spawning ws_send_task
[2022-12-13T11:58:45Z DEBUG iot] ws_sender_channel is closed 2: true
[2022-12-13T11:58:45Z DEBUG reqwest::connect] starting new connection: http://127.0.0.1:8000/
[2022-12-13T11:58:45Z DEBUG iot] ws_sender_channel is closed: true
thread 'tests::test_connect' panicked at 'called `Result::unwrap()` on an `Err` value: SendError("Some nights")', iot/src/lib.rs:199:50
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace

What am I missing? Please enlighten me.


问:
Scale service with multiple ports and pass these ports to another service
I'm trying to run a system with a controller and multiple workers. While doing a udp-Healthcheck the controller acts as a UDP client and the worker act as a server. The ports where the controller/client should send the udp request to, is passed through args, using Dockers ENTRYPOINT.

The worker also gets his port that he listens to through args, using ENTRYPOINT as well.

I now want to scale the number of workers dynamically using

```<code>Docker-compose up --scale worker=[numberOfWorkers]
</code>```

but I couldn't find anything on how to pass the ports that are now dynamically created from a range of ports. Here is my Docker-compose.yml:

```<code>version: '3'

services:
  controller:
    build: controller
    container_name: controller1
    volumes:
      - network-log-volume:/var/controller_logs
    entrypoint: [/controller, worker:80]

  worker:
    build: worker
    ports:
      - "1001-1005:80"

    entrypoint: [/worker, "80", ""]

</code>```

The previous "hardcoded" version (which was perfectly working) looked like this:

```<code>version: '3'

services:
  controller:
    build: controller
    container_name: controller1
    volumes:
      - network-log-volume:/var/controller_logs
    entrypoint: [/controller, worker1:1231, worker2:1232, worker3:1233, worker4:1234, worker5:1235, worker6:1236]

  worker1:
    build: worker
    container_name: worker1
    expose:
      - "1231"
    ports:
      - "1231:1231"

    entrypoint: [/worker, "1231", ""]

  worker2:
    build: worker
    container_name: worker2
    expose:
      - "1232"
    ports:
      - "1232:1232"

    entrypoint: [/worker, "1232", ""]

  worker3:
    build: worker
    container_name: worker3
    expose:
      - "1233"
    ports:
      - "1233:1233"

    entrypoint: [/worker, "1233", ""]

  worker4:
    build: worker
    container_name: worker4
    expose:
      - "1234"
    ports:
      - "1234:1234"

    entrypoint: [/worker, "1234", ""]

  worker5:
    build: worker
    container_name: worker5
    expose:
      - "1235"
    ports:
      - "1235:1235"

    entrypoint: [/worker, "1235", ""]
</code>```

So I basically want to make the above Docker-compose.yml be scalable dynamically rather that doing it like that. Thanks!

Edit: Due to the way my lecture is structured I can not change a lot about how the controller and the worker work in general. It is supposed to work with only the docker-compose.yml

I read a bit about using swarms, but I also read that they are deprecated and not to be used anymore.

Body:
I'm trying to run a system with a controller and multiple workers. While doing a udp-Healthcheck the controller acts as a UDP client and the worker act as a server. The ports where the controller/client should send the udp request to, is passed through args, using Dockers ENTRYPOINT.

The worker also gets his port that he listens to through args, using ENTRYPOINT as well.

I now want to scale the number of workers dynamically using

Docker-compose up --scale worker=[numberOfWorkers]

but I couldn't find anything on how to pass the ports that are now dynamically created from a range of ports. Here is my Docker-compose.yml:

version: '3'

services:
  controller:
    build: controller
    container_name: controller1
    volumes:
      - network-log-volume:/var/controller_logs
    entrypoint: [/controller, worker:80]

  worker:
    build: worker
    ports:
      - "1001-1005:80"

    entrypoint: [/worker, "80", ""]

The previous "hardcoded" version (which was perfectly working) looked like this:

version: '3'

services:
  controller:
    build: controller
    container_name: controller1
    volumes:
      - network-log-volume:/var/controller_logs
    entrypoint: [/controller, worker1:1231, worker2:1232, worker3:1233, worker4:1234, worker5:1235, worker6:1236]

  worker1:
    build: worker
    container_name: worker1
    expose:
      - "1231"
    ports:
      - "1231:1231"

    entrypoint: [/worker, "1231", ""]

  worker2:
    build: worker
    container_name: worker2
    expose:
      - "1232"
    ports:
      - "1232:1232"

    entrypoint: [/worker, "1232", ""]

  worker3:
    build: worker
    container_name: worker3
    expose:
      - "1233"
    ports:
      - "1233:1233"

    entrypoint: [/worker, "1233", ""]

  worker4:
    build: worker
    container_name: worker4
    expose:
      - "1234"
    ports:
      - "1234:1234"

    entrypoint: [/worker, "1234", ""]

  worker5:
    build: worker
    container_name: worker5
    expose:
      - "1235"
    ports:
      - "1235:1235"

    entrypoint: [/worker, "1235", ""]

So I basically want to make the above Docker-compose.yml be scalable dynamically rather that doing it like that. Thanks!

Edit: Due to the way my lecture is structured I can not change a lot about how the controller and the worker work in general. It is supposed to work with only the docker-compose.yml

I read a bit about using swarms, but I also read that they are deprecated and not to be used anymore.


问:
Python error: Index is out of bounds for axis & too large x-axis in the graph
I have a data set containing a few stocks on a time frame. I plotted returns = df['high_value'].pct_change()[1:] which is a percent change of high_value being the highest value recorded value that date under specific stock name. I detected some outliers in rows 3104 & 14482. However, my method doesn't work as

```<code>index 3104 is out of bounds for axis 0 with size 888
</code>```

error occurs. Which is weird, as I see indexes as big as 10k. So where 888 comes from? How to avoid this error?

I have checked the max, min values:

display(returns) returns.sort_values(ascending=True)

I wanted to remove positions 3104 and 14482 as those values are too big.

However, as explained above the error occurred.

Initial goal would be to plot returns. My plot is currently as follows:

plt.hist(returns,30);

What I want is a histogram with much shorter x-axis between -0.5 and 0.5. Something like,

Body:
I have a data set containing a few stocks on a time frame. I plotted returns = df['high_value'].pct_change()[1:] which is a percent change of high_value being the highest value recorded value that date under specific stock name. I detected some outliers in rows 3104 & 14482. However, my method doesn't work as

index 3104 is out of bounds for axis 0 with size 888

error occurs. Which is weird, as I see indexes as big as 10k. So where 888 comes from? How to avoid this error?

I have checked the max, min values:

display(returns) returns.sort_values(ascending=True)

I wanted to remove positions 3104 and 14482 as those values are too big.

However, as explained above the error occurred.

Initial goal would be to plot returns. My plot is currently as follows:

plt.hist(returns,30);

What I want is a histogram with much shorter x-axis between -0.5 and 0.5. Something like,


问:
About circuit breaker in nodejs
Can we wrap our all api end points in single instance of circuitbreaker in nodejs?

```<code>  breaker.on("open",()=>{
    console.log("Open");
  })
  breaker.on("close",()=>{
    console.log("closed");
  })
  breaker.on("success",()=>{
    console.log("success");
  })
  //  throw new Error('Error');

  return breaker.fire('/')
  .then(data => res.json(brands))
  .catch(next);

//  return breaker.fire('/').then((data) =>{
//   throw new Error('Error');
//   }).catch((next) => {
//     throw new Error('Error');
//   });
  }
</code>```

i am expecting to wrap more method in this circuit breaker

Title: About circuit breaker in nodejs

Body:
Can we wrap our all api end points in single instance of circuitbreaker in nodejs?

  breaker.on("open",()=>{
    console.log("Open");
  })
  breaker.on("close",()=>{
    console.log("closed");
  })
  breaker.on("success",()=>{
    console.log("success");
  })
  //  throw new Error('Error');

  return breaker.fire('/')
  .then(data => res.json(brands))
  .catch(next);

//  return breaker.fire('/').then((data) =>{
//   throw new Error('Error');
//   }).catch((next) => {
//     throw new Error('Error');
//   });
  }

i am expecting to wrap more method in this circuit breaker


问:
Solving a dp problem from codeforces named Cut Ribbon
I was trying to solve this problem but I am getting wrong answer for some input. Can anyone explain where the problem is? Here is my code:

```<code>#include<bits/stdc++.h>
using namespace std;
#define INF -999999999

int dp[4001][4001],a[3];
int Ribbon(int n,int i)
{
    if(i==3)
    {
        if(n==0)
            return 0;
        if(n>0)
            return INF;
    }
    if(dp[n][i]!=-1)
        return dp[n][i];
    int include=0,exclude=0;
    if(n-a[i]>=0)
        include=Ribbon(n-a[i],i)+1;
    exclude=Ribbon(n,i+1);
    return dp[n][i]=max(include,exclude);
}

int main()
{
    memset(dp,-1,sizeof dp);
    int n,ans=0;
    cin>>n>>a[0]>>a[1]>>a[2];
    ans=Ribbon(n,2);
    cout<<ans<<endl;

}
</code>```

When I am giving 7 5 5 2 as input, it is giving 3 in answer whereas it should be 2.

Body:
I was trying to solve this problem but I am getting wrong answer for some input. Can anyone explain where the problem is? Here is my code:

#include<bits/stdc++.h>
using namespace std;
#define INF -999999999

int dp[4001][4001],a[3];
int Ribbon(int n,int i)
{
    if(i==3)
    {
        if(n==0)
            return 0;
        if(n>0)
            return INF;
    }
    if(dp[n][i]!=-1)
        return dp[n][i];
    int include=0,exclude=0;
    if(n-a[i]>=0)
        include=Ribbon(n-a[i],i)+1;
    exclude=Ribbon(n,i+1);
    return dp[n][i]=max(include,exclude);
}

int main()
{
    memset(dp,-1,sizeof dp);
    int n,ans=0;
    cin>>n>>a[0]>>a[1]>>a[2];
    ans=Ribbon(n,2);
    cout<<ans<<endl;

}

When I am giving 7 5 5 2 as input, it is giving 3 in answer whereas it should be 2.