问:
How can I get both the audio I hear from microphone and the one I speak into?
I have been trying out this code:

```<code>import pyaudio
import wave

FORMAT = pyaudio.paInt16
CHANNELS = 2
RATE = 16000
CHUNK = 1024
RECORD_SECONDS = 5
WAVE_OUTPUT_FILENAME = "pytest.wav"
MIC_INDEX = 5

audio = pyaudio.PyAudio()
print(audio.get_default_output_device_info())

# start Recording
stream = audio.open(format=FORMAT, channels=CHANNELS, input_device_index=MIC_INDEX,
                rate=RATE, input=True,
                frames_per_buffer=CHUNK)
print ("recording...")
frames = []

for i in range(0, int(RATE / CHUNK * RECORD_SECONDS)):
    data = stream.read(CHUNK, exception_on_overflow = False)

    frames.append(data)
print ("finished recording")

# stop Recording
stream.stop_stream()
stream.close()
audio.terminate()

waveFile = wave.open(WAVE_OUTPUT_FILENAME, 'wb')
waveFile.setnchannels(CHANNELS)
waveFile.setsampwidth(audio.get_sample_size(FORMAT))
waveFile.setframerate(RATE)
waveFile.writeframes(b''.join(frames))
waveFile.close()

</code>```

{'index': 2, 'structVersion': 2, 'name': 'External Headphones', 'hostApi': 0, 'maxInputChannels': 0, 'maxOutputChannels': 2, 'defaultLowInputLatency': 0.01, 'defaultLowOutputLatency': 0.004875, 'defaultHighInputLatency': 0.1, 'defaultHighOutputLatency': 0.014208333333333333, 'defaultSampleRate': 48000.0}

By default, it is using my External Headphones which is correct. However, this code produces an error for CHANNELS=2 but works for CHANNELS=1 for just the speaking part. Does anyone know how I can get both listening + speaking in python.

Body:
I have been trying out this code:

import pyaudio
import wave

FORMAT = pyaudio.paInt16
CHANNELS = 2
RATE = 16000
CHUNK = 1024
RECORD_SECONDS = 5
WAVE_OUTPUT_FILENAME = "pytest.wav"
MIC_INDEX = 5

audio = pyaudio.PyAudio()
print(audio.get_default_output_device_info())

# start Recording
stream = audio.open(format=FORMAT, channels=CHANNELS, input_device_index=MIC_INDEX,
                rate=RATE, input=True,
                frames_per_buffer=CHUNK)
print ("recording...")
frames = []

for i in range(0, int(RATE / CHUNK * RECORD_SECONDS)):
    data = stream.read(CHUNK, exception_on_overflow = False)

    frames.append(data)
print ("finished recording")

# stop Recording
stream.stop_stream()
stream.close()
audio.terminate()

waveFile = wave.open(WAVE_OUTPUT_FILENAME, 'wb')
waveFile.setnchannels(CHANNELS)
waveFile.setsampwidth(audio.get_sample_size(FORMAT))
waveFile.setframerate(RATE)
waveFile.writeframes(b''.join(frames))
waveFile.close()

{'index': 2, 'structVersion': 2, 'name': 'External Headphones', 'hostApi': 0, 'maxInputChannels': 0, 'maxOutputChannels': 2, 'defaultLowInputLatency': 0.01, 'defaultLowOutputLatency': 0.004875, 'defaultHighInputLatency': 0.1, 'defaultHighOutputLatency': 0.014208333333333333, 'defaultSampleRate': 48000.0}

By default, it is using my External Headphones which is correct. However, this code produces an error for CHANNELS=2 but works for CHANNELS=1 for just the speaking part. Does anyone know how I can get both listening + speaking in python.


来源: stackexchange

问:
How to integrate DocuSign e-Signature API in Drupal 9
I have to integrate DocuSign API in Drupal 9. I tried a lot, but I couldn't do it.
What steps should we take to perform DocuSign integration in Drupal 9?

I tried to create a custom module. also inside the module, I created the configuration form and custom services and inject custom services in the controller file. but didn't find correct solutions.

ContentLicense: CC BY-SA 4.0


问:
How do I print colored and centered text at the same time using python?
I can print centered text just fine using myString.center(shutil.get_terminal_size().columns) and colors using colorama. However, using them together offsets the text.

How do I print colored text in the center of the terminal without the offset the coloring creates?


问:
How to check if two functions are equal?
I need to keep a list of unique functions. So, listeners below should have a length of 1

```<code>final listeners = <VoidCallback>[];
for (int i = 0; i < 5; i++) {
  void listener() => setState(() {});
  if (!listeners.contains(listener)) {
    listeners.add(listener);
  }
}
</code>```

But contains is returning false, so the same closure is added 5x. I tried testing with listener.hashCode but each hash was unique, so listeners.length was 5.

Is it possible to test for the same function?

If I move the function outsize

```<code>final listeners = <VoidCallback>[];
for (int i = 0; i < 5; i++) {
  void listener() => setState(() {});
  if (!listeners.contains(listener)) {
    listeners.add(listener);
  }
}
</code>```

Then listeners.length is 1, but I'm writing a library and need to accommodate the first use case.

Body:
I need to keep a list of unique functions. So, listeners below should have a length of 1

final listeners = <VoidCallback>[];
for (int i = 0; i < 5; i++) {
  void listener() => setState(() {});
  if (!listeners.contains(listener)) {
    listeners.add(listener);
  }
}

But contains is returning false, so the same closure is added 5x. I tried testing with listener.hashCode but each hash was unique, so listeners.length was 5.

Is it possible to test for the same function?

If I move the function outsize

final listeners = <VoidCallback>[];
for (int i = 0; i < 5; i++) {
  void listener() => setState(() {});
  if (!listeners.contains(listener)) {
    listeners.add(listener);
  }
}

Then listeners.length is 1, but I'm writing a library and need to accommodate the first use case.


问:
testing form fields as a shadow dom elements with react testing-library and jest
We have our own web component and using the same with react component as generic-component. I am trying to test those custom elements which are created inside the shadow dom for our form-fields.
Now there are multiple input fields in my form. I am only able to access one but not others i.e only one field. I am using react-hook-form to handle the form stimulation.

I tried the below query and looped over each input to get the element

```<code>const customInput = document.querySelectorAll("hds-input")
customInput.shadowRoot.querySelector("input[name='mapName']")
</code>```
```<code>  it("check form input fields with dummy values", async () => {
    render(<Order3DMaps />);
    const form = document.querySelector("form");
    expect(form).toBeInTheDocument();

    expect(screen.getByText("Basic Information")).toBeInTheDocument();
    //get the field and add use input value
    const hdsInput = document.querySelectorAll("hds-input");
    hdsInput.forEach((element) => {
      const mapName = element.shadowRoot.querySelector("input[name='mapName']");
      const rawDataSiteName = element.shadowRoot.querySelector("input[name='rawDataSiteName']");
      userEvent.type(mapName, "testmapname");
      const organizationId = element.querySelector(
        "input[name='organizationId']"
      );
      expect(organizationId).toBeDisabled();
    });
</code>```

In the above test case rawDataSiteName is always null. However, when I debug in the browser console and see the dom element, it's present but not accessible while writing a test case.

My idea here is to get the element and do userEvent like type and click on form fields to cover the unit testing. However, after spending a lot of time got to know that the testing library is not supporting shadow-dom which I found strange. As it is a dom testing library it should support all the dom.

Please help me to understand what I am missing here. Any help is appreciated.
Thanks

Body:
We have our own web component and using the same with react component as generic-component. I am trying to test those custom elements which are created inside the shadow dom for our form-fields.
Now there are multiple input fields in my form. I am only able to access one but not others i.e only one field. I am using react-hook-form to handle the form stimulation.

I tried the below query and looped over each input to get the element

const customInput = document.querySelectorAll("hds-input")
customInput.shadowRoot.querySelector("input[name='mapName']")

  it("check form input fields with dummy values", async () => {
    render(<Order3DMaps />);
    const form = document.querySelector("form");
    expect(form).toBeInTheDocument();

    expect(screen.getByText("Basic Information")).toBeInTheDocument();
    //get the field and add use input value
    const hdsInput = document.querySelectorAll("hds-input");
    hdsInput.forEach((element) => {
      const mapName = element.shadowRoot.querySelector("input[name='mapName']");
      const rawDataSiteName = element.shadowRoot.querySelector("input[name='rawDataSiteName']");
      userEvent.type(mapName, "testmapname");
      const organizationId = element.querySelector(
        "input[name='organizationId']"
      );
      expect(organizationId).toBeDisabled();
    });

In the above test case rawDataSiteName is always null. However, when I debug in the browser console and see the dom element, it's present but not accessible while writing a test case.

My idea here is to get the element and do userEvent like type and click on form fields to cover the unit testing. However, after spending a lot of time got to know that the testing library is not supporting shadow-dom which I found strange. As it is a dom testing library it should support all the dom.

Please help me to understand what I am missing here. Any help is appreciated.
Thanks


问:
How to establish 2 way audio connection with bluethooth between android phone and windows PC?
I would like my phone to recognize my computer as a headset when I receive or initiate a call. I know that Microsoft Phone Link and CallCenter do the same. How could I establish a two-way audio connection with Bluetooth between an android phone and a windows PC preferably using C# (or any other C language)?</p>


问:
Way to update receipt in Google business message
I am trying to send the read receipt to a message on behalf of the agent. But the bmApi.conversations.messages.updateReceipt() is not working. It is saying that it is not a function.

I am trying to do as per the documentation

I am able to send messages using this bmApi but I am unable to update it using a receipt.
But I am getting error of not a function. I am using "^1.0.3" version of "businessmessages".

Why there is no such function or how can I find it?


问:
Easy OCR can’t recognize multiple choice answers with one answer circled
I have an image with question and multiple choice answers labeled A, B, C, D. One of this letter is circled by human handwriting. When I use easy OCR, it is recognizing the A,B,C,D but can’t recognize which letter is circled. See the image.
enter image description here
How to do this ?

Installed EasyOCR and selected ROI, getting output as A B C D, but I need one of them as circled Letter.


问:
Download Notifications actions
I have an app that in part of this app downloads video files.
I show the download in the notification in the status bar.
and every notification has a cancel action button.
in the first notification cancel action button enable but in another notification cancel action button is disabled!!!

please help me.

my classes:

```<code>    private void DownloadMovie(String _link, String fileName)
{

   BottomSheetDialog bottomSheetDialog = new BottomSheetDialog(ProductDetails.this);
    bottomSheetDialog.setContentView(R.layout.dialog_startingdownload);
    bottomSheetDialog.setCancelable(true);

    MaterialButton reject_btn = bottomSheetDialog.findViewById(R.id.canceldw_btn);
    MaterialButton close_btn = bottomSheetDialog.findViewById(R.id.closeWindow);
    ProgressBar progressBar = bottomSheetDialog.findViewById(R.id.progressbar);
    TextView downloadingtxt = bottomSheetDialog.findViewById(R.id.txt);
    TextView progresstext = bottomSheetDialog.findViewById(R.id.progresstxt);
    TextView TVSizeDownload = bottomSheetDialog.findViewById(R.id.TVSizeDownload);
    TextView TVSizeTypeDownload = bottomSheetDialog.findViewById(R.id.TVSizeTypeDownload);

     TextView fileSizetxt = bottomSheetDialog.findViewById(R.id.fileSize);

    assert TVSizeDownload != null;
    TVSizeDownload.setVisibility(VISIBLE);
    assert TVSizeTypeDownload != null;
    TVSizeTypeDownload.setVisibility(VISIBLE);
    assert progresstext != null;
    progresstext.setVisibility(VISIBLE);
    assert downloadingtxt != null;
    downloadingtxt.setVisibility(VISIBLE);
    assert progressBar != null;
    progressBar.setVisibility(VISIBLE);
    assert reject_btn != null;
    reject_btn.setVisibility(VISIBLE);
    assert fileSizetxt != null;
    fileSizetxt.setVisibility(VISIBLE);
    assert close_btn != null;
    close_btn.setVisibility(VISIBLE);

    downloadManager = new ThinDownloadManager(1);
    retryPolicy = new DefaultRetryPolicy();
   NewDownloadClass myDownloadStatusListener = new
   NewDownloadClass(downloadManager, progresstext, downloadingtxt,
  TVSizeDownload, TVSizeTypeDownload, pathdata, fileName,
            bottomSheetDialog, progressBar, "film", titleName,

ProductDetails.this,lat,lng,product_id,user_id,token,os_ver,deviceName);

    Toast.makeText(this, "released"+"-"+downloadManager.isReleased(), Toast.LENGTH_SHORT).show();
    myDownloadStatusListener.delegate = this;

    isDownloadCompleted = false;

    Uri downloadUri = Uri.parse(_link);
    Uri destinationUri = Uri.parse(pathdata + fileName);
    retryPolicy = new DefaultRetryPolicy(5000, 3, 2f);
    downloadingtxt.setText("downloading");

    DownloadRequest downloadRequest = new DownloadRequest(downloadUri)
.setRetryPolicy(retryPolicy)
            .setDestinationURI(destinationUri).setPriority(DownloadRequest.Priority.HIGH)
            .setDownloadContext("first")//Optional
            .setDeleteDestinationFileOnFailure(true)
            .setDownloadResumable(true)
            .setStatusListener(myDownloadStatusListener);

    if (downloadManager.query(downloadId) == DownloadManager.STATUS_NOT_FOUND) {
        downloadId = downloadManager.add(downloadRequest);
    }

    close_btn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            bottomSheetDialog.dismiss();
        }
    });
     reject_btn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            bottomSheetDialog.dismiss();
            downloadManager.cancelAll();

            if (new File(pathdata + fileName).exists())
                if (new File(pathdata + fileName).delete()) {
                    Log.e("DEL FILE FROM SD", "--ok");
                }

            if (notificationId != 0)
                if (mNotifyManager != null)
                    mNotifyManager.cancel(notificationId);

            isDownloadCompleted=true;

        }
    });

    bottomSheetDialog.show();

}
</code>```

my NewDownloadClass:

```<code>public class NewDownloadClass implements DownloadStatusListenerV1 {

String type;

BottomSheetDialog bottomSheetDialog;
TextView downloadingtxt;
TextView progresstext;
TextView tvSizeDownload;
TextView tvSizeTypeDownload;
ProgressBar progressBar;
public ThinDownloadManager downloadManager;
public AsyncResponse delegate = null;

ProgressDialog bar;
static int i = 0;
Activity activity;
String link, id, name, path, unziplocate, state, notifName;

private static String TAG = "MainActivity";
private NotificationManager mNotifyManager;
private NotificationCompat.Builder mBuilder;
DownloadClass downloadClass;

String NOTIFICATION_CHANNEL_ID = "my_channel_id_01";
PendingIntent pendingIntent, dismissNotif;
int notificationId = 0;
String lat;
String lng;
String product_id;
String user_id;
String token;
String os_ver;
String deviceName;

public NewDownloadClass(ThinDownloadManager downloadManager, TextView
 progresstext, TextView downloadingtxt, TextView tvSizeDownload,
  TextView tvSizeTypeDownload,
                        String pathdata, String fileName,
   BottomSheetDialog bottomSheetDialog, ProgressBar progressBar,
     String film, String titleName,
                        ProductDetails productDetails, String lat,
   String lng, String product_id, String user_id, String token,
    String os_ver, String deviceName) {
    this.downloadManager = downloadManager;

    this.bottomSheetDialog = bottomSheetDialog;
    this.downloadingtxt = downloadingtxt;
    this.progresstext = progresstext;
    this.progressBar = progressBar;
    this.tvSizeDownload = tvSizeDownload;
    this.tvSizeTypeDownload = tvSizeTypeDownload;
    //        this.bar = progress;
    this.link = link;
    this.path = pathdata;
    this.name = fileName;

    this.state = film;
    this.notifName = titleName;
    this.activity = productDetails;
    this.lat = lat;
    this.lng = lng;
    this.product_id = product_id;
    this.user_id = user_id;
    this.token = token;
    this.os_ver = os_ver;
    this.deviceName = deviceName;
    //        this.mNotifyManager=mNotifyManager;
    //        this.mBuilder=mBuilder;
    //        this.notificationId=notificationId;

    preparAndShowDownload();

}

private void preparAndShowDownload() {

    notificationId = new Random().nextInt(); // just use a counter in
    some util class...
    //behtare id khode file bashe ke uniqe

    // for open activity
    Intent intent = new Intent(activity, ProductDetails.class);
    //todo intent put extra
    //todo check in below android 6 and api 23

    intent.putExtra("lat", lat);
    intent.putExtra("lng", lng);
    intent.putExtra("product_id", product_id);
    intent.putExtra("user_id", user_id);
    intent.putExtra("token", token);
    intent.putExtra("os_ver", os_ver);
    intent.putExtra("deviceName", deviceName);

    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK |
    Intent.FLAG_ACTIVITY_CLEAR_TASK);
    if (android.os.Build.VERSION.SDK_INT >=
     android.os.Build.VERSION_CODES.M) {

        pendingIntent = PendingIntent.getActivity(activity, 0,
    intent, PendingIntent.FLAG_UPDATE_CURRENT);
    }

    mNotifyManager = (NotificationManager)
    activity.getSystemService(Context.NOTIFICATION_SERVICE);
    mBuilder = null;
    if (android.os.Build.VERSION.SDK_INT >=
        android.os.Build.VERSION_CODES.O) {
        int importance = NotificationManager.IMPORTANCE_DEFAULT;
        NotificationChannel notificationChannel = new
       NotificationChannel(NOTIFICATION_CHANNEL_ID, notifName,
        importance);

      mNotifyManager.createNotificationChannel(notificationChannel);
        mBuilder = new NotificationCompat.Builder(activity,
    notificationChannel.getId());
    } else {
        mBuilder = new NotificationCompat.Builder(activity);
    }

    ButtonReceiver.downloadManager = downloadManager;

    Intent buttonIntent = new Intent(activity, ButtonReceiver.class);
    buttonIntent.putExtra("notificationId", notificationId);
    buttonIntent.putExtra("file", path + name);
    dismissNotif = PendingIntent.getBroadcast(activity, 0,
    buttonIntent, PendingIntent.FLAG_CANCEL_CURRENT);

    mBuilder = mBuilder
            .setSmallIcon(R.drawable.ic_comica_about_logo)
            .setColor(ContextCompat.getColor(activity,
       R.color.ocher))
            .setContentTitle("downloading")
            .setOnlyAlertOnce(true)

            .setProgress(0, 0, false)
            .setDefaults(Notification.DEFAULT_ALL)
            .setPriority(Notification.PRIORITY_DEFAULT)
            .setAutoCancel(true)
            .setContentIntent(pendingIntent)
            .addAction(R.drawable.ic_close_notif, "انصراف",
       dismissNotif)

  .setLargeIcon(BitmapFactory.decodeResource(activity.getResources(),
 R.drawable.ic_comica_about_logo));

    mNotifyManager.notify(notificationId, mBuilder.build());

}

@Override
public void onDownloadComplete(DownloadRequest downloadRequest) {
    progressBar.setVisibility(View.GONE);
    downloadManager.release();
    bottomSheetDialog.dismiss();
    delegate.processFinish(true);

    downloadingtxt.setText("دانلود کامل شد.");

    mBuilder
            .setContentTitle("دانلود تمام شد")
            .setContentText("")

            // Removes the progress bar
            .setProgress(0, 0, false);
    mNotifyManager.notify(notificationId, mBuilder.build());

    if (notificationId != 0)
        mNotifyManager.cancel(notificationId);

}

@Override
public void onDownloadFailed(DownloadRequest downloadRequest, int
   errorCode, String errorMessage) {
    progressBar.setProgress(0);
    if (activity != null && !activity.isFinishing())
        bottomSheetDialog.dismiss();
    downloadManager.cancelAll();

    File file = new File(path + name);
    if (file.exists())
        if (file.delete())
            Log.e("failed del  sd", "--ok--" + path + name);
        else
            Log.e("failed del  sd", "--NOT ok--" + path + name);

    if (notificationId != 0)
        mNotifyManager.cancel(notificationId);

    delegate.allowDownload(true);

}

@Override
public void onProgress(DownloadRequest downloadRequest, long
  totalBytes, long downloadedBytes, int progress) {
    progressBar.setProgress(progress);
    progresstext.setText(progress + "%");

    int size = (int) ((totalBytes / 1024) / 1024);
    String type;
    if (size < 1) {
        size = (int) (totalBytes / (1024));
        type = " KB";
    } else {
        type = " MB";
    }
    tvSizeDownload.setText(String.valueOf(size));
    tvSizeTypeDownload.setText(type);

    mBuilder
            .setSubText(progress + "%")
            .setProgress(100, progress, false);

    mNotifyManager.notify(notificationId, mBuilder.build());
   }

  }
</code>```

Title: Download Notifications actions

Body:
I have an app that in part of this app downloads video files.
I show the download in the notification in the status bar.
and every notification has a cancel action button.
in the first notification cancel action button enable but in another notification cancel action button is disabled!!!

please help me.

my classes:

    private void DownloadMovie(String _link, String fileName)
{

   BottomSheetDialog bottomSheetDialog = new BottomSheetDialog(ProductDetails.this);
    bottomSheetDialog.setContentView(R.layout.dialog_startingdownload);
    bottomSheetDialog.setCancelable(true);

    MaterialButton reject_btn = bottomSheetDialog.findViewById(R.id.canceldw_btn);
    MaterialButton close_btn = bottomSheetDialog.findViewById(R.id.closeWindow);
    ProgressBar progressBar = bottomSheetDialog.findViewById(R.id.progressbar);
    TextView downloadingtxt = bottomSheetDialog.findViewById(R.id.txt);
    TextView progresstext = bottomSheetDialog.findViewById(R.id.progresstxt);
    TextView TVSizeDownload = bottomSheetDialog.findViewById(R.id.TVSizeDownload);
    TextView TVSizeTypeDownload = bottomSheetDialog.findViewById(R.id.TVSizeTypeDownload);

     TextView fileSizetxt = bottomSheetDialog.findViewById(R.id.fileSize);

    assert TVSizeDownload != null;
    TVSizeDownload.setVisibility(VISIBLE);
    assert TVSizeTypeDownload != null;
    TVSizeTypeDownload.setVisibility(VISIBLE);
    assert progresstext != null;
    progresstext.setVisibility(VISIBLE);
    assert downloadingtxt != null;
    downloadingtxt.setVisibility(VISIBLE);
    assert progressBar != null;
    progressBar.setVisibility(VISIBLE);
    assert reject_btn != null;
    reject_btn.setVisibility(VISIBLE);
    assert fileSizetxt != null;
    fileSizetxt.setVisibility(VISIBLE);
    assert close_btn != null;
    close_btn.setVisibility(VISIBLE);

    downloadManager = new ThinDownloadManager(1);
    retryPolicy = new DefaultRetryPolicy();
   NewDownloadClass myDownloadStatusListener = new
   NewDownloadClass(downloadManager, progresstext, downloadingtxt,
  TVSizeDownload, TVSizeTypeDownload, pathdata, fileName,
            bottomSheetDialog, progressBar, "film", titleName,

ProductDetails.this,lat,lng,product_id,user_id,token,os_ver,deviceName);

    Toast.makeText(this, "released"+"-"+downloadManager.isReleased(), Toast.LENGTH_SHORT).show();
    myDownloadStatusListener.delegate = this;

    isDownloadCompleted = false;

    Uri downloadUri = Uri.parse(_link);
    Uri destinationUri = Uri.parse(pathdata + fileName);
    retryPolicy = new DefaultRetryPolicy(5000, 3, 2f);
    downloadingtxt.setText("downloading");

    DownloadRequest downloadRequest = new DownloadRequest(downloadUri)
.setRetryPolicy(retryPolicy)
            .setDestinationURI(destinationUri).setPriority(DownloadRequest.Priority.HIGH)
            .setDownloadContext("first")//Optional
            .setDeleteDestinationFileOnFailure(true)
            .setDownloadResumable(true)
            .setStatusListener(myDownloadStatusListener);

    if (downloadManager.query(downloadId) == DownloadManager.STATUS_NOT_FOUND) {
        downloadId = downloadManager.add(downloadRequest);
    }

    close_btn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            bottomSheetDialog.dismiss();
        }
    });
     reject_btn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            bottomSheetDialog.dismiss();
            downloadManager.cancelAll();

            if (new File(pathdata + fileName).exists())
                if (new File(pathdata + fileName).delete()) {
                    Log.e("DEL FILE FROM SD", "--ok");
                }

            if (notificationId != 0)
                if (mNotifyManager != null)
                    mNotifyManager.cancel(notificationId);

            isDownloadCompleted=true;

        }
    });

    bottomSheetDialog.show();

}

my NewDownloadClass:

public class NewDownloadClass implements DownloadStatusListenerV1 {

String type;

BottomSheetDialog bottomSheetDialog;
TextView downloadingtxt;
TextView progresstext;
TextView tvSizeDownload;
TextView tvSizeTypeDownload;
ProgressBar progressBar;
public ThinDownloadManager downloadManager;
public AsyncResponse delegate = null;

ProgressDialog bar;
static int i = 0;
Activity activity;
String link, id, name, path, unziplocate, state, notifName;

private static String TAG = "MainActivity";
private NotificationManager mNotifyManager;
private NotificationCompat.Builder mBuilder;
DownloadClass downloadClass;

String NOTIFICATION_CHANNEL_ID = "my_channel_id_01";
PendingIntent pendingIntent, dismissNotif;
int notificationId = 0;
String lat;
String lng;
String product_id;
String user_id;
String token;
String os_ver;
String deviceName;

public NewDownloadClass(ThinDownloadManager downloadManager, TextView
 progresstext, TextView downloadingtxt, TextView tvSizeDownload,
  TextView tvSizeTypeDownload,
                        String pathdata, String fileName,
   BottomSheetDialog bottomSheetDialog, ProgressBar progressBar,
     String film, String titleName,
                        ProductDetails productDetails, String lat,
   String lng, String product_id, String user_id, String token,
    String os_ver, String deviceName) {
    this.downloadManager = downloadManager;

    this.bottomSheetDialog = bottomSheetDialog;
    this.downloadingtxt = downloadingtxt;
    this.progresstext = progresstext;
    this.progressBar = progressBar;
    this.tvSizeDownload = tvSizeDownload;
    this.tvSizeTypeDownload = tvSizeTypeDownload;
    //        this.bar = progress;
    this.link = link;
    this.path = pathdata;
    this.name = fileName;

    this.state = film;
    this.notifName = titleName;
    this.activity = productDetails;
    this.lat = lat;
    this.lng = lng;
    this.product_id = product_id;
    this.user_id = user_id;
    this.token = token;
    this.os_ver = os_ver;
    this.deviceName = deviceName;
    //        this.mNotifyManager=mNotifyManager;
    //        this.mBuilder=mBuilder;
    //        this.notificationId=notificationId;

    preparAndShowDownload();

}

private void preparAndShowDownload() {

    notificationId = new Random().nextInt(); // just use a counter in
    some util class...
    //behtare id khode file bashe ke uniqe

    // for open activity
    Intent intent = new Intent(activity, ProductDetails.class);
    //todo intent put extra
    //todo check in below android 6 and api 23

    intent.putExtra("lat", lat);
    intent.putExtra("lng", lng);
    intent.putExtra("product_id", product_id);
    intent.putExtra("user_id", user_id);
    intent.putExtra("token", token);
    intent.putExtra("os_ver", os_ver);
    intent.putExtra("deviceName", deviceName);

    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK |
    Intent.FLAG_ACTIVITY_CLEAR_TASK);
    if (android.os.Build.VERSION.SDK_INT >=
     android.os.Build.VERSION_CODES.M) {

        pendingIntent = PendingIntent.getActivity(activity, 0,
    intent, PendingIntent.FLAG_UPDATE_CURRENT);
    }

    mNotifyManager = (NotificationManager)
    activity.getSystemService(Context.NOTIFICATION_SERVICE);
    mBuilder = null;
    if (android.os.Build.VERSION.SDK_INT >=
        android.os.Build.VERSION_CODES.O) {
        int importance = NotificationManager.IMPORTANCE_DEFAULT;
        NotificationChannel notificationChannel = new
       NotificationChannel(NOTIFICATION_CHANNEL_ID, notifName,
        importance);

      mNotifyManager.createNotificationChannel(notificationChannel);
        mBuilder = new NotificationCompat.Builder(activity,
    notificationChannel.getId());
    } else {
        mBuilder = new NotificationCompat.Builder(activity);
    }

    ButtonReceiver.downloadManager = downloadManager;

    Intent buttonIntent = new Intent(activity, ButtonReceiver.class);
    buttonIntent.putExtra("notificationId", notificationId);
    buttonIntent.putExtra("file", path + name);
    dismissNotif = PendingIntent.getBroadcast(activity, 0,
    buttonIntent, PendingIntent.FLAG_CANCEL_CURRENT);

    mBuilder = mBuilder
            .setSmallIcon(R.drawable.ic_comica_about_logo)
            .setColor(ContextCompat.getColor(activity,
       R.color.ocher))
            .setContentTitle("downloading")
            .setOnlyAlertOnce(true)

            .setProgress(0, 0, false)
            .setDefaults(Notification.DEFAULT_ALL)
            .setPriority(Notification.PRIORITY_DEFAULT)
            .setAutoCancel(true)
            .setContentIntent(pendingIntent)
            .addAction(R.drawable.ic_close_notif, "انصراف",
       dismissNotif)

  .setLargeIcon(BitmapFactory.decodeResource(activity.getResources(),
 R.drawable.ic_comica_about_logo));

    mNotifyManager.notify(notificationId, mBuilder.build());

}

@Override
public void onDownloadComplete(DownloadRequest downloadRequest) {
    progressBar.setVisibility(View.GONE);
    downloadManager.release();
    bottomSheetDialog.dismiss();
    delegate.processFinish(true);

    downloadingtxt.setText("دانلود کامل شد.");

    mBuilder
            .setContentTitle("دانلود تمام شد")
            .setContentText("")

            // Removes the progress bar
            .setProgress(0, 0, false);
    mNotifyManager.notify(notificationId, mBuilder.build());

    if (notificationId != 0)
        mNotifyManager.cancel(notificationId);

}

@Override
public void onDownloadFailed(DownloadRequest downloadRequest, int
   errorCode, String errorMessage) {
    progressBar.setProgress(0);
    if (activity != null && !activity.isFinishing())
        bottomSheetDialog.dismiss();
    downloadManager.cancelAll();

    File file = new File(path + name);
    if (file.exists())
        if (file.delete())
            Log.e("failed del  sd", "--ok--" + path + name);
        else
            Log.e("failed del  sd", "--NOT ok--" + path + name);

    if (notificationId != 0)
        mNotifyManager.cancel(notificationId);

    delegate.allowDownload(true);

}

@Override
public void onProgress(DownloadRequest downloadRequest, long
  totalBytes, long downloadedBytes, int progress) {
    progressBar.setProgress(progress);
    progresstext.setText(progress + "%");

    int size = (int) ((totalBytes / 1024) / 1024);
    String type;
    if (size < 1) {
        size = (int) (totalBytes / (1024));
        type = " KB";
    } else {
        type = " MB";
    }
    tvSizeDownload.setText(String.valueOf(size));
    tvSizeTypeDownload.setText(type);

    mBuilder
            .setSubText(progress + "%")
            .setProgress(100, progress, false);

    mNotifyManager.notify(notificationId, mBuilder.build());
   }

  }


问:
weblogic.PlanGenerator utility is failing with "Could not find or load main class weblogic.PlanGenerator"
Generating deployment plan file for a .war file using the command "java weblogic.PlanGenerator -all application.war" is failing with Error: Could not find or load main class weblogic.PlanGenerator


问:
want to write screen reload function in public folder react js
I have intregate firebase cloud messaging service in project , on Onbackground function that in firebase-messaging-sw.js file,  I want to refresh the screen or an API call which is in src folder , but i can not import src file in public folder.

I have try to reload screen in responce of Onbackground , in which console is printing
code:
file location public > firebase-messaging-sw.js

```<code>
messaging.onBackgroundMessage((payload) => {
    debugger
    console.log(
        "[firebase-messaging-sw.js] Received background message ",
        payload
    );

    window.location.reload();
    const notificationTitle = payload.data.title;
    const notificationOptions = {
        body: payload.data.message,
        icon: payload.notification.image,
    };
    // showNotification(notificationTitle, notificationOptions )

});
</code>```

Body:
I have intregate firebase cloud messaging service in project , on Onbackground function that in firebase-messaging-sw.js file,  I want to refresh the screen or an API call which is in src folder , but i can not import src file in public folder.

I have try to reload screen in responce of Onbackground , in which console is printing
code:
file location public > firebase-messaging-sw.js

messaging.onBackgroundMessage((payload) => {
    debugger
    console.log(
        "[firebase-messaging-sw.js] Received background message ",
        payload
    );

    window.location.reload();
    const notificationTitle = payload.data.title;
    const notificationOptions = {
        body: payload.data.message,
        icon: payload.notification.image,
    };
    // showNotification(notificationTitle, notificationOptions )

});


问:
ModuleNotFoundError in Conda environment after installing module
I opened VSCode through my anaconda environment 'fastAPI'. I am attempting to run a script "main.py" in my VSCode powershell terminal. Directory is "fast-api".

```<code>PS C:\Users\James\OneDrive\Documents\VSCode\projects\fast-api> python3 main.py
</code>```

This returns "ModuleNotFoundError: No Module named 'fastapi'"

I was able to run my code yesterday after using

```<code>pip install fastapi[all]
</code>```

but today my code would not run as if I never installed the module. Import line below.

```<code>from fastapi import FastAPI
</code>```

Today I have tried the following options, seperately of course.

```<code>pip install fastapi[all]

conda install fastapi[all]

conda install -c conda-forge fastapi
</code>```

To check my environment status, I used the following commands. The first returns my base, R-MINI, and fastAPI environment with a star next to it as expected. fastAPi location is 'C:\Users\James\anaconda3\envs\fastAPI'. Could this path be the issue? The second line returns my active packages which includes 'fastapi 0.88.0 pyhd8ed1ab_0 conda-forge'.

```<code>conda env list

conda list
</code>```

A solution I saw earlier suggested folium installation as well but that changed nothing. Running python 3.9.15. Deleted and installed Anaconda today so I am up to date with my conda distribution as well. My biggest source of confusion is how I was able to run the code last night even though I'm sure I had the same setup. I think the issue is that I'm not running the code in the environment I installed the modules in. I can't seem to fix that myself though if that is the issue. I appreciate any help, thanks.

Body:
I opened VSCode through my anaconda environment 'fastAPI'. I am attempting to run a script "main.py" in my VSCode powershell terminal. Directory is "fast-api".

PS C:\Users\James\OneDrive\Documents\VSCode\projects\fast-api> python3 main.py

This returns "ModuleNotFoundError: No Module named 'fastapi'"

I was able to run my code yesterday after using

pip install fastapi[all]

but today my code would not run as if I never installed the module. Import line below.

from fastapi import FastAPI

Today I have tried the following options, seperately of course.

pip install fastapi[all]

conda install fastapi[all]

conda install -c conda-forge fastapi

To check my environment status, I used the following commands. The first returns my base, R-MINI, and fastAPI environment with a star next to it as expected. fastAPi location is 'C:\Users\James\anaconda3\envs\fastAPI'. Could this path be the issue? The second line returns my active packages which includes 'fastapi 0.88.0 pyhd8ed1ab_0 conda-forge'.

conda env list

conda list

A solution I saw earlier suggested folium installation as well but that changed nothing. Running python 3.9.15. Deleted and installed Anaconda today so I am up to date with my conda distribution as well. My biggest source of confusion is how I was able to run the code last night even though I'm sure I had the same setup. I think the issue is that I'm not running the code in the environment I installed the modules in. I can't seem to fix that myself though if that is the issue. I appreciate any help, thanks.


问:
Cloning a complex hierarchical entity in typeorm
What is the easiest/best way to clone a complex hierarchical entity with typeorm?
The main issue is with ids (main entity ids and foreign key ids), which need to be re-generated for the new object.
I tried implementing a generic "clone" operation, but it's insufficient:

load the entity from the DB

delete all ids from the object recursively (assumes object id property is named id)

save the object to the db

As said it's not enough since this only deletes the main object ids, but doesn't deal with foreign key properties which can have various names depending on the relation names.
One option is to implement a non-generic clone for each of the entities in the model hierarchy, which is not very elegant code, and will require maintenance each time new entities/foreign keys are added.
Any other suggestions?


问:
How to connect MT4 account with quickfixj app?
Hello Guys I have built quickfix app with the help of [https://medium.com/@onrkrdmn.socialmedia/quickfixj-exersise-hello-world-fd14590d8a4b] this documentation link. Now I'm trying to build a connection with mt4 account using this code. But I dont't find any way to do this if you guys ever done this help me or you can also share some guidlines to acheive this.

I have tries many recources but it didnot work at all I use Java for this project and have to done with this.


问:
Gitlab CI/CD pipeline tests fails to connect to MongoDB Atlas even though my local machine testing does
When running NestJS tests in my local machine all tests runs smoothly and no error arises. However, when my pipeline runs tests on Gitlab, it fails to connect to the MongoDB Atlas giving the following error.
ERROR [MongooseModule] Unable to connect to the database.

From doing my own tests on the pipeline I have noticed that environment variables are indeed recognized by the pipeline environment and that my MongoDB atlas is allowing all IP addresses to access it, so I have no idea what to do, any help would be greatly appreciated.

Gitlab yml file (take note for node image I have also tried latest):

```<code>stages:
  - backend

cache:
  paths:
    - node_modules/
    - .npm/

backend:
  image: node:14.17.0
  stage: backend

variables:
  ABASSES_PASSWORD: $ABASSES_PASSWORD
  ABASSES_USERNAME: $ABASSES_USERNAME
  ADMIN_PASSWORD: $ADMIN_PASSWORD
  ADMIN_USERNAME: $ADMIN_USERNAME
  ERICS_PASSWORD: $ERICS_PASSWORD
  ERICS_USERNAME: $ERICS_USERNAME
  JWT_SECRET: $JWT_SECRET

script:
  - cd ./src/nestjs-backend
  - npm ci
  - npm run lint
  - npm run build
  - npm run test

artifacts:
  paths:
    - .env

only:
  - backend
</code>```

Pactum test file for NestJS server:

```<code>import { Test } from '@nestjs/testing';
import * as pactum from 'pactum';
import { INestApplication, ValidationPipe } from '@nestjs/common';
import { AppModule } from './../src/app.module';
import { UserDto } from 'src/users/dto/user.dto';
import * as dotenv from 'dotenv';
dotenv.config();

describe('AppController (e2e)', () => {
  describe('App e2e', function () {
    let app: INestApplication;
    beforeAll(async () => {
      jest.setTimeout(24000)
      const moduleRef = await Test.createTestingModule({
        imports: [AppModule],
      }).compile();
      app = moduleRef.createNestApplication();
      app.useGlobalPipes(new ValidationPipe({ whitelist: true }));
      await app.init();
      await app.listen(5000);
      pactum.request.setBaseUrl('http://127.0.0.1:5000');
    });
    afterAll(() => {
      app.close();
    });

    describe('User authorization', function () {
      let randomString = '';
      const possibleCharacter =
        'abcdefghijklmnopqrstuvwxyz0123456789QAZXSWEDCVFRTGBNHYMJUIKOLP';

      for (let i = 0; i < 8; i++)
        randomString += possibleCharacter.charAt(
          Math.floor(Math.random() * possibleCharacter.length),
        );

      const dto: UserDto = {
        username: `${randomString}@gmail.com`,
        firstName: 'Eric',
        lastName: 'Test',
        password: 'r43rfe$£fed!',
      };

      describe('Participant signup', () => {
        it('Should throw error if first and last names are empty', () => {
          return pactum
            .spec()
            .post('/participant/signup')
            .withBody({ username: dto.username, password: dto.password })
            .expectStatus(400);
        });

        it('Should throw error if username is empty', () => {
          return pactum
            .spec()
            .post('/participant/signup')
            .withBody({
              firstName: dto.firstName,
              lastName: dto.lastName,
              password: dto.password,
            })
            .expectStatus(400);
        });

        it('Should throw error if password is empty', () => {
          return pactum
            .spec()
            .post('/participant/signup')
            .withBody({
              username: dto.username,
              firstName: dto.firstName,
              lastName: dto.lastName,
            })
            .expectStatus(400);
        });

        it('Should signup if all parameters are correctly provided', () => {
          return pactum
            .spec()
            .post('/participant/signup')
            .withBody(dto)
            .expectStatus(201)
            .stores('participantId', '_id');
        });
      });

      describe('User login and deletion', () => {
        it('Should throw error if username empty', () => {
          return pactum
            .spec()
            .post('/participant/login')
            .withBody({ password: 'cdscds' })
            .expectStatus(401);
        });

        it('Should throw error if password empty', () => {
          return pactum
            .spec()
            .post('/participant/login')
            .withBody({ username: 'dswdesw' })
            .expectStatus(401);
        });

        it('Should throw error if body is empty', () => {
          return pactum.spec().post('/auth/login').expectStatus(404);
        });

        it('Should login with admin account', () => {
          return pactum
            .spec()
            .post('/researcher/login')
            .withBody({
              username: process.env.ADMIN_USERNAME,
              password: process.env.ADMIN_PASSWORD,
            })
            .expectStatus(201)
            .stores('jwt', 'jwt');
        });

        it('Should delete previously created account', () => {
          return pactum
            .spec()
            .delete('/admin/participant/delete/$S{participantId}')
            .withHeaders({ Authorization: 'Bearer $S{jwt}' })
            .expectStatus(200);
        });
      });
    });

  });
});
</code>```

If anyone can help it would be greatly appreciated I've spent countless hours trying to resolve this issue.

Body:
When running NestJS tests in my local machine all tests runs smoothly and no error arises. However, when my pipeline runs tests on Gitlab, it fails to connect to the MongoDB Atlas giving the following error.
ERROR [MongooseModule] Unable to connect to the database.

From doing my own tests on the pipeline I have noticed that environment variables are indeed recognized by the pipeline environment and that my MongoDB atlas is allowing all IP addresses to access it, so I have no idea what to do, any help would be greatly appreciated.

Gitlab yml file (take note for node image I have also tried latest):

stages:
  - backend

cache:
  paths:
    - node_modules/
    - .npm/

backend:
  image: node:14.17.0
  stage: backend

variables:
  ABASSES_PASSWORD: $ABASSES_PASSWORD
  ABASSES_USERNAME: $ABASSES_USERNAME
  ADMIN_PASSWORD: $ADMIN_PASSWORD
  ADMIN_USERNAME: $ADMIN_USERNAME
  ERICS_PASSWORD: $ERICS_PASSWORD
  ERICS_USERNAME: $ERICS_USERNAME
  JWT_SECRET: $JWT_SECRET

script:
  - cd ./src/nestjs-backend
  - npm ci
  - npm run lint
  - npm run build
  - npm run test

artifacts:
  paths:
    - .env

only:
  - backend

Pactum test file for NestJS server:

import { Test } from '@nestjs/testing';
import * as pactum from 'pactum';
import { INestApplication, ValidationPipe } from '@nestjs/common';
import { AppModule } from './../src/app.module';
import { UserDto } from 'src/users/dto/user.dto';
import * as dotenv from 'dotenv';
dotenv.config();

describe('AppController (e2e)', () => {
  describe('App e2e', function () {
    let app: INestApplication;
    beforeAll(async () => {
      jest.setTimeout(24000)
      const moduleRef = await Test.createTestingModule({
        imports: [AppModule],
      }).compile();
      app = moduleRef.createNestApplication();
      app.useGlobalPipes(new ValidationPipe({ whitelist: true }));
      await app.init();
      await app.listen(5000);
      pactum.request.setBaseUrl('http://127.0.0.1:5000');
    });
    afterAll(() => {
      app.close();
    });

    describe('User authorization', function () {
      let randomString = '';
      const possibleCharacter =
        'abcdefghijklmnopqrstuvwxyz0123456789QAZXSWEDCVFRTGBNHYMJUIKOLP';

      for (let i = 0; i < 8; i++)
        randomString += possibleCharacter.charAt(
          Math.floor(Math.random() * possibleCharacter.length),
        );

      const dto: UserDto = {
        username: `${randomString}@gmail.com`,
        firstName: 'Eric',
        lastName: 'Test',
        password: 'r43rfe$£fed!',
      };

      describe('Participant signup', () => {
        it('Should throw error if first and last names are empty', () => {
          return pactum
            .spec()
            .post('/participant/signup')
            .withBody({ username: dto.username, password: dto.password })
            .expectStatus(400);
        });

        it('Should throw error if username is empty', () => {
          return pactum
            .spec()
            .post('/participant/signup')
            .withBody({
              firstName: dto.firstName,
              lastName: dto.lastName,
              password: dto.password,
            })
            .expectStatus(400);
        });

        it('Should throw error if password is empty', () => {
          return pactum
            .spec()
            .post('/participant/signup')
            .withBody({
              username: dto.username,
              firstName: dto.firstName,
              lastName: dto.lastName,
            })
            .expectStatus(400);
        });

        it('Should signup if all parameters are correctly provided', () => {
          return pactum
            .spec()
            .post('/participant/signup')
            .withBody(dto)
            .expectStatus(201)
            .stores('participantId', '_id');
        });
      });

      describe('User login and deletion', () => {
        it('Should throw error if username empty', () => {
          return pactum
            .spec()
            .post('/participant/login')
            .withBody({ password: 'cdscds' })
            .expectStatus(401);
        });

        it('Should throw error if password empty', () => {
          return pactum
            .spec()
            .post('/participant/login')
            .withBody({ username: 'dswdesw' })
            .expectStatus(401);
        });

        it('Should throw error if body is empty', () => {
          return pactum.spec().post('/auth/login').expectStatus(404);
        });

        it('Should login with admin account', () => {
          return pactum
            .spec()
            .post('/researcher/login')
            .withBody({
              username: process.env.ADMIN_USERNAME,
              password: process.env.ADMIN_PASSWORD,
            })
            .expectStatus(201)
            .stores('jwt', 'jwt');
        });

        it('Should delete previously created account', () => {
          return pactum
            .spec()
            .delete('/admin/participant/delete/$S{participantId}')
            .withHeaders({ Authorization: 'Bearer $S{jwt}' })
            .expectStatus(200);
        });
      });
    });

  });
});

If anyone can help it would be greatly appreciated I've spent countless hours trying to resolve this issue.


问:
Use C++ ATL COM without registration for communication between 32-bit and 64-bit processes
I need to call into a 64-bit COM server from a 32-bit client. Both C++.

In order to avoid registration, I use the ROT to publish the class factory.

The IDispatch interface is used from the client to avoid marshaling issues.

I get an error at the first attempt to call a server method:

Error loading type library/DLL

```<code>CheckHR(driver.Invoke1(L"SetValue", &ret, &arg), "SetValue");
</code>```

Why do I need a type library or proxy if I only use IDispatch?

All the code is below.

IDL:

```<code>import "unknwn.idl";
[
    object,
    uuid(C3498C72-22F8-477A-B8BF-A6BCE9DE0596),
    dual,
    nonextensible,
    helpstring("IZebraServer Interface"),
    pointer_default(unique)
]
interface IZebraServer : IDispatch
{
    [id(1), helpstring("method GetValue")] HRESULT GetValue([out, retval] int* pValue);
    [id(2), helpstring("method SetValue")] HRESULT SetValue(int value);
};

[
    uuid(1632C43C-7C08-451F-A341-A6486F0CE517),
    version(1.0),
]
library ZebraServer
{
    importlib("stdole32.tlb");
    importlib("stdole2.tlb");

    [
        uuid(C2E745B1-6DA1-4DD4-AF10-5860182B66EF),
        helpstring("CZebraServer Class"),
    ]
    coclass CZebraServer
    {
        [default] interface IZebraServer;
    };
};
</code>```

Here is the server code:

```<code>#include <SDKDDKVer.h>
#include <atlbase.h>
#include <atlcom.h>
#include <atlctl.h>
#include <comdef.h>

#include <sstream>
#include <iostream>

using namespace ATL;

#include "ZebraServer_i.h"

inline void CheckHR(HRESULT hr, const char* msg)
{
    if (SUCCEEDED(hr))
        return;

    USES_CONVERSION;
    _com_error error(hr);
    std::ostringstream ss;
    ss << msg << "::" << W2A(error.ErrorMessage());
    throw std::exception(ss.str().c_str());
}

DWORD RegisterObjectInROT(
    IUnknown* pUnknown)
{
    // create binding context object
    CComPtr<IBindCtx> pBindCtx;
    CheckHR(CreateBindCtx(0, &pBindCtx), "CreateBindCtx");

    // Get a pointer to the ROT
    CComPtr<IRunningObjectTable> pRot;
    CheckHR(pBindCtx->GetRunningObjectTable(&pRot), "Getting ROT");

    // Create a moniker for the object
    CComPtr<IMoniker> pMoniker;
    CheckHR(CreateClassMoniker(CLSID_CZebraServer, &pMoniker), "CreateClassMoniker");
    // Register the object in the ROT with the specified display name
    DWORD dwRegisterCookie{};
    CheckHR(pRot->Register(
        ROTFLAGS_REGISTRATIONKEEPSALIVE,
        pUnknown,
        pMoniker,
        &dwRegisterCookie),
        "Register object");
    return dwRegisterCookie;
}

class ATL_NO_VTABLE CZebraServer :
    public CComObjectRootEx<CComSingleThreadModel>,
    public CComCoClass<CZebraServer, &CLSID_CZebraServer>,
    public IDispatchImpl<IZebraServer, &IID_IZebraServer, &LIBID_ZebraServer, /*wMajor =*/ 1, /*wMinor =*/ 0>
{
public:
    CZebraServer() {}

    DECLARE_NO_REGISTRY()

    BEGIN_COM_MAP(CZebraServer)
        COM_INTERFACE_ENTRY(IZebraServer)
        COM_INTERFACE_ENTRY(IDispatch)
    END_COM_MAP()

    // IZebraServer methods
    STDMETHOD(GetValue)(int* pVal)
    {
        *pVal = m_value;
        return S_OK;
    }

    STDMETHOD(SetValue)(int newVal)
    {
        m_value = newVal;
        return S_OK;
    }

private:
    int m_value = 0;
};

OBJECT_ENTRY_AUTO(__uuidof(CZebraServer), CZebraServer)

class ATL_NO_VTABLE CZebraServerFactory :
    public CComObjectRootEx<CComSingleThreadModel>,
    public CComCoClass<CZebraServerFactory, &CLSID_CZebraServer>,
    public IClassFactory
{
public:
    CZebraServerFactory() {}

    DECLARE_NO_REGISTRY()

    BEGIN_COM_MAP(CZebraServerFactory)
        COM_INTERFACE_ENTRY(IClassFactory)
    END_COM_MAP()

    // IClassFactory methods
    STDMETHOD(CreateInstance)(IUnknown* pUnkOuter, REFIID riid, void** ppv)
    {
        return CComCreator<CComObject<CZebraServer>>::CreateInstance(pUnkOuter, riid, ppv);
    }

    STDMETHOD(LockServer)(BOOL fLock);

};

OBJECT_ENTRY_AUTO(CLSID_CZebraServer, CZebraServerFactory)

CComObject<CZebraServerFactory>* g_pFactoryObject;

class CZebraServerModule : public ATL::CAtlExeModuleT<CZebraServerModule>
{
public:
    DECLARE_NO_REGISTRY()
    DECLARE_LIBID(LIBID_ZebraServer)

    HRESULT PreMessageLoop(int nShowCmd)
    {
        try {

            CheckHR(ATL::CAtlExeModuleT<CZebraServerModule>::PreMessageLoop(nShowCmd),
                "CAtlExeModuleT<CZebraServerModule>::PreMessageLoop");

            std::cout << "Server started" << std::endl;

            // Create an instance of the factory class
            CheckHR(CComObject<CZebraServerFactory>::CreateInstance(&g_pFactoryObject),
                "Create Class Factory Instance");

            // Query for the IUnknown interface
            DWORD dwRegisterCookie = RegisterObjectInROT(g_pFactoryObject);

        }
        catch (std::exception& ex)
        {
            std::cout << ex.what();
            return S_FALSE;
        }
        return S_OK;
    }
};
CZebraServerModule g_module;

HRESULT CZebraServerFactory::LockServer(BOOL fLock)
{
    if (fLock)
        g_module.Lock();
    else
        g_module.Unlock();
    return S_OK;
}

extern "C" int WINAPI _tWinMain(
    HINSTANCE /*hInstance*/,
    HINSTANCE /*hPrevInstance*/,
    LPTSTR /*lpCmdLine*/,
    int nShowCmd)
{
    g_module.WinMain(nShowCmd);
}
</code>```

Client :

```<code>#include <iostream>
#include <sstream>
#include <atlbase.h>
#include <atlcom.h>

#import "C:\\Sources\\misc\\Zebra\\x64\\Debug\\AAA_ZebraServer.exe"

using namespace std;
using namespace ATL;

inline void CheckHR(HRESULT hr, const char* msg)
{
    if (SUCCEEDED(hr))
        return;

    USES_CONVERSION;
    _com_error error(hr);
    std::ostringstream ss;
    ss << msg << "::" << W2A(error.ErrorMessage());
    const auto& str = ss.str();
    throw std::exception(str.c_str());
}

class CComInitializer
{
public:
    CComInitializer()
    {
        CheckHR(CoInitialize(nullptr), "CoInitialize");
    }

    ~CComInitializer()
    {
        CoUninitialize();
    }
};

int main()
{
    try {
        CComInitializer coinit;

        // create binding context object
        CComPtr<IBindCtx> pBindCtx;
        CheckHR(CreateBindCtx(0, &pBindCtx), "CreateBindCtx");

        // Get a pointer to the ROT
        CComPtr<IRunningObjectTable> pRot;
        CheckHR(pBindCtx->GetRunningObjectTable(&pRot), "Get ROT");

        CComPtr<IMoniker> pMoniker;
        CheckHR(CreateClassMoniker(__uuidof(ZebraServer::CZebraServer), &pMoniker), "CreateClassMoniker");

        CComPtr<IUnknown> pUnknown;
        CheckHR(pRot->GetObject(pMoniker, &pUnknown), "pROT->GetObject");

        CComQIPtr<IClassFactory> pClassFactory(pUnknown);
        if (!pClassFactory)
            return 0;

        CComPtr<IDispatch> pDispatch;
        CheckHR(pClassFactory->CreateInstance(
            nullptr,IID_IDispatch,(void**)&pDispatch),
            "pClassFactory->CreateInstance");

        CComDispatchDriver driver(pDispatch);

        CComVariant ret, arg(100);
        CheckHR(driver.Invoke1(L"SetValue", &ret, &arg), "SetValue");
        CheckHR(driver.Invoke0(L"GetValue", &ret), "GetValue");
    }
    catch(...)
    {}
    return 0;
}
</code>```

Body:
I need to call into a 64-bit COM server from a 32-bit client. Both C++.

In order to avoid registration, I use the ROT to publish the class factory.

The IDispatch interface is used from the client to avoid marshaling issues.

I get an error at the first attempt to call a server method:

Error loading type library/DLL

CheckHR(driver.Invoke1(L"SetValue", &ret, &arg), "SetValue");

Why do I need a type library or proxy if I only use IDispatch?

All the code is below.

IDL:

import "unknwn.idl";
[
    object,
    uuid(C3498C72-22F8-477A-B8BF-A6BCE9DE0596),
    dual,
    nonextensible,
    helpstring("IZebraServer Interface"),
    pointer_default(unique)
]
interface IZebraServer : IDispatch
{
    [id(1), helpstring("method GetValue")] HRESULT GetValue([out, retval] int* pValue);
    [id(2), helpstring("method SetValue")] HRESULT SetValue(int value);
};

[
    uuid(1632C43C-7C08-451F-A341-A6486F0CE517),
    version(1.0),
]
library ZebraServer
{
    importlib("stdole32.tlb");
    importlib("stdole2.tlb");

    [
        uuid(C2E745B1-6DA1-4DD4-AF10-5860182B66EF),
        helpstring("CZebraServer Class"),
    ]
    coclass CZebraServer
    {
        [default] interface IZebraServer;
    };
};

Here is the server code:

#include <SDKDDKVer.h>
#include <atlbase.h>
#include <atlcom.h>
#include <atlctl.h>
#include <comdef.h>

#include <sstream>
#include <iostream>

using namespace ATL;

#include "ZebraServer_i.h"

inline void CheckHR(HRESULT hr, const char* msg)
{
    if (SUCCEEDED(hr))
        return;

    USES_CONVERSION;
    _com_error error(hr);
    std::ostringstream ss;
    ss << msg << "::" << W2A(error.ErrorMessage());
    throw std::exception(ss.str().c_str());
}

DWORD RegisterObjectInROT(
    IUnknown* pUnknown)
{
    // create binding context object
    CComPtr<IBindCtx> pBindCtx;
    CheckHR(CreateBindCtx(0, &pBindCtx), "CreateBindCtx");

    // Get a pointer to the ROT
    CComPtr<IRunningObjectTable> pRot;
    CheckHR(pBindCtx->GetRunningObjectTable(&pRot), "Getting ROT");

    // Create a moniker for the object
    CComPtr<IMoniker> pMoniker;
    CheckHR(CreateClassMoniker(CLSID_CZebraServer, &pMoniker), "CreateClassMoniker");
    // Register the object in the ROT with the specified display name
    DWORD dwRegisterCookie{};
    CheckHR(pRot->Register(
        ROTFLAGS_REGISTRATIONKEEPSALIVE,
        pUnknown,
        pMoniker,
        &dwRegisterCookie),
        "Register object");
    return dwRegisterCookie;
}

class ATL_NO_VTABLE CZebraServer :
    public CComObjectRootEx<CComSingleThreadModel>,
    public CComCoClass<CZebraServer, &CLSID_CZebraServer>,
    public IDispatchImpl<IZebraServer, &IID_IZebraServer, &LIBID_ZebraServer, /*wMajor =*/ 1, /*wMinor =*/ 0>
{
public:
    CZebraServer() {}

    DECLARE_NO_REGISTRY()

    BEGIN_COM_MAP(CZebraServer)
        COM_INTERFACE_ENTRY(IZebraServer)
        COM_INTERFACE_ENTRY(IDispatch)
    END_COM_MAP()

    // IZebraServer methods
    STDMETHOD(GetValue)(int* pVal)
    {
        *pVal = m_value;
        return S_OK;
    }

    STDMETHOD(SetValue)(int newVal)
    {
        m_value = newVal;
        return S_OK;
    }

private:
    int m_value = 0;
};

OBJECT_ENTRY_AUTO(__uuidof(CZebraServer), CZebraServer)

class ATL_NO_VTABLE CZebraServerFactory :
    public CComObjectRootEx<CComSingleThreadModel>,
    public CComCoClass<CZebraServerFactory, &CLSID_CZebraServer>,
    public IClassFactory
{
public:
    CZebraServerFactory() {}

    DECLARE_NO_REGISTRY()

    BEGIN_COM_MAP(CZebraServerFactory)
        COM_INTERFACE_ENTRY(IClassFactory)
    END_COM_MAP()

    // IClassFactory methods
    STDMETHOD(CreateInstance)(IUnknown* pUnkOuter, REFIID riid, void** ppv)
    {
        return CComCreator<CComObject<CZebraServer>>::CreateInstance(pUnkOuter, riid, ppv);
    }

    STDMETHOD(LockServer)(BOOL fLock);

};

OBJECT_ENTRY_AUTO(CLSID_CZebraServer, CZebraServerFactory)

CComObject<CZebraServerFactory>* g_pFactoryObject;

class CZebraServerModule : public ATL::CAtlExeModuleT<CZebraServerModule>
{
public:
    DECLARE_NO_REGISTRY()
    DECLARE_LIBID(LIBID_ZebraServer)

    HRESULT PreMessageLoop(int nShowCmd)
    {
        try {

            CheckHR(ATL::CAtlExeModuleT<CZebraServerModule>::PreMessageLoop(nShowCmd),
                "CAtlExeModuleT<CZebraServerModule>::PreMessageLoop");

            std::cout << "Server started" << std::endl;

            // Create an instance of the factory class
            CheckHR(CComObject<CZebraServerFactory>::CreateInstance(&g_pFactoryObject),
                "Create Class Factory Instance");

            // Query for the IUnknown interface
            DWORD dwRegisterCookie = RegisterObjectInROT(g_pFactoryObject);

        }
        catch (std::exception& ex)
        {
            std::cout << ex.what();
            return S_FALSE;
        }
        return S_OK;
    }
};
CZebraServerModule g_module;

HRESULT CZebraServerFactory::LockServer(BOOL fLock)
{
    if (fLock)
        g_module.Lock();
    else
        g_module.Unlock();
    return S_OK;
}

extern "C" int WINAPI _tWinMain(
    HINSTANCE /*hInstance*/,
    HINSTANCE /*hPrevInstance*/,
    LPTSTR /*lpCmdLine*/,
    int nShowCmd)
{
    g_module.WinMain(nShowCmd);
}

Client :

#include <iostream>
#include <sstream>
#include <atlbase.h>
#include <atlcom.h>

#import "C:\\Sources\\misc\\Zebra\\x64\\Debug\\AAA_ZebraServer.exe"

using namespace std;
using namespace ATL;

inline void CheckHR(HRESULT hr, const char* msg)
{
    if (SUCCEEDED(hr))
        return;

    USES_CONVERSION;
    _com_error error(hr);
    std::ostringstream ss;
    ss << msg << "::" << W2A(error.ErrorMessage());
    const auto& str = ss.str();
    throw std::exception(str.c_str());
}

class CComInitializer
{
public:
    CComInitializer()
    {
        CheckHR(CoInitialize(nullptr), "CoInitialize");
    }

    ~CComInitializer()
    {
        CoUninitialize();
    }
};

int main()
{
    try {
        CComInitializer coinit;

        // create binding context object
        CComPtr<IBindCtx> pBindCtx;
        CheckHR(CreateBindCtx(0, &pBindCtx), "CreateBindCtx");

        // Get a pointer to the ROT
        CComPtr<IRunningObjectTable> pRot;
        CheckHR(pBindCtx->GetRunningObjectTable(&pRot), "Get ROT");

        CComPtr<IMoniker> pMoniker;
        CheckHR(CreateClassMoniker(__uuidof(ZebraServer::CZebraServer), &pMoniker), "CreateClassMoniker");

        CComPtr<IUnknown> pUnknown;
        CheckHR(pRot->GetObject(pMoniker, &pUnknown), "pROT->GetObject");

        CComQIPtr<IClassFactory> pClassFactory(pUnknown);
        if (!pClassFactory)
            return 0;

        CComPtr<IDispatch> pDispatch;
        CheckHR(pClassFactory->CreateInstance(
            nullptr,IID_IDispatch,(void**)&pDispatch),
            "pClassFactory->CreateInstance");

        CComDispatchDriver driver(pDispatch);

        CComVariant ret, arg(100);
        CheckHR(driver.Invoke1(L"SetValue", &ret, &arg), "SetValue");
        CheckHR(driver.Invoke0(L"GetValue", &ret), "GetValue");
    }
    catch(...)
    {}
    return 0;
}


问:
Regex in file path to get a file with hash, when you don't know this hash Javascript
Question is hard to understand, but i want ( in my mind ) easy thing to do.
I have 2 folders css and js. Inside them are files like:

app.[genericHash].js

vendor.[genericHash].js

app.[genericHash].css

I need to get this file path, without changing file's code.
Example:

appCss: {
import: './node_modules/project/testPackage/css/app.[hash].css', --> this [hash] with regex or something like that.
filename: './views/css/appWebpackCss.[contenthash].css',
}

hash will be something like af15fb34c mean a-z A-Z 1-9

For claryfication it is Webpack Entry option.
You would ask, why i need it, just change manualy. It is realy bad option, when i have 10 projects like that. Each new version of module will change yts hash. It is strongly needed to do it automaticaly.

Thanks for answers. Another option would be a loop in folder, but this looks expensive. Thanks.


问:
How to query a streambuilder in flutter, By using Google places?
I am already running a category search query on it!! Ultimately I want specific category results with in the Area(Google Place) e.g. German Shepherds With in Indira nagar, Surat).

Cloud Firestore is not Allowing to query fields isEqualTo: Specific field

```<code>Future queryData(String queryString) async {
  return FirebaseFirestore.instance
      .collection('All_Breeds').where('Location', isEqualTo: *****Selected Google Place*****)
      .where('Breeds', isEqualTo: queryString)
      .where("private", isEqualTo: false)
      .get();
</code>```

Body:
I am already running a category search query on it!! Ultimately I want specific category results with in the Area(Google Place) e.g. German Shepherds With in Indira nagar, Surat).

Cloud Firestore is not Allowing to query fields isEqualTo: Specific field

Future queryData(String queryString) async {
  return FirebaseFirestore.instance
      .collection('All_Breeds').where('Location', isEqualTo: *****Selected Google Place*****)
      .where('Breeds', isEqualTo: queryString)
      .where("private", isEqualTo: false)
      .get();


问:
Apache airflow issue while trying to update new script from S3
I've a very specific issue and need your help, appreciate any help in this regard.

I'm using the MWAA (AWS) airflow and the DAG details are picked up from S3.
Recently we found that one of the DAGs was not configured properly, hence we updated the script and uploaded the new version to S3 (with the changes).
After a while, the DAG changed to reflect the new changes, however, few hours later, it switched back to the old DAG. The step status was showing as 'removed'.

We've checked within our team and no one had reverted the changes and the new/changed script is still at the S3 location.

My doubt is if the MWAA has some kind of cache where it store the old script and is falling back to it? If so, any suggestions on how to clear it so the new script can take effect?

Thank you for your time

Newbie MWAA


问:
how to create a local storage for the saved files using kivy python
After deploying it into apk file and testing it. The problem that I encountered was after saving the file name, it crashes and my images don't show up.

I tried using the code from the kivy doc, which is what I'm currently using right now, but I'd like to have my own local storage where the user can save it there and can easily retrieve it.

main.py

```<code>from kivy.core.window import Window
from kivymd.app import MDApp
from kivy.uix.popup import Popup
from kivy.uix.widget import Widget
from kivy.uix.floatlayout import FloatLayout
from kivy.uix.screenmanager import ScreenManager
from kivy.graphics import Color, Ellipse
from kivy.properties import ObjectProperty, OptionProperty
from kivy.lang import Builder
from kivy.factory import Factory
import shutil
import os
from kivymd.uix.screen import MDScreen

class LoadDialog(FloatLayout):
    load = ObjectProperty(None)
    cancel = ObjectProperty(None)

class SaveDialog(FloatLayout):
    save = ObjectProperty(None)
    text_input = ObjectProperty(None)
    cancel = ObjectProperty(None)

class Root(FloatLayout):
    pass

class Cluster(Widget):
    loadfile = ObjectProperty(None)
    text_input = ObjectProperty(None)

    def dismiss_popup(self):
        self._popup.dismiss()

    def show_load(self):
        content = LoadDialog(load=self.load, cancel=self.dismiss_popup)
        self._popup = Popup(title="Load file", content=content,
                            size_hint=(0.9, 0.9))
        self._popup.open()

    def load(self, path, filename):
        with open(os.path.join(path, filename[0])) as stream:
            self.text_input.text = stream.read()

        self.dismiss_popup()

    def clustering(self):
        return

class MyFigure(Widget):
    savefile = ObjectProperty(None)
    text_input = ObjectProperty(None)
    open('save_file.csv', 'w').write("Shot type,X,Y\n")

    def on_touch_down(self, touch):
        self.canvas.add(Color(rgb=(46 / 255.0, 172 / 255.0, 88 / 255.0)))
        d = 10
        self.canvas.add(Ellipse(pos=(touch.x - d / 2, touch.y), size=(d, d)))
        with open('save_file.csv', 'a', newline='') as f:
            print("Made," + str(touch.x) + "," + str(touch.y), file=f)

            if touch.is_double_tap:
                self.canvas.add(Color(rgb=(220 / 255.0, 8 / 255.0, 8 / 255.0)))
                d = 10
                self.canvas.add(
                    Ellipse(pos=(touch.x - d / 2, touch.y), size=(d, d)))
                print("Missed," + str(touch.x) + "," + str(touch.y), file=f)

    def clear_screen(self):
        self.canvas.after.clear()

    def save(self, path, filename):
        with open(os.path.join(MDApp.get_running_app().user_data_dir, filename), 'w') as stream:
            stream.write(self.text_input.text)

        self.dismiss_popup()

class MainScreen(MDScreen):
    pass

class PlotScreen(MDScreen):
    savefile = ObjectProperty(None)
    text_input = ObjectProperty(None)

    def dismiss_popup(self):
        self._popup.dismiss()

    def show_save(self):
        content = SaveDialog(save=self.save, cancel=self.dismiss_popup)
        self._popup = Popup(title="Save file", content=content,
                            size_hint=(0.9, 0.9))
        self._popup.open()

    def load(self, path, filename):
        with open(os.path.join(MDApp.get_running_app().user_data_dir, filename[0])) as stream:
            self.text_input.text = stream.read()

        self.dismiss_popup()

    def save(self, path, filename):
        shutil.move("save_file.csv", os.path.join(MDApp.get_running_app().user_data_dir, filename))

        self.dismiss_popup()

class VisualScreen(MDScreen):
    loadfile = ObjectProperty(None)
    text_input = ObjectProperty(None)

    def dismiss_popup(self):
        self._popup.dismiss()

    def show_load(self):
        content = LoadDialog(load=self.load, cancel=self.dismiss_popup)
        self._popup = Popup(title="Load file", content=content,
                            size_hint=(0.9, 0.9))
        self._popup.open()

    def load(self, path, filename):
        with open(os.path.join(MDApp.get_running_app().user_data_dir, filename[0])) as stream:
            self.text_input.text = stream.read()

        self.dismiss_popup()

class WindowManager(ScreenManager):
    pass

class MyApp(MDApp):
    # _user_data_dir = ""
    media = OptionProperty('M', options=('XS', 'S', 'M', 'L', 'XL'))

    def build(self):
        Window.bind(size=self.update_media)
        Builder.load_file("app.kv")
        return WindowManager()

    def update_media(self, win, size):
        width, height = size
        self.media = (
            'XS' if width < 250 else
            'S' if width < 500 else
            'M' if width < 1000 else
            'L' if width < 1200 else
            'XL'
        )

Factory.register('Root', cls=Root)
Factory.register('LoadDialog', cls=LoadDialog)
Factory.register('SaveDialog', cls=SaveDialog)

if __name__ == "__main__":
    MyApp().run()

</code>```

app.kv

```<code> <WindowManager>:
    MainScreen:
    PlotScreen:
    VisualScreen:

<MainScreen>:
    name: 'main'
    MDBoxLayout:
        orientation: 'vertical'
        height: self.minimum_height
        MDBoxLayout:
            orientation: 'vertical'
            MDLabel:
                text: "logo"
                font_size: 20
                pos_hint: {"center_x": 0.6, "center_y": .1}
            Image:
                source: 'images/bball_dude_new.png'
                allow_stretch: True
                pos_hint: {"center_x": 0.5, "center_y": .1}
                size_hint: 15, 15

        MDBoxLayout:
            MDCard:
                size_hint: .7, 1
                pos_hint: {"center_x": .5, "center_y": .5}
                elevation: 5
                radius: 20
                md_bg_color: 246/255,245/255,241/255

                MDFloatLayout:
                    Widget:
                    Button:
                        background_normal: 'images/dataset.png'
                        background_down: 'images/dataset_clicked.png'
                        size_hint: .15, .35
                        pos_hint: {'x': .25, 'y': .5}
                        on_release: app.root.current = 'plot'
                    MDLabel:
                        color: 144/255,163/255,167/255
                        text: "Data Gathering"
                        pos_hint: {'center_x': 1.02, 'y': .32}
                        font_style: 'Subtitle2'
                    MDLabel:
                        color: 147/255,84/255,48/255
                        text: "Create New Dataset"
                        pos_hint: {'center_x': 1.02, 'y': .25}
                        font_style: 'Button'
                    MDLabel:
                        text: "save the data points into \ncsv file and save scatter \nplot output"
                        color: 144/255,163/255,167/255
                        pos_hint: {'center_x': 1.02, 'y': .13}
                        font_size: 10
                        font_style: 'Caption'
                    Widget:
                    Button:
                        background_normal: 'images/visualization.png'
                        background_down: 'images/visualization_clicked.png'
                        size_hint: .15, .35
                        pos_hint: {'x': .25, 'y': .1}
                        on_release: app.root.current = 'visual'
                    MDLabel:
                        color: 144/255,163/255,167/255
                        text: "Visualization"
                        pos_hint: {'center_x': 1.02, 'top': .93}
                        font_style: 'Subtitle2'
                        text_size: self.width, None
                    MDLabel:
                        color: 147/255,84/255,48/255
                        text: "Get Data Visualization"
                        pos_hint: {'center_x': 1.02, 'top': .85}
                        font_size: 15
                        font_style: 'Button'
                    MDLabel:
                        color: 144/255,163/255,167/255
                        text: "get the data points and start \nclustering to see results \nof a player"
                        font_size: 10
                        font_style: 'Caption'
                        pos_hint: {'center_x': 1.02, 'top': .72}

<PlotScreen>:
    name: 'plot'
    MDBoxLayout:
        orientation: 'vertical'
        pos_hint: {'center_x': .5, 'center_y': .5}
        size: 500, 500

        RelativeLayout:
            size_hint: 1, 1
            MDCard:
                size_hint: None, None
                size: "360dp", "350dp"
                pos_hint: {'center_x': .5, 'center_y': .5}
                elevation: 5
                md_bg_color: 246/255,245/255,241/255
            Image:
                source: 'images/half-court.png'

            MyFigure:
                size_hint: .9, .8

        MDBottomNavigation:
            MDBottomNavigationItem:
                name: "btnSave"
                text: "Save"
                selected_color_background: 0, 0, 1, .4
                icon: "images/save.png"
                on_tab_release: root.show_save()

            MDBottomNavigationItem:
                name: "btnClear"
                text: "Clear Screen"
                icon: "images/clear.png"
                selected_color_background: 0, 0, 1, .4

            MDBottomNavigationItem:
                name: "btnBack"
                text: "Home"
                icon: "images/home.png"
                selected_color_background: 0, 0, 1, .4
                on_tab_release: app.root.current = 'main'

<VisualScreen>:
    name: 'visual'
    MDBoxLayout:
        Cluster:

    MDBottomNavigation:
        MDBottomNavigationItem:
            name: "btnLoad"
            text: "Get Dataset"
            selected_color_background: 0, 0, 1, .4
            icon: "images/analysis.png"
            on_tab_release: root.show_load()

        MDBottomNavigationItem:
            name: "btnSave"
            text: "Save"
            selected_color_background: 0, 0, 1, .4
            icon: "images/save.png"

        MDBottomNavigationItem:
            name: "btnBack"
            text: "Home"
            icon: "images/home.png"
            selected_color_background: 0, 0, 1, .4
            on_tab_release: app.root.current = 'main'

<LoadDialog>:
    BoxLayout:
        size: root.size
        pos: root.pos
        orientation: "vertical"
        FileChooserListView:
            id: filechooser

        BoxLayout:
            size_hint_y: None
            height: 30
            Button:
                text: "Cancel"
                on_release: root.cancel()

            Button:
                text: "Load"
                on_release: root.load(filechooser.path, filechooser.selection)

<SaveDialog>:
    text_input: text_input
    BoxLayout:
        size: root.size
        pos: root.pos
        orientation: "vertical"
        FileChooserListView:
            id: filechooser
            on_selection: text_input.text = self.selection and self.selection[0] or ''

        TextInput:
            id: text_input
            size_hint_y: None
            height: 50
            multiline: False

        BoxLayout:
            size_hint_y: None
            height: 30
            Button:
                text: "Cancel"
                on_release: root.cancel()

            Button:
                text: "Save"
                on_release: root.save(filechooser.path, text_input.text)
</code>```

Body:
After deploying it into apk file and testing it. The problem that I encountered was after saving the file name, it crashes and my images don't show up.

I tried using the code from the kivy doc, which is what I'm currently using right now, but I'd like to have my own local storage where the user can save it there and can easily retrieve it.

main.py

from kivy.core.window import Window
from kivymd.app import MDApp
from kivy.uix.popup import Popup
from kivy.uix.widget import Widget
from kivy.uix.floatlayout import FloatLayout
from kivy.uix.screenmanager import ScreenManager
from kivy.graphics import Color, Ellipse
from kivy.properties import ObjectProperty, OptionProperty
from kivy.lang import Builder
from kivy.factory import Factory
import shutil
import os
from kivymd.uix.screen import MDScreen

class LoadDialog(FloatLayout):
    load = ObjectProperty(None)
    cancel = ObjectProperty(None)

class SaveDialog(FloatLayout):
    save = ObjectProperty(None)
    text_input = ObjectProperty(None)
    cancel = ObjectProperty(None)

class Root(FloatLayout):
    pass

class Cluster(Widget):
    loadfile = ObjectProperty(None)
    text_input = ObjectProperty(None)

    def dismiss_popup(self):
        self._popup.dismiss()

    def show_load(self):
        content = LoadDialog(load=self.load, cancel=self.dismiss_popup)
        self._popup = Popup(title="Load file", content=content,
                            size_hint=(0.9, 0.9))
        self._popup.open()

    def load(self, path, filename):
        with open(os.path.join(path, filename[0])) as stream:
            self.text_input.text = stream.read()

        self.dismiss_popup()

    def clustering(self):
        return

class MyFigure(Widget):
    savefile = ObjectProperty(None)
    text_input = ObjectProperty(None)
    open('save_file.csv', 'w').write("Shot type,X,Y\n")

    def on_touch_down(self, touch):
        self.canvas.add(Color(rgb=(46 / 255.0, 172 / 255.0, 88 / 255.0)))
        d = 10
        self.canvas.add(Ellipse(pos=(touch.x - d / 2, touch.y), size=(d, d)))
        with open('save_file.csv', 'a', newline='') as f:
            print("Made," + str(touch.x) + "," + str(touch.y), file=f)

            if touch.is_double_tap:
                self.canvas.add(Color(rgb=(220 / 255.0, 8 / 255.0, 8 / 255.0)))
                d = 10
                self.canvas.add(
                    Ellipse(pos=(touch.x - d / 2, touch.y), size=(d, d)))
                print("Missed," + str(touch.x) + "," + str(touch.y), file=f)

    def clear_screen(self):
        self.canvas.after.clear()

    def save(self, path, filename):
        with open(os.path.join(MDApp.get_running_app().user_data_dir, filename), 'w') as stream:
            stream.write(self.text_input.text)

        self.dismiss_popup()

class MainScreen(MDScreen):
    pass

class PlotScreen(MDScreen):
    savefile = ObjectProperty(None)
    text_input = ObjectProperty(None)

    def dismiss_popup(self):
        self._popup.dismiss()

    def show_save(self):
        content = SaveDialog(save=self.save, cancel=self.dismiss_popup)
        self._popup = Popup(title="Save file", content=content,
                            size_hint=(0.9, 0.9))
        self._popup.open()

    def load(self, path, filename):
        with open(os.path.join(MDApp.get_running_app().user_data_dir, filename[0])) as stream:
            self.text_input.text = stream.read()

        self.dismiss_popup()

    def save(self, path, filename):
        shutil.move("save_file.csv", os.path.join(MDApp.get_running_app().user_data_dir, filename))

        self.dismiss_popup()

class VisualScreen(MDScreen):
    loadfile = ObjectProperty(None)
    text_input = ObjectProperty(None)

    def dismiss_popup(self):
        self._popup.dismiss()

    def show_load(self):
        content = LoadDialog(load=self.load, cancel=self.dismiss_popup)
        self._popup = Popup(title="Load file", content=content,
                            size_hint=(0.9, 0.9))
        self._popup.open()

    def load(self, path, filename):
        with open(os.path.join(MDApp.get_running_app().user_data_dir, filename[0])) as stream:
            self.text_input.text = stream.read()

        self.dismiss_popup()

class WindowManager(ScreenManager):
    pass

class MyApp(MDApp):
    # _user_data_dir = ""
    media = OptionProperty('M', options=('XS', 'S', 'M', 'L', 'XL'))

    def build(self):
        Window.bind(size=self.update_media)
        Builder.load_file("app.kv")
        return WindowManager()

    def update_media(self, win, size):
        width, height = size
        self.media = (
            'XS' if width < 250 else
            'S' if width < 500 else
            'M' if width < 1000 else
            'L' if width < 1200 else
            'XL'
        )

Factory.register('Root', cls=Root)
Factory.register('LoadDialog', cls=LoadDialog)
Factory.register('SaveDialog', cls=SaveDialog)

if __name__ == "__main__":
    MyApp().run()

app.kv

 <WindowManager>:
    MainScreen:
    PlotScreen:
    VisualScreen:

<MainScreen>:
    name: 'main'
    MDBoxLayout:
        orientation: 'vertical'
        height: self.minimum_height
        MDBoxLayout:
            orientation: 'vertical'
            MDLabel:
                text: "logo"
                font_size: 20
                pos_hint: {"center_x": 0.6, "center_y": .1}
            Image:
                source: 'images/bball_dude_new.png'
                allow_stretch: True
                pos_hint: {"center_x": 0.5, "center_y": .1}
                size_hint: 15, 15

        MDBoxLayout:
            MDCard:
                size_hint: .7, 1
                pos_hint: {"center_x": .5, "center_y": .5}
                elevation: 5
                radius: 20
                md_bg_color: 246/255,245/255,241/255

                MDFloatLayout:
                    Widget:
                    Button:
                        background_normal: 'images/dataset.png'
                        background_down: 'images/dataset_clicked.png'
                        size_hint: .15, .35
                        pos_hint: {'x': .25, 'y': .5}
                        on_release: app.root.current = 'plot'
                    MDLabel:
                        color: 144/255,163/255,167/255
                        text: "Data Gathering"
                        pos_hint: {'center_x': 1.02, 'y': .32}
                        font_style: 'Subtitle2'
                    MDLabel:
                        color: 147/255,84/255,48/255
                        text: "Create New Dataset"
                        pos_hint: {'center_x': 1.02, 'y': .25}
                        font_style: 'Button'
                    MDLabel:
                        text: "save the data points into \ncsv file and save scatter \nplot output"
                        color: 144/255,163/255,167/255
                        pos_hint: {'center_x': 1.02, 'y': .13}
                        font_size: 10
                        font_style: 'Caption'
                    Widget:
                    Button:
                        background_normal: 'images/visualization.png'
                        background_down: 'images/visualization_clicked.png'
                        size_hint: .15, .35
                        pos_hint: {'x': .25, 'y': .1}
                        on_release: app.root.current = 'visual'
                    MDLabel:
                        color: 144/255,163/255,167/255
                        text: "Visualization"
                        pos_hint: {'center_x': 1.02, 'top': .93}
                        font_style: 'Subtitle2'
                        text_size: self.width, None
                    MDLabel:
                        color: 147/255,84/255,48/255
                        text: "Get Data Visualization"
                        pos_hint: {'center_x': 1.02, 'top': .85}
                        font_size: 15
                        font_style: 'Button'
                    MDLabel:
                        color: 144/255,163/255,167/255
                        text: "get the data points and start \nclustering to see results \nof a player"
                        font_size: 10
                        font_style: 'Caption'
                        pos_hint: {'center_x': 1.02, 'top': .72}

<PlotScreen>:
    name: 'plot'
    MDBoxLayout:
        orientation: 'vertical'
        pos_hint: {'center_x': .5, 'center_y': .5}
        size: 500, 500

        RelativeLayout:
            size_hint: 1, 1
            MDCard:
                size_hint: None, None
                size: "360dp", "350dp"
                pos_hint: {'center_x': .5, 'center_y': .5}
                elevation: 5
                md_bg_color: 246/255,245/255,241/255
            Image:
                source: 'images/half-court.png'

            MyFigure:
                size_hint: .9, .8

        MDBottomNavigation:
            MDBottomNavigationItem:
                name: "btnSave"
                text: "Save"
                selected_color_background: 0, 0, 1, .4
                icon: "images/save.png"
                on_tab_release: root.show_save()

            MDBottomNavigationItem:
                name: "btnClear"
                text: "Clear Screen"
                icon: "images/clear.png"
                selected_color_background: 0, 0, 1, .4

            MDBottomNavigationItem:
                name: "btnBack"
                text: "Home"
                icon: "images/home.png"
                selected_color_background: 0, 0, 1, .4
                on_tab_release: app.root.current = 'main'

<VisualScreen>:
    name: 'visual'
    MDBoxLayout:
        Cluster:

    MDBottomNavigation:
        MDBottomNavigationItem:
            name: "btnLoad"
            text: "Get Dataset"
            selected_color_background: 0, 0, 1, .4
            icon: "images/analysis.png"
            on_tab_release: root.show_load()

        MDBottomNavigationItem:
            name: "btnSave"
            text: "Save"
            selected_color_background: 0, 0, 1, .4
            icon: "images/save.png"

        MDBottomNavigationItem:
            name: "btnBack"
            text: "Home"
            icon: "images/home.png"
            selected_color_background: 0, 0, 1, .4
            on_tab_release: app.root.current = 'main'

<LoadDialog>:
    BoxLayout:
        size: root.size
        pos: root.pos
        orientation: "vertical"
        FileChooserListView:
            id: filechooser

        BoxLayout:
            size_hint_y: None
            height: 30
            Button:
                text: "Cancel"
                on_release: root.cancel()

            Button:
                text: "Load"
                on_release: root.load(filechooser.path, filechooser.selection)

<SaveDialog>:
    text_input: text_input
    BoxLayout:
        size: root.size
        pos: root.pos
        orientation: "vertical"
        FileChooserListView:
            id: filechooser
            on_selection: text_input.text = self.selection and self.selection[0] or ''

        TextInput:
            id: text_input
            size_hint_y: None
            height: 50
            multiline: False

        BoxLayout:
            size_hint_y: None
            height: 30
            Button:
                text: "Cancel"
                on_release: root.cancel()

            Button:
                text: "Save"
                on_release: root.save(filechooser.path, text_input.text)


问:
VSCode adds a folding indicator within markdown, how do I get rid of it?
The above shows the ascii diagram, with the extra line with the arrow, I don't want this.

When you click the arrow you end up with the bottom part of the image, with no way apart from ctrl+z to undo it.

Does anyone know how to stop this from happening?

I looked in settings to see if there was any folding options for markdown code blocks, there isn't.


问:
How to login to nhost within a next.js API route?
Started using nhost a few days ago and really enjoying it so far, but I can't figure out how to make properly authorized requests from the server side (which is what API routes are in Next.js, these don't run in the browser).

I'm doing import { NhostClient } from '@nhost/nhost-js' to then create a client, this is from the nhost docs: https://docs.nhost.io/reference/javascript

Doing

```<code>await nhost.auth.signIn({
    email: 'xxxxx@hotmail.com',
     password: 'xxxx',
})
</code>```

works just fine, but I feel it's more appropriate to do:
nhost.functions.setAccessToken(nhostToken)

Which doesn't seem to work even though I'm passing the token that the frontend uses. Thoughts?

Body:
Started using nhost a few days ago and really enjoying it so far, but I can't figure out how to make properly authorized requests from the server side (which is what API routes are in Next.js, these don't run in the browser).

I'm doing import { NhostClient } from '@nhost/nhost-js' to then create a client, this is from the nhost docs: https://docs.nhost.io/reference/javascript

Doing

await nhost.auth.signIn({
    email: 'xxxxx@hotmail.com',
     password: 'xxxx',
})

works just fine, but I feel it's more appropriate to do:
nhost.functions.setAccessToken(nhostToken)

Which doesn't seem to work even though I'm passing the token that the frontend uses. Thoughts?


问:
Do static waits or something like browser.pause(#seconds) (in javascript) work in a headless mode?
I am building tests on Vscode using javascript and having some static waits using browser.pause(#secs). When I run it locally on my machine, it works fine, but when it runs on Jenkins in a headless mode, I get this error:

 Error:  Unable to load spec files quite likely because they rely on `browser` object that is not fully initialised.
`browser` object has only `capabilities` and some flags like `isMobile`.
Helper files that use other `browser` commands have to be moved to `before` hook.
Spec file(s): /var/lib/jenkins/workspace/Testing/Automated-FrontEnd-Integration-Tests/Automation_Tests/EndlessWebdriverAutomationSuite/test/specs/eventsTests.js
Error: Error: Cannot find module '../commonSteps/eventsSteps'
Require stack:
- /var/lib/jenkins/workspace/Testing/Automated-FrontEnd-Integration-Tests/Automation_Tests/EndlessWebdriverAutomationSuite/test/specs/eventsTests.js
    at Module._resolveFilename (node:internal/modules/cjs/loader:1039:15)
    at Module._load (node:internal/modules/cjs/loader:885:27)
    at Module.require (node:internal/modules/cjs/loader:1105:19)
    at require (node:internal/modules/cjs/helpers:103:18)
    at Object.<anonymous> (/var/lib/jenkins/workspace/Testing/Automated-FrontEnd-Integration-Tests/Automation_Tests/EndlessWebdriverAutomationSuite/test/specs/eventsTests.js:6:20)
    at Module._compile (node:internal/modules/cjs/loader:1218:14)
    at Module._extensions..js (node:internal/modules/cjs/loader:1272:10)
    at Module.load (node:internal/modules/cjs/loader:1081:32)
    at Module._load (node:internal/modules/cjs/loader:922:12)
    at ModuleWrap.<anonymous> (node:internal/modules/esm/translators:167:29)
```

What is the problem, and how can it be fixed?

I tried to run it locally on my machine in a headless mode, this error does not show but other issues show.

Body:
I am building tests on Vscode using javascript and having some static waits using browser.pause(#secs). When I run it locally on my machine, it works fine, but when it runs on Jenkins in a headless mode, I get this error:

 Error:  Unable to load spec files quite likely because they rely on `browser` object that is not fully initialised.
`browser` object has only `capabilities` and some flags like `isMobile`.
Helper files that use other `browser` commands have to be moved to `before` hook.
Spec file(s): /var/lib/jenkins/workspace/Testing/Automated-FrontEnd-Integration-Tests/Automation_Tests/EndlessWebdriverAutomationSuite/test/specs/eventsTests.js
Error: Error: Cannot find module '../commonSteps/eventsSteps'
Require stack:
- /var/lib/jenkins/workspace/Testing/Automated-FrontEnd-Integration-Tests/Automation_Tests/EndlessWebdriverAutomationSuite/test/specs/eventsTests.js
    at Module._resolveFilename (node:internal/modules/cjs/loader:1039:15)
    at Module._load (node:internal/modules/cjs/loader:885:27)
    at Module.require (node:internal/modules/cjs/loader:1105:19)
    at require (node:internal/modules/cjs/helpers:103:18)
    at Object.<anonymous> (/var/lib/jenkins/workspace/Testing/Automated-FrontEnd-Integration-Tests/Automation_Tests/EndlessWebdriverAutomationSuite/test/specs/eventsTests.js:6:20)
    at Module._compile (node:internal/modules/cjs/loader:1218:14)
    at Module._extensions..js (node:internal/modules/cjs/loader:1272:10)
    at Module.load (node:internal/modules/cjs/loader:1081:32)
    at Module._load (node:internal/modules/cjs/loader:922:12)
    at ModuleWrap.<anonymous> (node:internal/modules/esm/translators:167:29)

What is the problem, and how can it be fixed?

I tried to run it locally on my machine in a headless mode, this error does not show but other issues show.


问:
one specific route not working having controller in one folder
I am using Codeigniter 3. My controller is placed in the following position.

My URL is like http://localhost/my-pro/index.php/pro/ProCompTest/fulltest/6, and it is giving following error.

All other routes are working those are directly inside controller folder but this specific route is not working. After spending hours, I could not identify what could be the fix for it. Can anyone suggest what could the fix in this case?


问:
data:image/png;base64 not work but I don't know what to replace it with
```<code>def get_image():
    buffer=BytesIO()
    plt.savefig(buffer, format='png')
    buffer.seek(0)
    graph=base64.b64encode(buffer.getvalue()).decode()
    buffer.close()
    return graph

def get_simple_plot(chart_type,*args, **kwargs):
    ....
    if chart_type=='bar plot':
        title='title'
        plt.title(title)
        plt.bar(x,y)
    ...
    graph=get_image()
    return graph

</code>```
```<code>def chart_select_views(request):
    graph=None
    error_message=None;
    df=None;
    ...

    if purpd.shape[0]>0:
      ..
        if request.method=='POST':
            chart_type=request.POST.get('sales')
            datefrom=request.POST.get('date_from')
            dateto=request.POST.get('date_to')

            df2=df.groupby('date' ,as_index=False)['total_price'].agg('sum')

            if chart_type!="":
                if datefrom!= "" and dateto!="":
                    df=df[(df['date']>datefrom) & (df['date']<dateto)]
                    df2=df.groupby('date' ,as_index=False)['total_price'].agg('sum')
                    graph=get_simple_plot(chart_type,x=df2['date'],y=df2['total_price'],data=df)
            ....
    context={
        'product': prpd.to_html,
        'purchase': purpd.to_html,
        'df':df.to_html,
        'error_message':error_message,
        'graph': graph,
     }
    return render(request, 'Product/index.html',context)
</code>```
```<code><img src="data:image/png;base64, {{graph|safe}}">
</code>```

the image is not displayed I tried with another format.

I want to display the data in png format of the data that comes from my database of course in this part I do not want to use js even if it is very easy

Body:
def get_image():
    buffer=BytesIO()
    plt.savefig(buffer, format='png')
    buffer.seek(0)
    graph=base64.b64encode(buffer.getvalue()).decode()
    buffer.close()
    return graph

def get_simple_plot(chart_type,*args, **kwargs):
    ....
    if chart_type=='bar plot':
        title='title'
        plt.title(title)
        plt.bar(x,y)
    ...
    graph=get_image()
    return graph

def chart_select_views(request):
    graph=None
    error_message=None;
    df=None;
    ...

    if purpd.shape[0]>0:
      ..
        if request.method=='POST':
            chart_type=request.POST.get('sales')
            datefrom=request.POST.get('date_from')
            dateto=request.POST.get('date_to')

            df2=df.groupby('date' ,as_index=False)['total_price'].agg('sum')

            if chart_type!="":
                if datefrom!= "" and dateto!="":
                    df=df[(df['date']>datefrom) & (df['date']<dateto)]
                    df2=df.groupby('date' ,as_index=False)['total_price'].agg('sum')
                    graph=get_simple_plot(chart_type,x=df2['date'],y=df2['total_price'],data=df)
            ....
    context={
        'product': prpd.to_html,
        'purchase': purpd.to_html,
        'df':df.to_html,
        'error_message':error_message,
        'graph': graph,
     }
    return render(request, 'Product/index.html',context)

the image is not displayed I tried with another format.

I want to display the data in png format of the data that comes from my database of course in this part I do not want to use js even if it is very easy