问:
Remove all the activites before restarting app.
Does someknow how I get set flags at the main (startup) activity? I want that all activties will be removed of the stack.

This is my code know, but it doenst work:

```<code>/** Called when the activity is first created. */
@Override
public void onCreate(Bundle icicle) {
    super.onCreate(icicle);
Intent mainIntent = new Intent(this, Main.class);

mainIntent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(mainIntent);

setContentView(R.layout.splashscreen);

LoadData();
</code>```

}

I have also tried to use android:clearTaskOnLaunch but that seems not to work...

答:
AndroidManifest.xml update as shown below,

```<code><activity
        android:name="Main" android:label="Post an Ad" android:launchMode="singleTop">
</code>```

Use following code,

```<code>            Intent intent = new Intent(this,Main.class);
            intent.setFlags( Intent.FLAG_ACTIVITY_CLEAR_TOP );
            startActivity( intent );
</code>```

Body:
Does someknow how I get set flags at the main (startup) activity? I want that all activties will be removed of the stack.

This is my code know, but it doenst work:

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle icicle) {
    super.onCreate(icicle);
Intent mainIntent = new Intent(this, Main.class);

mainIntent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(mainIntent);

setContentView(R.layout.splashscreen);

LoadData();

}

I have also tried to use android:clearTaskOnLaunch but that seems not to work...

Body:
AndroidManifest.xml update as shown below,

<activity
        android:name="Main" android:label="Post an Ad" android:launchMode="singleTop">

Use following code,

            Intent intent = new Intent(this,Main.class);
            intent.setFlags( Intent.FLAG_ACTIVITY_CLEAR_TOP );
            startActivity( intent );


来源: stackexchange

问:
Java how to write object to xlsx using SXSSFWorkbook?
I have a class that takes in a List<Person> and writes it out to an .xlsx file.

The person model's fields are:

```<code>String name
String address
Integer age
Double balance
</code>```

The headers are List<String> header = Arrays.asList("Name","Address","Age","Balance").

To create my headers I did:

```<code>SXSSFWorkbook workbook = new SXSSFWorkbook(100);

SXSSFSheet sheet = workbook.createSheet("People's Info");

int rowNum = 0;
Row headerRow = sheet.createRow(rowNum);

int colNum = 0;
for (String header: headers) {
          Cell cell = headerRow.createCell(colNum++);
          cell.setCellValue(header);
}

// want to do a for loop and go through list of list of Person and write their info down
</code>```

How would I go through the List<Person> and dynamically or smartly use their get method or something and correctly. And I am pretty sure I need to be able to set the cell value as a Double or String depending on the object fields type correct?

答:
In your example, you've already done filling cells of one row by loop, for filling person data it will be the same:

```<code>int rowNum = 1;
for (Person person: personList) {
     Row row = sheet.createRow(rowNum++);
     Cell cell0 = row.createCell(0);
     cell0.setCellValue(person.getName());
     Cell cell1 = row.createCell(1);
     cell1.setCellValue(person.getAddress());
     Cell cell2 = row.createCell(2);
     cell2.setCellValue(person.getAge());
     Cell cell3 = row.createCell(3);
     cell3.setCellValue(person.getBallance());
}
</code>```

Cell's type have different types of overriding constructors for double type, String, Integer, and so on.

How you asked, I'll add reflection getting fields of Person.class

```<code>    int rowNum = 1;
    for (Person person: personList) {
         Row row = sheet.createRow(rowNum++);
         Field[] fieldArray = Person.class.getDeclaredFields();
         for(int i = 0; i < fieldArray.length; i++){
           Cell cell = row.createCell(i);
           cell.setCellValue(fieldArray[i].get(person));
         }
    }
</code>```

But you should remember in this solution value of fields will be type Object, for simple cases you can cast this value to String type, but if you want to create a cell with different types you can't do it in the loop,  since for every individual cell you will create an individual cell, how I wrote above.

The main reason why you can't create cells dynamicly is a different types of fields in your DTO class

ContentLicense: CC BY-SA 4.0

Body:
I have a class that takes in a List<Person> and writes it out to an .xlsx file.

The person model's fields are:

String name
String address
Integer age
Double balance

The headers are List<String> header = Arrays.asList("Name","Address","Age","Balance").

To create my headers I did:

SXSSFWorkbook workbook = new SXSSFWorkbook(100);

SXSSFSheet sheet = workbook.createSheet("People's Info");

int rowNum = 0;
Row headerRow = sheet.createRow(rowNum);

int colNum = 0;
for (String header: headers) {
          Cell cell = headerRow.createCell(colNum++);
          cell.setCellValue(header);
}

// want to do a for loop and go through list of list of Person and write their info down

How would I go through the List<Person> and dynamically or smartly use their get method or something and correctly. And I am pretty sure I need to be able to set the cell value as a Double or String depending on the object fields type correct?

Body:
In your example, you've already done filling cells of one row by loop, for filling person data it will be the same:

int rowNum = 1;
for (Person person: personList) {
     Row row = sheet.createRow(rowNum++);
     Cell cell0 = row.createCell(0);
     cell0.setCellValue(person.getName());
     Cell cell1 = row.createCell(1);
     cell1.setCellValue(person.getAddress());
     Cell cell2 = row.createCell(2);
     cell2.setCellValue(person.getAge());
     Cell cell3 = row.createCell(3);
     cell3.setCellValue(person.getBallance());
}

Cell's type have different types of overriding constructors for double type, String, Integer, and so on.

How you asked, I'll add reflection getting fields of Person.class

    int rowNum = 1;
    for (Person person: personList) {
         Row row = sheet.createRow(rowNum++);
         Field[] fieldArray = Person.class.getDeclaredFields();
         for(int i = 0; i < fieldArray.length; i++){
           Cell cell = row.createCell(i);
           cell.setCellValue(fieldArray[i].get(person));
         }
    }

But you should remember in this solution value of fields will be type Object, for simple cases you can cast this value to String type, but if you want to create a cell with different types you can't do it in the loop,  since for every individual cell you will create an individual cell, how I wrote above.

The main reason why you can't create cells dynamicly is a different types of fields in your DTO class


问:
Selenium chrome driver unable to locate input element
Getting error when trying to locate the input element. Tried locating by xpath and className.

HTML of the Input Element:

```<code><input data-v-9182d0dc="" type="text" id="filterElement" data-cy="v-search-input" autocomplete="off" placeholder="Type a name or a number" class="padding-right-30 round">
</code>```

Xpath for this element:

```<code>//*[@id="filterElement"]
</code>```

Full Xpath for this element: /html/body/div[2]/div[5]/div/div[2]/div/div[1]/div/div/div[2]/input

Statement to find the element

```<code>temp=driver.find_element_by_xpath('/html/body/div[2]/div[5]/div/div[2]/div/div[1]/div/div/div[2]/input')
</code>```

Getting below error message:

```<code>selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"xpath","selector":"/html/body/div[2]/div[5]/div/div[2]/div/div[1]/div/div/div[2]/input"}
</code>```

Update: The element seems to be inside an iframe. Not sure how this comes into play when selecting an element

答: I had to switch the iframe. The input element was located inside another iframe.</p>

Body:
Getting error when trying to locate the input element. Tried locating by xpath and className.

HTML of the Input Element:

<input data-v-9182d0dc="" type="text" id="filterElement" data-cy="v-search-input" autocomplete="off" placeholder="Type a name or a number" class="padding-right-30 round">

Xpath for this element:

//*[@id="filterElement"]

Full Xpath for this element: /html/body/div[2]/div[5]/div/div[2]/div/div[1]/div/div/div[2]/input

Statement to find the element

temp=driver.find_element_by_xpath('/html/body/div[2]/div[5]/div/div[2]/div/div[1]/div/div/div[2]/input')

Getting below error message:

selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"xpath","selector":"/html/body/div[2]/div[5]/div/div[2]/div/div[1]/div/div/div[2]/input"}

Update: The element seems to be inside an iframe. Not sure how this comes into play when selecting an element


问:
How to specify jackson to only use fields - preferably globally
Default jackon behaviour seems to use both properties (getters and setters) and fields to serialize and deserialize to json.

I would like to use the fields as the canonical source of serialization config and thus don't want jackson to look at properties at all.

I can do this on an individual class basis with the annotation:

```<code> @JsonAutoDetect(fieldVisibility = Visibility.ANY, getterVisibility = Visibility.NONE, setterVisibility = Visibility.NONE)
</code>```

But I don't want to have to put this on every single class...

Is it possible to configure this globally? Like add some to the Object Mapper?

答:
You can configure individual ObjectMappers like this:

```<code>ObjectMapper mapper  = new ObjectMapper();
mapper.setVisibility(mapper.getSerializationConfig().getDefaultVisibilityChecker()
                .withFieldVisibility(JsonAutoDetect.Visibility.ANY)
                .withGetterVisibility(JsonAutoDetect.Visibility.NONE)
                .withSetterVisibility(JsonAutoDetect.Visibility.NONE)
                .withCreatorVisibility(JsonAutoDetect.Visibility.NONE));
</code>```

If you want it set globally, I usually access a configured mapper through a wrapper class.

Body:
Default jackon behaviour seems to use both properties (getters and setters) and fields to serialize and deserialize to json.

I would like to use the fields as the canonical source of serialization config and thus don't want jackson to look at properties at all.

I can do this on an individual class basis with the annotation:

 @JsonAutoDetect(fieldVisibility = Visibility.ANY, getterVisibility = Visibility.NONE, setterVisibility = Visibility.NONE)

But I don't want to have to put this on every single class...

Is it possible to configure this globally? Like add some to the Object Mapper?

Body:
You can configure individual ObjectMappers like this:

ObjectMapper mapper  = new ObjectMapper();
mapper.setVisibility(mapper.getSerializationConfig().getDefaultVisibilityChecker()
                .withFieldVisibility(JsonAutoDetect.Visibility.ANY)
                .withGetterVisibility(JsonAutoDetect.Visibility.NONE)
                .withSetterVisibility(JsonAutoDetect.Visibility.NONE)
                .withCreatorVisibility(JsonAutoDetect.Visibility.NONE));

If you want it set globally, I usually access a configured mapper through a wrapper class.


问:
How to remove a sub string pattern from a json string in vim?
```<code>json_str = {"type":"0","num":"1","processtime_ms":"14","model":"label"}
</code>```

I have a lot of json string like this, and I want to remove this part from the string in vim:

```<code>"processtime_ms":"14",
</code>```

I know how to remove a full line when matching a pattern, but how to remove the substring?

答:
```<code>:1,$s/"processtime_ms":"14",//g
</code>```

will remove the pattern from every line in the file

Body:
json_str = {"type":"0","num":"1","processtime_ms":"14","model":"label"}

I have a lot of json string like this, and I want to remove this part from the string in vim:

"processtime_ms":"14",

I know how to remove a full line when matching a pattern, but how to remove the substring?

Body:
:1,$s/"processtime_ms":"14",//g

will remove the pattern from every line in the file


问:
Setting Up Windows Authentication for Apache
To begin, I've been searching the internet for about an hour trying to find out how to do this with no success - therefore I'm writing this question.

I have an intranet site that requires to access the users Windows Username (not the server running Apache, but a user accessing the intranet site).

I have installed adLDAP and have it working where a user can log in by that, to check the group that the user is in. But, to have my site more secure I'd rather it access the Windows username.

I've saw that there's an apache module called mod_auth_sspi but I could not find how to install it or even implement (use) it in my code.

I am using Apache v2.4, PHP 5.6.8 on Windows Server 2008.

答:
Ok this is a much more detailed explanation I have which shows an Apache
server using LDAP authentication to Windows Domain Controller. And is using
NGINX to proxy requests to Apache... which manages authentication to IIS...
quite a complicated approach but NGINX is a much faster web proxy than Apache
in general.... these instructions are much more specific and likely accurate. Windows Server manages LDAP requests to Active Directory on Port 389 by default
this can be changed but at your own risk. Not many companies open 389 across public boundaries so you do need a web proxy usually.

note this configuration shows what you put above is not sufficient as I expected....

https://techexpert.tips/nginx/nginx-ldap-authentication-active-directory/

These are the additional Apache flags this team has identified which from experience looks accurate...

AuthBasicProvider ldap
Auth LDAPURL "ldap://10.X.X.X/CN=Users,DC=tech,DC=local?sAMAccountName?sub(objectClass=*)"
AuthLDAPBindDN "bind@tech.local"
AuthLDAPBindPassword kamisama123

ContentLicense: CC BY-SA 3.0


问:
Issues with threading in c#
I want this method to be threaded out so I can set a timer and not wait for it to finish. It's a call to a service.

```<code>private static void callValueEng(ValueEngineService.Contracts.ValueEngServiceParams param)
{
    using (WCFServiceChannelFactory<IValueEngineService> client =
              new WCFServiceChannelFactory<IValueEngineService>(
                  Repository.Instance.GetWCFServiceUri(typeof(IValueEngineService))))
    {
        client.Call(x => x.ValueManyTransactionsWithOldEngines(translatedParams));
    }
}
</code>```

I tried threading it out like this:

```<code>System.Threading.Thread newThread;
//RestartValueEngineService();

List<TransactionInfo> currentIdsForValuation = ((counter + 7000) <= allIds.Count)
                              ? allIds.GetRange(counter, 7000)
                              : allIds.GetRange(counter, allIds.Count - counter);
translatedParams.tranquoteIds = currentIdsForValuation;

// thread this out
newThread = new System.Threading.Thread(callValueEng(translatedParams));
</code>```

But it's saying 'the best overloaded match has some invalid arguments.' What am I doing wrong?

答:
try:

```<code>var invoker = new Action<ValueEngineService.Contracts.ValueEngServiceParams>(callValueEng);
invoker.BeginInvoke(translatedParams, null, null);
</code>```

this will asynchronously call your method.

Title: Issues with threading in c#

Body:
I want this method to be threaded out so I can set a timer and not wait for it to finish. It's a call to a service.

private static void callValueEng(ValueEngineService.Contracts.ValueEngServiceParams param)
{
    using (WCFServiceChannelFactory<IValueEngineService> client =
              new WCFServiceChannelFactory<IValueEngineService>(
                  Repository.Instance.GetWCFServiceUri(typeof(IValueEngineService))))
    {
        client.Call(x => x.ValueManyTransactionsWithOldEngines(translatedParams));
    }
}

I tried threading it out like this:

System.Threading.Thread newThread;
//RestartValueEngineService();

List<TransactionInfo> currentIdsForValuation = ((counter + 7000) <= allIds.Count)
                              ? allIds.GetRange(counter, 7000)
                              : allIds.GetRange(counter, allIds.Count - counter);
translatedParams.tranquoteIds = currentIdsForValuation;

// thread this out
newThread = new System.Threading.Thread(callValueEng(translatedParams));

But it's saying 'the best overloaded match has some invalid arguments.' What am I doing wrong?

Body:
try:

var invoker = new Action<ValueEngineService.Contracts.ValueEngServiceParams>(callValueEng);
invoker.BeginInvoke(translatedParams, null, null);

this will asynchronously call your method.


问:
Python telling me thread assigned outside function isn't assigned
I made this program to have a timed input:

```<code>import time
from threading import Thread

def get_answer():
    answer = input ("ANSWER THE QUESTION!!!")

def runtime():
    time.sleep(1)
    timer = timer-1
    print (timer)
    if timer == 0:
        thread1.cancel()
        print ("hi")

timer = 5

# create two new threads
thread1 = Thread(target=get_answer)
thread2 = Thread(target=runtime)

# start the threads
thread1.start()
thread2.start()

# wait for the threads to complete
thread1.join()
thread2.join()
</code>```

When I run it though, I get this error:

```<code>Exception in thread Thread-2 (runtime):
Traceback (most recent call last):
  File "C:\Users\user1\AppData\Local\Programs\Python\Python310\lib\threading.py", line 1009, in _bootstrap_inner
    self.run()
  File "C:\Users\user1\AppData\Local\Programs\Python\Python310\lib\threading.py", line 946, in run
    self._target(*self._args, **self._kwargs)
  File "c:\Users\user1\Desktop\import time.py", line 9, in runtime
    timer = timer-1
UnboundLocalError: local variable 'timer' referenced before assignment
</code>```

How can I fix this? I set the variable timer before the thread runs, so why isn't it assigned already?

答:
Thanks @Marya

Made the variable global, and put the subtracting part in a while loop.

```<code>import time
from threading import Thread

global timer
timer = 5

def get_answer():
    answer = input ("ANSWER THE QUESTION!!!")

def runtime():
    global timer
    while True:
        time.sleep(1)
        timer = timer-1
        print (timer)
        if timer == 0:
            thread1.kill()
            thread1.join|()
            print ("hi")
            break

# create two new threads
thread1 = Thread(target=get_answer)
thread2 = Thread(target=runtime)

# start the threads
thread1.start()
thread2.start()

# wait for the threads to complete
thread1.join()
thread2.join()
</code>```

Body:
I made this program to have a timed input:

import time
from threading import Thread

def get_answer():
    answer = input ("ANSWER THE QUESTION!!!")

def runtime():
    time.sleep(1)
    timer = timer-1
    print (timer)
    if timer == 0:
        thread1.cancel()
        print ("hi")

timer = 5

# create two new threads
thread1 = Thread(target=get_answer)
thread2 = Thread(target=runtime)

# start the threads
thread1.start()
thread2.start()

# wait for the threads to complete
thread1.join()
thread2.join()

When I run it though, I get this error:

Exception in thread Thread-2 (runtime):
Traceback (most recent call last):
  File "C:\Users\user1\AppData\Local\Programs\Python\Python310\lib\threading.py", line 1009, in _bootstrap_inner
    self.run()
  File "C:\Users\user1\AppData\Local\Programs\Python\Python310\lib\threading.py", line 946, in run
    self._target(*self._args, **self._kwargs)
  File "c:\Users\user1\Desktop\import time.py", line 9, in runtime
    timer = timer-1
UnboundLocalError: local variable 'timer' referenced before assignment

How can I fix this? I set the variable timer before the thread runs, so why isn't it assigned already?

Body:
Thanks @Marya

Made the variable global, and put the subtracting part in a while loop.

import time
from threading import Thread

global timer
timer = 5

def get_answer():
    answer = input ("ANSWER THE QUESTION!!!")

def runtime():
    global timer
    while True:
        time.sleep(1)
        timer = timer-1
        print (timer)
        if timer == 0:
            thread1.kill()
            thread1.join|()
            print ("hi")
            break

# create two new threads
thread1 = Thread(target=get_answer)
thread2 = Thread(target=runtime)

# start the threads
thread1.start()
thread2.start()

# wait for the threads to complete
thread1.join()
thread2.join()


问:
How to verify that an API Request is coming from my Javascript on my Site?
I have some JS on my website which requests Data from my own PHP API and the API request data from external APIs (Google, YT etc.)

How can my own PHP API can verify, that the request is from MY Javascript and not from someone else?

答:
If all you want to do is to simply prevent people from accessing your API through JS on other sites you can just set the CORS header Access-Control-Allow-Origin to your own domain.

```<code>header("Access-Control-Allow-Origin: your.domain.here");
</code>```

Note that this doesn't mean people can't access your API through direct calls using software like Postman, python scripts etc.

If, for example, you want only yourself and/or specific users to be able to access the API you could look into php session management. This way you can create accounts which are allowed to access specific data on your API.

You could also use API keys to allow users to directly communicate with your API if needed.

Body:
If all you want to do is to simply prevent people from accessing your API through JS on other sites you can just set the CORS header Access-Control-Allow-Origin to your own domain.

header("Access-Control-Allow-Origin: your.domain.here");

Note that this doesn't mean people can't access your API through direct calls using software like Postman, python scripts etc.

If, for example, you want only yourself and/or specific users to be able to access the API you could look into php session management. This way you can create accounts which are allowed to access specific data on your API.

You could also use API keys to allow users to directly communicate with your API if needed.


问:
parsing XML configuration file using Etree in python
Please help me parse a configuration file of the below prototype using lxml etree. I tried with for event, element with tostring.  Unfortunately I don't need the text, but the XML between

```<code><template name>
   <config>
 </template>
</code>```

for a given attribute.

I started with this code, but get a key error while searching for the attribute since it scans from start

```<code>config_tree = etree.iterparse(token_template_file)
for event, element in config_tree:

    if element.attrib['name']=="ad auth":
        print ("attrib reached. get XML before child ends")
</code>```

Since I am a newbie to XML and python, I am not sure how to go about it. Here is the config file:

```<code><Templates>

  <template name="config1">

    <request>

      <password>pass</password>

      <userName>username</userName>

      <appID>someapp</appID>

    </request>

  </template>

  <template name="config2">

    <request>

      <password>pass1</password>

      <userName>username1</userName>

      <appID>someapp</appID>

    </request>

  </template>

</Templates>
</code>```

Thanks in advance!

Expected Output:

Say the user requests the config2- then the output should look like:

```<code>   <request>

      <password>pass1</password>

      <userName>username1</userName>

      <appID>someapp</appID>

    </request>
</code>```

(I send this XML using httplib2 to a server for initial authentication)

FINAL CODE:

thanks to FC and Constantnius. Here is the final code:

```<code>    config_tree = etree.parse(token_template_file)
    for template in config_tree.iterfind("template"):

        if template.get("name") == "config2":
            element = etree.tostring(template.find("request"))

            print (template.get("name"))
            print (element)
</code>```

output:

```<code>     config2

    <request>

         <password>pass1</password>

          <userName>username1</userName>

          <appID>someapp</appID>

    </request>
</code>```

答:
You could try using get('name', default='') instead of ['name']

To get the text in the tag use .text

Body:
Please help me parse a configuration file of the below prototype using lxml etree. I tried with for event, element with tostring.  Unfortunately I don't need the text, but the XML between

<template name>
   <config>
 </template>

for a given attribute.

I started with this code, but get a key error while searching for the attribute since it scans from start

config_tree = etree.iterparse(token_template_file)
for event, element in config_tree:

    if element.attrib['name']=="ad auth":
        print ("attrib reached. get XML before child ends")

Since I am a newbie to XML and python, I am not sure how to go about it. Here is the config file:

<Templates>

  <template name="config1">

    <request>

      <password>pass</password>

      <userName>username</userName>

      <appID>someapp</appID>

    </request>

  </template>

  <template name="config2">

    <request>

      <password>pass1</password>

      <userName>username1</userName>

      <appID>someapp</appID>

    </request>

  </template>

</Templates>

Thanks in advance!

Expected Output:

Say the user requests the config2- then the output should look like:

   <request>

      <password>pass1</password>

      <userName>username1</userName>

      <appID>someapp</appID>

    </request>

(I send this XML using httplib2 to a server for initial authentication)

FINAL CODE:

thanks to FC and Constantnius. Here is the final code:

    config_tree = etree.parse(token_template_file)
    for template in config_tree.iterfind("template"):

        if template.get("name") == "config2":
            element = etree.tostring(template.find("request"))

            print (template.get("name"))
            print (element)

output:

     config2

    <request>

         <password>pass1</password>

          <userName>username1</userName>

          <appID>someapp</appID>

    </request>


问:
Modern best approach to using Django ORM with async?
The world of async Django is changing rapidly, and it's hard to tell what is current and what is dated.

So, what is the current best approach to using the Django ORM (or, possibly, another ORM) for the best/smoothest async capability?  What do people use successfully today?

Lots of references out there, including:

https://forum.djangoproject.com/t/asynchronous-orm/5925/70

https://channels.readthedocs.io/en/latest/topics/databases.html

One problem I have is that no matter what I try, I run into the "django.db.utils.OperationalError: database "test_djangoasyncproj" is being accessed by other users" issue.

答:
i think u should follow documentation
https://docs.djangoproject.com/en/4.0/topics/async/#asgiref.sync.sync_to_async
https://docs.djangoproject.com/en/4.0/topics/async/#async-views

```<code>from asgiref.sync import sync_to_async

results = await sync_to_async(Blog.objects.get, thread_sensitive=True)(pk=123)
</code>```

or

```<code>from asgiref.sync import sync_to_async

def _get_blog(pk):
    return Blog.objects.select_related('author').get(pk=pk)

get_blog = sync_to_async(_get_blog, thread_sensitive=True)
</code>```

Body:
i think u should follow documentation
https://docs.djangoproject.com/en/4.0/topics/async/#asgiref.sync.sync_to_async
https://docs.djangoproject.com/en/4.0/topics/async/#async-views

from asgiref.sync import sync_to_async

results = await sync_to_async(Blog.objects.get, thread_sensitive=True)(pk=123)

or

from asgiref.sync import sync_to_async

def _get_blog(pk):
    return Blog.objects.select_related('author').get(pk=pk)

get_blog = sync_to_async(_get_blog, thread_sensitive=True)


问:
Issues with fill a screen with DIV
I need to make a screen with 3 divs. In div one i will show a video so it needs to be in 16:9 ratio. Then i have two divs left. At the right i need a div that will be fill the width left from the video div. But in needs to be a square div. And below the video div i want another div that use that space.

I was thinking of two columns, two rows and combined column at the right. But that is table wise. How can i do this with a div.

What i have in HTML now is:

```<code> <div id="mainWrapper">
        <div id="streamDiv"><iframe width="90%" height="90%"  src="https://www.youtube.com/embed/SQzhybzvRaQ" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe></div>
        <div id="chatDiv">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus iaculis libero finibus mi finibus, in consectetur lorem finibus. Phasellus consequat at ipsum a efficitur. Nulla facilisi. Sed tempus mi vel mauris efficitur rhoncus. Maecenas tristique neque sit amet fringilla pharetra. Sed porta nec sem quis viverra. Curabitur at bibendum mauris, eget condimentum diam. Phasellus nunc nisi, mollis sed mauris a, maximus pharetra lacus. Vestibulum quis nibh ut lacus feugiat placerat at sed dui. Mauris eget vehicula urna. Fusce in dolor quis sapien rutrum porta sed sit amet elit. Aliquam feugiat nisl nec augue feugiat maximus.</div>
        <div id="pollDiv">poll</div>
</div>
</code>```

and in CSS i have:

```<code>#mainWrapper {
    height: auto;
    margin-bottom: 30px;
}
#streamDiv {
    width: 1000px;
    background-color: aqua;
  height: 563px;
  display: block;
  float: left;
  position: relative;

}
#chatDiv {
    left: auto;
    width: 100% auto;
    height: 100% ;
    margin-left: 10px;
    margin-right: 10px;
    flex-grow: 1;
    margin-top: auto;
    background-color: #ff3333;
    height: 1000px auto;
    display: block;
}
#pollDiv {
    clear: both;
}
</code>```

but that will give me this:

enter image description here
but i want:
enter image description here

答:
This here seems to get the desired result that you want. I changed the wrapper to be a grid system. You can read more about it here CSS: Grid Layout

#mainWrapper {
    height: auto;
    margin-bottom: 30px;
    display: grid;
    grid-template-columns: auto auto;
}
#streamDiv {
    width: 1000px;
    background-color: aqua;
    height: 563px;
    display: block;
}
#chatDiv {
    left: auto;
    width: 100% auto;
    height: 100% ;
    margin-left: 10px;
    margin-right: 10px;
    margin-top: auto;
    background-color: #ff3333;
    height: 1000px auto;
    display: block;
}

#pollDiv {
    clear: both;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code> <div id="mainWrapper">
        <div id="streamDiv"><iframe width="90%" height="90%"  src="https://www.youtube.com/embed/SQzhybzvRaQ" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe></div>
        <div id="chatDiv">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus iaculis libero finibus mi finibus, in consectetur lorem finibus. Phasellus consequat at ipsum a efficitur. Nulla facilisi. Sed tempus mi vel mauris efficitur rhoncus. Maecenas tristique neque sit amet fringilla pharetra. Sed porta nec sem quis viverra. Curabitur at bibendum mauris, eget condimentum diam. Phasellus nunc nisi, mollis sed mauris a, maximus pharetra lacus. Vestibulum quis nibh ut lacus feugiat placerat at sed dui. Mauris eget vehicula urna. Fusce in dolor quis sapien rutrum porta sed sit amet elit. Aliquam feugiat nisl nec augue feugiat maximus.</div>
        <div id="pollDiv">poll</div>
</div></code>```

Title: Issues with fill a screen with DIV

Body:
I need to make a screen with 3 divs. In div one i will show a video so it needs to be in 16:9 ratio. Then i have two divs left. At the right i need a div that will be fill the width left from the video div. But in needs to be a square div. And below the video div i want another div that use that space.

I was thinking of two columns, two rows and combined column at the right. But that is table wise. How can i do this with a div.

What i have in HTML now is:

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus iaculis libero finibus mi finibus, in consectetur lorem finibus. Phasellus consequat at ipsum a efficitur. Nulla facilisi. Sed tempus mi vel mauris efficitur rhoncus. Maecenas tristique neque sit amet fringilla pharetra. Sed porta nec sem quis viverra. Curabitur at bibendum mauris, eget condimentum diam. Phasellus nunc nisi, mollis sed mauris a, maximus pharetra lacus. Vestibulum quis nibh ut lacus feugiat placerat at sed dui. Mauris eget vehicula urna. Fusce in dolor quis sapien rutrum porta sed sit amet elit. Aliquam feugiat nisl nec augue feugiat maximus.

poll

and in CSS i have:

#mainWrapper {
    height: auto;
    margin-bottom: 30px;
}
#streamDiv {
    width: 1000px;
    background-color: aqua;
  height: 563px;
  display: block;
  float: left;
  position: relative;

}
#chatDiv {
    left: auto;
    width: 100% auto;
    height: 100% ;
    margin-left: 10px;
    margin-right: 10px;
    flex-grow: 1;
    margin-top: auto;
    background-color: #ff3333;
    height: 1000px auto;
    display: block;
}
#pollDiv {
    clear: both;
}

but that will give me this:

enter image description here
but i want:
enter image description here

Body:
This here seems to get the desired result that you want. I changed the wrapper to be a grid system. You can read more about it here CSS: Grid Layout

#mainWrapper {
    height: auto;
    margin-bottom: 30px;
    display: grid;
    grid-template-columns: auto auto;
}
#streamDiv {
    width: 1000px;
    background-color: aqua;
    height: 563px;
    display: block;
}
#chatDiv {
    left: auto;
    width: 100% auto;
    height: 100% ;
    margin-left: 10px;
    margin-right: 10px;
    margin-top: auto;
    background-color: #ff3333;
    height: 1000px auto;
    display: block;
}

#pollDiv {
    clear: both;
}

 <div id="mainWrapper">
        <div id="streamDiv"><iframe width="90%" height="90%"  src="https://www.youtube.com/embed/SQzhybzvRaQ" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe></div>
        <div id="chatDiv">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus iaculis libero finibus mi finibus, in consectetur lorem finibus. Phasellus consequat at ipsum a efficitur. Nulla facilisi. Sed tempus mi vel mauris efficitur rhoncus. Maecenas tristique neque sit amet fringilla pharetra. Sed porta nec sem quis viverra. Curabitur at bibendum mauris, eget condimentum diam. Phasellus nunc nisi, mollis sed mauris a, maximus pharetra lacus. Vestibulum quis nibh ut lacus feugiat placerat at sed dui. Mauris eget vehicula urna. Fusce in dolor quis sapien rutrum porta sed sit amet elit. Aliquam feugiat nisl nec augue feugiat maximus.</div>
        <div id="pollDiv">poll</div>
</div>


问:
Clicking a button by selenium
I'm trying to click that button, I've tried several ways and I couldn't.</p>
```<code><div class="item" data-id="rota_grupo">
   <i class="fal fa-users">
   </i>
</div>
</code>```

答:
To locate the clickable element you need to induce WebDriverWait for the element_to_be_clickable() and you can use either of the following locator strategies:

Using CSS_SELECTOR:

```<code>WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "div.item[data-id='rota_grupo'] > i.fal.fa-users"))).click()
</code>```

Using XPATH:

```<code>WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//div[@class='item' and @data-id='rota_grupo']/i[@class='fal fa-users']"))).click()
</code>```

Note : You have to add the following imports :

```<code>from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
</code>```

Title: Clicking a button by selenium

Body:
To locate the clickable element you need to induce WebDriverWait for the element_to_be_clickable() and you can use either of the following locator strategies:

Using CSS_SELECTOR:

WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "div.item[data-id='rota_grupo'] > i.fal.fa-users"))).click()

Using XPATH:

WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//div[@class='item' and @data-id='rota_grupo']/i[@class='fal fa-users']"))).click()

Note : You have to add the following imports :

from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC


问:
Prevent Popup from QZ Tray on online server
I am writing script for woocommerce offline POS ordering where QZ Tray can help for print from local PC.

I have manage to integrate it but dialog box comes says,

Wants to connect QZ Tray Untrusted webiste

To avoid that i have done some research.

What i understood is there is a private key required like SSL.
as explained here, https://github.com/qzind/tray/blob/2.0/assets/signing/sign-message.js

i tried the same as above but it wont work on local host, may be due to fact that, as i didn't created SSL yet.

But can it be achieved for server SSL? i mean if i write my domain private key as below and pass it to function qz.security.setSignaturePromise

```<code> var privateKey = "-----BEGIN PRIVATE KEY-----\n" +
   "MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQC0z9FeMynsC8+u\n" +
   "dvX+LciZxnh5uRj4C9S6tNeeAlIGCfQYk0zUcNFCoCkTknNQd/YEiawDLNbxBqut\n" +
   "bMDZ1aarys1a0lYmUeVLCIqvzBkPJTSQsCopQQ9V8WuT252zzNzs68dVGNdCJd5J\n" +
   "NRQykpwexmnjPPv0mvj7i8XgG379TyW6P+WWV5okeUkXJ9eJS2ouDYdR2SM9BoVW\n" +
   "+FgxDu6BmXhozW5EfsnajFp7HL8kQClI0QOc79yuKl3492rH6bzFsFn2lfwWy9ic\n" +
   "7cP8EpCTeFp1tFaD+vxBhPZkeTQ1HKx6hQ5zeHIB5ySJJZ7af2W8r4eTGYzbdRW2\n" +
   "4DDHCPhZAgMBAAECggEATvofR3gtrY8TLe+ET3wMDS8l3HU/NMlmKA9pxvjYfw7F\n" +
   "8h4VBw4oOWPfzU7A07syWJUR72kckbcKMfw42G18GbnBrRQG0UIgV3/ppBQQNg9Y\n" +
   "QILSR6bFXhLPnIvm/GxVa58pOEBbdec4it2Gbvie/MpJ4hn3K8atTqKk0djwxQ+b\n" +
   "QNBWtVgTkyIqMpUTFDi5ECiVXaGWZ5AOVK2TzlLRNQ5Y7US8lmGxVWzt0GONjXSE\n" +
   "iO/eBk8A7wI3zknMx5o1uZa/hFCPQH33uKeuqU5rmphi3zS0BY7iGY9EoKu/o+BO\n" +
   "HPwLQJ3wCDA3O9APZ3gmmbHFPMFPr/mVGeAeGP/BAQKBgQDaPELRriUaanWrZpgT\n" +
   "VnKKrRSqPED3anAVgmDfzTQwuR/3oD506F3AMBzloAo3y9BXmDfe8qLn6kgdZQKy\n" +
   "SFNLz888at96oi+2mEKPpvssqiwE6F3OtEM6yv4DP9KJHaHmXaWv+/sjwjzpFNjs\n" +
   "wGThBxFvrTWRJqBYsM1XNJJ2EQKBgQDUGbTSwHKqRCYWhQ1GPCZKE98l5UtMKvUb\n" +
   "hyWWOXoyoeYbJEMfG1ynX4JeXIkl6YtBjYCqszv9PjHa1rowTZaAPJ0V70zyhTcF\n" +
   "t581ii9LpiejIGrELHvJnW87QmjjStkjwGIqgKLp7Qe6CDjHI9HP1NM0uav/IQLW\n" +
   "pB6wyEz1yQKBgQCuxPut+Ax2rzM05KB9PAnWzO1zt3U/rtm8IAF8uVVGf7r+EDJ0\n" +
   "ZXJO6zj5G8WTEYHz5E86GI4ltBW0lKQoKouqdu27sMrv5trXG/CSImOcTVubQot9\n" +
   "chc1CkOKTp5IeJajafO6j817wZ4N+0gNsbYYEBUCnm/7ojdfT5ficpOoQQKBgQDB\n" +
   "PgKPmaNfGeQR1Ht5qEfCakR/RF/ML79Nq15FdmytQPBjfjBhYQ6Tt+MRkgGqtxOX\n" +
   "UBMQc2iOnGHT3puYcrhScec1GufidhjhbqDxqMrag7HNYDWmMlk+IeA7/4+Mtp8L\n" +
   "gbZuvvCvbLQDfIYueaYpUuBzQ08/jZYGdVU4/+WOcQKBgAGUN0kIB6EM1K/iZ0TN\n" +
   "jlt8P5UEV3ZCyATWFiGZRhhE2WAh8gv1jx4J26pcUs1n8sd2a1h6ZuBSqsyIlNSp\n" +
   "xtKsm3bqQFDHRrPcsBX4nanrw9DzkpH1k/I3WMSdGqkDAR3DtL7yXTJXJo2Sbrp5\n" +
   "EjzSn7DcDE1tL2En/tSVXeUY\n" +
   "-----END PRIVATE KEY-----";
</code>```

Can any one guide me can i use that?

答:
The private key can be created manually (like SSL, as you've stated), but with newer QZ Tray versions, I would recommend that you allow the software to do this for you.

Please use Advanced, Site Manager, "+", Create New, then with the files you have been given, follow the appropriate signing tutorial https://qz.io/wiki/signing-examples.

Note, this will only work on that one workstation.

Body:
I am writing script for woocommerce offline POS ordering where QZ Tray can help for print from local PC.

I have manage to integrate it but dialog box comes says,

Wants to connect QZ Tray Untrusted webiste

To avoid that i have done some research.

What i understood is there is a private key required like SSL.
as explained here, https://github.com/qzind/tray/blob/2.0/assets/signing/sign-message.js

i tried the same as above but it wont work on local host, may be due to fact that, as i didn't created SSL yet.

But can it be achieved for server SSL? i mean if i write my domain private key as below and pass it to function qz.security.setSignaturePromise

 var privateKey = "-----BEGIN PRIVATE KEY-----\n" +
   "MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQC0z9FeMynsC8+u\n" +
   "dvX+LciZxnh5uRj4C9S6tNeeAlIGCfQYk0zUcNFCoCkTknNQd/YEiawDLNbxBqut\n" +
   "bMDZ1aarys1a0lYmUeVLCIqvzBkPJTSQsCopQQ9V8WuT252zzNzs68dVGNdCJd5J\n" +
   "NRQykpwexmnjPPv0mvj7i8XgG379TyW6P+WWV5okeUkXJ9eJS2ouDYdR2SM9BoVW\n" +
   "+FgxDu6BmXhozW5EfsnajFp7HL8kQClI0QOc79yuKl3492rH6bzFsFn2lfwWy9ic\n" +
   "7cP8EpCTeFp1tFaD+vxBhPZkeTQ1HKx6hQ5zeHIB5ySJJZ7af2W8r4eTGYzbdRW2\n" +
   "4DDHCPhZAgMBAAECggEATvofR3gtrY8TLe+ET3wMDS8l3HU/NMlmKA9pxvjYfw7F\n" +
   "8h4VBw4oOWPfzU7A07syWJUR72kckbcKMfw42G18GbnBrRQG0UIgV3/ppBQQNg9Y\n" +
   "QILSR6bFXhLPnIvm/GxVa58pOEBbdec4it2Gbvie/MpJ4hn3K8atTqKk0djwxQ+b\n" +
   "QNBWtVgTkyIqMpUTFDi5ECiVXaGWZ5AOVK2TzlLRNQ5Y7US8lmGxVWzt0GONjXSE\n" +
   "iO/eBk8A7wI3zknMx5o1uZa/hFCPQH33uKeuqU5rmphi3zS0BY7iGY9EoKu/o+BO\n" +
   "HPwLQJ3wCDA3O9APZ3gmmbHFPMFPr/mVGeAeGP/BAQKBgQDaPELRriUaanWrZpgT\n" +
   "VnKKrRSqPED3anAVgmDfzTQwuR/3oD506F3AMBzloAo3y9BXmDfe8qLn6kgdZQKy\n" +
   "SFNLz888at96oi+2mEKPpvssqiwE6F3OtEM6yv4DP9KJHaHmXaWv+/sjwjzpFNjs\n" +
   "wGThBxFvrTWRJqBYsM1XNJJ2EQKBgQDUGbTSwHKqRCYWhQ1GPCZKE98l5UtMKvUb\n" +
   "hyWWOXoyoeYbJEMfG1ynX4JeXIkl6YtBjYCqszv9PjHa1rowTZaAPJ0V70zyhTcF\n" +
   "t581ii9LpiejIGrELHvJnW87QmjjStkjwGIqgKLp7Qe6CDjHI9HP1NM0uav/IQLW\n" +
   "pB6wyEz1yQKBgQCuxPut+Ax2rzM05KB9PAnWzO1zt3U/rtm8IAF8uVVGf7r+EDJ0\n" +
   "ZXJO6zj5G8WTEYHz5E86GI4ltBW0lKQoKouqdu27sMrv5trXG/CSImOcTVubQot9\n" +
   "chc1CkOKTp5IeJajafO6j817wZ4N+0gNsbYYEBUCnm/7ojdfT5ficpOoQQKBgQDB\n" +
   "PgKPmaNfGeQR1Ht5qEfCakR/RF/ML79Nq15FdmytQPBjfjBhYQ6Tt+MRkgGqtxOX\n" +
   "UBMQc2iOnGHT3puYcrhScec1GufidhjhbqDxqMrag7HNYDWmMlk+IeA7/4+Mtp8L\n" +
   "gbZuvvCvbLQDfIYueaYpUuBzQ08/jZYGdVU4/+WOcQKBgAGUN0kIB6EM1K/iZ0TN\n" +
   "jlt8P5UEV3ZCyATWFiGZRhhE2WAh8gv1jx4J26pcUs1n8sd2a1h6ZuBSqsyIlNSp\n" +
   "xtKsm3bqQFDHRrPcsBX4nanrw9DzkpH1k/I3WMSdGqkDAR3DtL7yXTJXJo2Sbrp5\n" +
   "EjzSn7DcDE1tL2En/tSVXeUY\n" +
   "-----END PRIVATE KEY-----";

Can any one guide me can i use that?


问:
Is there a function to stop a JWPlayer (8.7.3) ad and/or ad pod?
JWPlayer (version 8.7.3+commercial) provides the methods playAd and pauseAd. But it does NOT provide something to stop an ad and to resume the stream or the VoD.

https://developer.jwplayer.com/jw-player/docs/javascript-api-reference/#jwplayerplayadtag

There is an answered question from 2014/15, but it does not work for JWPlayer 8 anymore:
Stop JWPlayer ad playback

For context:

During a livestream we want to show some midrolls and let the JWPlayer request a VAST-URL.

The VAST-URL might return multiple ads within one ad pod.

Now we get an event that something interesting happens within the livestream and we want to stop the ads.

If it is impossible to stop the current ad, we want at least not start the next one within the pod.

We shudder away from destroying and recreating the player just to enable this feature.

Is there any way to do it?

答: jwplayer().playAd() will error but will stop the ad. You can follow that up with a jwplayer().pause(); jwplayer().play(); to return smoothly to the stream.


问:
Set limit bandwidth on EC2 instance
I'm going to use EC2 as test machines, and I have test scenario where I need bandwidth limit. So I'm wondering is there a way to set bandwidth limit using Java API for EC2, maybe using ELB or ?

Thanks

答:
If your servers use Linux, enable Traffic Control (tc) or you can setup your own gateway with tc.
In windows 10  - https://www.makeuseof.com/tag/tools-limit-bandwidth/</p>

Title: Set limit bandwidth on EC2 instance


问:
How do I get total number of columns received in RestAPI response?

This Is How My Current Parameter Input Looks Like:

```<code>value={data?.body?.marketState}
</code>```

I want to return no. of columns in "marketState".

eg.

```<code>4
</code>```

答:
You can simply access the .length property on the array

value={data?.body?.marketState?.length}

For more info about .length:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/length

For more information about JavaScript arrays in general:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array

Body:
This Is How My Current Parameter Input Looks Like:

value={data?.body?.marketState}

I want to return no. of columns in "marketState".

eg.

4


问:
User's email update time Send an email for authentication in laravel
When the user registers, an email will be sent to confirmation

But how do I send a notification when a user updates their email?

Like when he registers

答:
if you want to reverify your user's email  , you should set his email_verified_at to null then call sendEmailVerificationNotification method .

in your user model (located in app\user) add this method :

```<code> public function sendNewVerification() {
    $this->email_verified_at =null;
   $this->sendEmailVerificationNotification();
 }
</code>```

and call it in your controller .

hope that would work.

Body:
if you want to reverify your user's email  , you should set his email_verified_at to null then call sendEmailVerificationNotification method .

in your user model (located in app\user) add this method :

 public function sendNewVerification() {
    $this->email_verified_at =null;
   $this->sendEmailVerificationNotification();
 }

and call it in your controller .

hope that would work.


问:
Error while trying to send message to WMQ through java
I am trying to connect to a QM and send message to one of the queues, using below code:

```<code>import javax.jms.Connection;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.MessageConsumer;
import javax.jms.MessageProducer;
import javax.jms.Session;
import javax.jms.TextMessage;
import javax.jms.JMSException;

import com.ibm.msg.client.commonservices.*;
import com.ibm.mq.commonservices.internal.trace.*;
import com.ibm.msg.client.jms.JmsConnectionFactory;
import com.ibm.msg.client.jms.JmsFactoryFactory;
import com.ibm.msg.client.wmq.WMQConstants;

public class MQConnect {

    public static void main(String[] args) {
    Connection connection = null;
    Session session = null;
    Destination destination = null;
    Destination tempDestination = null;
    MessageProducer producer = null;
    MessageConsumer consumer = null;

    try {

        System.out.println(WMQConstants.WMQ_PROVIDER);

      JmsFactoryFactory ff = JmsFactoryFactory.getInstance(WMQConstants.WMQ_PROVIDER);
      JmsConnectionFactory cf = ff.createConnectionFactory();

      cf.setStringProperty(WMQConstants.WMQ_HOST_NAME, "hostname");
      cf.setIntProperty(WMQConstants.WMQ_PORT, port);
      cf.setStringProperty(WMQConstants.WMQ_CHANNEL, "channel");
      cf.setIntProperty(WMQConstants.WMQ_CONNECTION_MODE, WMQConstants.WMQ_CM_CLIENT);
      cf.setStringProperty(WMQConstants.WMQ_QUEUE_MANAGER, "QMName");

      connection = cf.createConnection();
      session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
      destination = session.createQueue("test_java_q");
      producer = session.createProducer(destination);

      long uniqueNumber = System.currentTimeMillis() % 1000;
      TextMessage message = session.createTextMessage(" " + uniqueNumber);
      connection.start();
      producer.send(message);

      }catch (JMSException jmsex) {
          System.out.println(jmsex.getErrorCode());
          System.out.println(jmsex.getLinkedException().getCause());
          System.out.println(jmsex.getMessage());
          }
    }
}
</code>```

The error I'm getting is :

```<code>Exception in thread "main" java.lang.NoClassDefFoundError:
    com/ibm/msg/client/commonservices/trace/Trace
    at com.ibm.msg.client.jms.JmsFactoryFactory.<clinit>(JmsFactoryFactory.java:54)
    at MQConnect.main(MQConnect.java:33)
Caused by: java.lang.ClassNotFoundException: com.ibm.msg.client.commonservices.trace.Trace
    at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
    ... 2 more
</code>```

I have the required jar files but I believe something is still missing from project references.
I have checked the jars and class specified in error is present in one of the jar files.

These are the jar files I have referenced:

```<code>com.ibm.mq.headers.jar
com.ibm.mq.jar
com.ibm.mq.pcf.jar
com.ibm.mq.tools.ras.jar
jms.jar
com.ibm.mqjms.jar
com.ibm.mq.jmqi.jar
com.ibm.mq.commonservices.jar
</code>```

There are also several other jars which are not com.ibm.*

Any suggestions?

答:
You really shouldn't be picking and choosing MQ JAR files.  For IBM MQ v8.0 or higher, you should be using the com.ibm.mq.allclient.jar and jms.jar files.  That's it, just 2 files.  IBM has posted the com.ibm.mq.allclient.jar file on Maven (and use the most recent one). You can find com.ibm.mq.allclient.jar here and jms.jar from here.

If you are using IBM MQ v7.5 or lower (which all releases are out of support) then the correct JAR files are:

connector.jar

com.ibm.mq.jar

com.ibm.mq.commonservices.jar

com.ibm.mq.headers.jar

com.ibm.mq.jmqi.jar

com.ibm.mq.pcf.jar

com.ibm.mqjms.jar

jms.jar

fscontext.jar

jndi.jar

jta.jar

ldap.jar

Also, do NOT mix and match JAR files between different releases of IBM MQ.  It will cause you all kinds of headaches.

Finally, what is this line:

```<code>destination = session.createQueue("test_java_q");
</code>```

It should be:

```<code>destination = context.createQueue("queue:///MY.TEST.QUEUE");
</code>```

where 'MY.TEST.QUEUE' actually exists in the queue manager.  All MQ objects are case sensitive and MQ Best Practises says to use uppercase object names.  i.e. avoid lowercase names.

Updated Feb. 14, 2022.

You need to add some code to your program so we can see what is going on.

(1) Add the following MQLevel class (taken from my open source project Universal File Mover) to your project:

```<code>public class MQLevel extends MQJavaLevel
{
   /**
    * The constructor
    */
   public MQLevel()
   {
      super();
   }

   /**
    * Get the IBM name for the MQ JAR class.
    * @return
    */
   public String getName()
   {
      return queryValue(0);
   }

   /**
    * Get the version of the MQ JAR class.
    * @return
    */
   public String getVersion()
   {
      return queryValue(1);
   }
}
</code>```

(2) Next add the following lines of code in your main method or at the very top of your code:

```<code>System.out.println(System.getProperty("java.class.path").replace(';','\n'));

try
{
   MQLevel mql = new MQLevel();
   System.out.println("MQ JAR Version = " + mql.getName()+" V"+mql.getVersion());
}
catch(Exception e)
{
   e.printStackTrace();
}
</code>```

Note: If you are on Linux/Unix rather than Windows then change the ';' (semi-colon) in the replace method to a ':' (colon).
i.e.

```<code>System.out.println(System.getProperty("java.class.path").replace(':','\n'));
</code>```

Run your program with the updates, then update the original posting both with the new output.

Body:
I am trying to connect to a QM and send message to one of the queues, using below code:

import javax.jms.Connection;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.MessageConsumer;
import javax.jms.MessageProducer;
import javax.jms.Session;
import javax.jms.TextMessage;
import javax.jms.JMSException;

import com.ibm.msg.client.commonservices.*;
import com.ibm.mq.commonservices.internal.trace.*;
import com.ibm.msg.client.jms.JmsConnectionFactory;
import com.ibm.msg.client.jms.JmsFactoryFactory;
import com.ibm.msg.client.wmq.WMQConstants;

public class MQConnect {

    public static void main(String[] args) {
    Connection connection = null;
    Session session = null;
    Destination destination = null;
    Destination tempDestination = null;
    MessageProducer producer = null;
    MessageConsumer consumer = null;

    try {

        System.out.println(WMQConstants.WMQ_PROVIDER);

      JmsFactoryFactory ff = JmsFactoryFactory.getInstance(WMQConstants.WMQ_PROVIDER);
      JmsConnectionFactory cf = ff.createConnectionFactory();

      cf.setStringProperty(WMQConstants.WMQ_HOST_NAME, "hostname");
      cf.setIntProperty(WMQConstants.WMQ_PORT, port);
      cf.setStringProperty(WMQConstants.WMQ_CHANNEL, "channel");
      cf.setIntProperty(WMQConstants.WMQ_CONNECTION_MODE, WMQConstants.WMQ_CM_CLIENT);
      cf.setStringProperty(WMQConstants.WMQ_QUEUE_MANAGER, "QMName");

      connection = cf.createConnection();
      session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
      destination = session.createQueue("test_java_q");
      producer = session.createProducer(destination);

      long uniqueNumber = System.currentTimeMillis() % 1000;
      TextMessage message = session.createTextMessage(" " + uniqueNumber);
      connection.start();
      producer.send(message);

      }catch (JMSException jmsex) {
          System.out.println(jmsex.getErrorCode());
          System.out.println(jmsex.getLinkedException().getCause());
          System.out.println(jmsex.getMessage());
          }
    }
}

The error I'm getting is :

Exception in thread "main" java.lang.NoClassDefFoundError:
    com/ibm/msg/client/commonservices/trace/Trace
    at com.ibm.msg.client.jms.JmsFactoryFactory.<clinit>(JmsFactoryFactory.java:54)
    at MQConnect.main(MQConnect.java:33)
Caused by: java.lang.ClassNotFoundException: com.ibm.msg.client.commonservices.trace.Trace
    at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
    ... 2 more

I have the required jar files but I believe something is still missing from project references.
I have checked the jars and class specified in error is present in one of the jar files.

These are the jar files I have referenced:

com.ibm.mq.headers.jar
com.ibm.mq.jar
com.ibm.mq.pcf.jar
com.ibm.mq.tools.ras.jar
jms.jar
com.ibm.mqjms.jar
com.ibm.mq.jmqi.jar
com.ibm.mq.commonservices.jar

There are also several other jars which are not com.ibm.*

Any suggestions?

Body:
You really shouldn't be picking and choosing MQ JAR files.  For IBM MQ v8.0 or higher, you should be using the com.ibm.mq.allclient.jar and jms.jar files.  That's it, just 2 files.  IBM has posted the com.ibm.mq.allclient.jar file on Maven (and use the most recent one). You can find com.ibm.mq.allclient.jar here and jms.jar from here.

If you are using IBM MQ v7.5 or lower (which all releases are out of support) then the correct JAR files are:

connector.jar

com.ibm.mq.jar

com.ibm.mq.commonservices.jar

com.ibm.mq.headers.jar

com.ibm.mq.jmqi.jar

com.ibm.mq.pcf.jar

com.ibm.mqjms.jar

jms.jar

fscontext.jar

jndi.jar

jta.jar

ldap.jar

Also, do NOT mix and match JAR files between different releases of IBM MQ.  It will cause you all kinds of headaches.

Finally, what is this line:

destination = session.createQueue("test_java_q");

It should be:

destination = context.createQueue("queue:///MY.TEST.QUEUE");

where 'MY.TEST.QUEUE' actually exists in the queue manager.  All MQ objects are case sensitive and MQ Best Practises says to use uppercase object names.  i.e. avoid lowercase names.

Updated Feb. 14, 2022.

You need to add some code to your program so we can see what is going on.

(1) Add the following MQLevel class (taken from my open source project Universal File Mover) to your project:

public class MQLevel extends MQJavaLevel
{
   /**
    * The constructor
    */
   public MQLevel()
   {
      super();
   }

   /**
    * Get the IBM name for the MQ JAR class.
    * @return
    */
   public String getName()
   {
      return queryValue(0);
   }

   /**
    * Get the version of the MQ JAR class.
    * @return
    */
   public String getVersion()
   {
      return queryValue(1);
   }
}

(2) Next add the following lines of code in your main method or at the very top of your code:

System.out.println(System.getProperty("java.class.path").replace(';','\n'));

try
{
   MQLevel mql = new MQLevel();
   System.out.println("MQ JAR Version = " + mql.getName()+" V"+mql.getVersion());
}
catch(Exception e)
{
   e.printStackTrace();
}

Note: If you are on Linux/Unix rather than Windows then change the ';' (semi-colon) in the replace method to a ':' (colon).
i.e.

System.out.println(System.getProperty("java.class.path").replace(':','\n'));

Run your program with the updates, then update the original posting both with the new output.


问:
error with appending to a file and using an array
I have written this code:

```<code>    class component(object):

      def __init__(self,
                   name = None,
                   height = None,
                   width = None):

        self.name = name
        self.height = height
        self.width = width

class system(object):

      def __init__(self,
                   name = None,
                   lines = None,
                   *component):

        self.name = name
        self.component = component

        if lines is None:
                self.lines = []
        else:
                            self.lines = lines

      def writeTOFile(self,
                      *component):
        self.component = component

        line =" "
        self.lines.append(line)

        line= "#----------------------------------------- SYSTEM ---------------------------------------#"
        self.lines.append(line)

Component1 = component ( name = 'C1',
                         height = 500,
                         width = 400)
Component2 = component ( name = 'C2',
                         height = 600,
                         width = 700)

system1 = system(Component1, Component2)
system1.writeTOFile(Component1, Component2)
</code>```

and I get the error :

```<code>  Traceback (most recent call last):
  File "C:\Python27\Work\trial2.py", line 46, in <module>
    system1.writeTOFile(Component1, Component2)
  File "C:\Python27\Work\trial2.py", line 32, in writeTOFile
    self.lines.append(line)
AttributeError: 'component' object has no attribute 'append'
</code>```

And I don't really know how to fix it.

Also is there a way for defining my system1 as system(Component) where component = [Component1, Component2, ...Componentn] ?

Thanks in adavance

答:
The problem is in the fact that when defining system you pass Component1 as a line argument in constructor. Since python does all the operations he can and not checking for the argument types if the operation can be done legally, this passes.

Maybe it would be a nice idea in the system constructor to check if the given argument lines is really of type list, and maybe writing something like:

```<code>    if lines is None or not isinstance(lines, list):
            self.lines = []
    else:
            self.lines = lines
</code>```

That way, you would know about the problem before you try appending to the non-list object.

And as for the second part of your question, you can do it exactly like you suggested:

```<code>system1 = system([Component1, Component2, MyComponent], [])
</code>```

(if you, for example, want to make a system with 3 components, and an empty list as an "console" for lines)

Body:
I have written this code:

    class component(object):

      def __init__(self,
                   name = None,
                   height = None,
                   width = None):

        self.name = name
        self.height = height
        self.width = width

class system(object):

      def __init__(self,
                   name = None,
                   lines = None,
                   *component):

        self.name = name
        self.component = component

        if lines is None:
                self.lines = []
        else:
                            self.lines = lines

      def writeTOFile(self,
                      *component):
        self.component = component

        line =" "
        self.lines.append(line)

        line= "#----------------------------------------- SYSTEM ---------------------------------------#"
        self.lines.append(line)

Component1 = component ( name = 'C1',
                         height = 500,
                         width = 400)
Component2 = component ( name = 'C2',
                         height = 600,
                         width = 700)

system1 = system(Component1, Component2)
system1.writeTOFile(Component1, Component2)

and I get the error :

  Traceback (most recent call last):
  File "C:\Python27\Work\trial2.py", line 46, in <module>
    system1.writeTOFile(Component1, Component2)
  File "C:\Python27\Work\trial2.py", line 32, in writeTOFile
    self.lines.append(line)
AttributeError: 'component' object has no attribute 'append'

And I don't really know how to fix it.

Also is there a way for defining my system1 as system(Component) where component = [Component1, Component2, ...Componentn] ?

Thanks in adavance

Body:
The problem is in the fact that when defining system you pass Component1 as a line argument in constructor. Since python does all the operations he can and not checking for the argument types if the operation can be done legally, this passes.

Maybe it would be a nice idea in the system constructor to check if the given argument lines is really of type list, and maybe writing something like:

    if lines is None or not isinstance(lines, list):
            self.lines = []
    else:
            self.lines = lines

That way, you would know about the problem before you try appending to the non-list object.

And as for the second part of your question, you can do it exactly like you suggested:

system1 = system([Component1, Component2, MyComponent], [])

(if you, for example, want to make a system with 3 components, and an empty list as an "console" for lines)


问:
How do I change viewControllers in swift with Foundation Xcode
I am trying to programmatically switch to another viewController scene when a certain event happens in Xcode for a MacOS app but am having trouble.
The second view controller is in the same storyboard as the one I am trying to switch from.
I currently have

```<code>let secondViewController = ViewController(nibName: "outcome", bundle: nil)
            self.present(secondViewController, animator: true as! NSViewControllerPresentationAnimator)
</code>```

but it seems to crash when the event is triggered:

```<code>Could not cast value of type 'Swift.Bool' (0x2010043a8) to '__C.NSViewControllerPresentationAnimator' (0x2007787d0).
</code>```

it also shows an error Thread 1: signal SIGABRT on the second command where I self.present

答:
you are trying to cast a bool to NSViewControllerPresentationAnimator

try this code instead:

```<code>let secondViewController = ViewController(nibName: "outcome", bundle: nil)
 self.present(secondViewController, animator: true)
</code>```

Body:
I am trying to programmatically switch to another viewController scene when a certain event happens in Xcode for a MacOS app but am having trouble.
The second view controller is in the same storyboard as the one I am trying to switch from.
I currently have

let secondViewController = ViewController(nibName: "outcome", bundle: nil)
            self.present(secondViewController, animator: true as! NSViewControllerPresentationAnimator)

but it seems to crash when the event is triggered:

Could not cast value of type 'Swift.Bool' (0x2010043a8) to '__C.NSViewControllerPresentationAnimator' (0x2007787d0).

it also shows an error Thread 1: signal SIGABRT on the second command where I self.present

Body:
you are trying to cast a bool to NSViewControllerPresentationAnimator

try this code instead:

let secondViewController = ViewController(nibName: "outcome", bundle: nil)
 self.present(secondViewController, animator: true)


问:
Elastic search, Logstash: document_id string does not get evaluated
To prevent data duplication while injesting data from logstash I am adding a document_id string for logstash conf with a peopleRowId column. However it does not get evaluated. So in my case I am trying to set document id as  document_id => "%{[document][projectsRowId]}", However this does not get evaluated for some reason and id in elastic search as I added ROW_NUMBER() OVER (
ORDER BY a.created_at
) as projectsRowId to create unique id

```<code>[
      {
        "_index" : "projectsv3",
        "_type" : "_doc",
        "_id" : "%{[document][projectsRowId]}",
        "_score" : 1.0,
        "_source" : {...single record}
</code>```

]

I am not sure why document id is not getting enabled. Using elastic search 7 and ECS is also disabled. I have tried out other methods too like filter with fingerprint I have also tried to set document id as document_id => "%{projectsRowId}" although in all cases it does not get evaluated

```<code>input {
    jdbc {
        jdbc_driver_library => "C:\\ElasticStack\\mysql-connector-java-8.0.24\\mysql-connector-java-8.0.24.jar"
        jdbc_driver_class => "com.mysql.jdbc.Driver"
        # mysql jdbc connection string to our database, mydb
         jdbc_connection_string =>  "jdbc:mysql://127.0.0.1:3306/corrabla_sercweb"
        # The user we wish to execute our statement as
        jdbc_user => "root"
        jdbc_password => "root"
        schedule => "* * * * *"
        clean_run => true
        # use_column_value => true
        # tracking_column => "%{[@metadata][fingerprint]}"
        # tracking_column_type => "numeric"
        # our query to fetch people details
        statement => "select ROW_NUMBER() OVER (
        ORDER BY a.created_at
    ) as projectsRowId , (a.created_at), tr.report_number as 'tech_report_number', tr.file_s3 as 'tech_report_file_name', tr.abstract as 'tech_report_abstract' , c.prefix as 'piPrefix' , c.first_name as 'piFirstName', c.middle_name as 'piMiddleName' ,c.last_name as 'piLastName', b.person_id, d.prefix as 'coPiPrefix' "
        # use_column_value => true
        # tracking_column => id
        # tracking_column_type => "numeric"
    }
}
output {
   elasticsearch {
       action => "create"
       hosts => "http://127.0.0.1:9200"
       index => "projectsv3"
       doc_as_upsert => true
       document_id => "%{[document][projectsRowId]}"
        }
}
</code>```

答: By default a jdbc input will fold field names to lower case, so your event will have a field called projectsrowid, not projectsRowId. If you set lowercase_column_names => false on the input then `document_id => "%{[projectsRowId]}" will work.

Body:
To prevent data duplication while injesting data from logstash I am adding a document_id string for logstash conf with a peopleRowId column. However it does not get evaluated. So in my case I am trying to set document id as  document_id => "%{[document][projectsRowId]}", However this does not get evaluated for some reason and id in elastic search as I added ROW_NUMBER() OVER (
ORDER BY a.created_at
) as projectsRowId to create unique id

[
      {
        "_index" : "projectsv3",
        "_type" : "_doc",
        "_id" : "%{[document][projectsRowId]}",
        "_score" : 1.0,
        "_source" : {...single record}

]

I am not sure why document id is not getting enabled. Using elastic search 7 and ECS is also disabled. I have tried out other methods too like filter with fingerprint I have also tried to set document id as document_id => "%{projectsRowId}" although in all cases it does not get evaluated

input {
    jdbc {
        jdbc_driver_library => "C:\\ElasticStack\\mysql-connector-java-8.0.24\\mysql-connector-java-8.0.24.jar"
        jdbc_driver_class => "com.mysql.jdbc.Driver"
        # mysql jdbc connection string to our database, mydb
         jdbc_connection_string =>  "jdbc:mysql://127.0.0.1:3306/corrabla_sercweb"
        # The user we wish to execute our statement as
        jdbc_user => "root"
        jdbc_password => "root"
        schedule => "* * * * *"
        clean_run => true
        # use_column_value => true
        # tracking_column => "%{[@metadata][fingerprint]}"
        # tracking_column_type => "numeric"
        # our query to fetch people details
        statement => "select ROW_NUMBER() OVER (
        ORDER BY a.created_at
    ) as projectsRowId , (a.created_at), tr.report_number as 'tech_report_number', tr.file_s3 as 'tech_report_file_name', tr.abstract as 'tech_report_abstract' , c.prefix as 'piPrefix' , c.first_name as 'piFirstName', c.middle_name as 'piMiddleName' ,c.last_name as 'piLastName', b.person_id, d.prefix as 'coPiPrefix' "
        # use_column_value => true
        # tracking_column => id
        # tracking_column_type => "numeric"
    }
}
output {
   elasticsearch {
       action => "create"
       hosts => "http://127.0.0.1:9200"
       index => "projectsv3"
       doc_as_upsert => true
       document_id => "%{[document][projectsRowId]}"
        }
}


问:
What dns query TYPE is used to resolve the name in an SPF include statement?
SPF records may contain include statements that list a dns name.  What is the query type you want to use to get the associated IPs for that name?  Do I need to query TXT records?</p>

答: Yes, you need to use an request TXT records when resolving SPF. For a while there was a separate SPF DNS record type, but uptake was poor, and so it reverted to using TXT records in RFC7208.


问:
CDK Assets - Docker load build context failing with Access Denied when using Container.fromImage
While using the ContainerImage.fromAsset() which builds the Docker image, I am running into an Access denied error during the copy operation (COPY client $APP_HOME/client). There is no error if I build the Docker image as is using the docker build command.

I have checked the file permissions and there is nothing wrong. It also does not seem to be related to the long path name and renaming anything in the path fixes the problem.

Tried checking out the code on another computer but same problem.

```<code>#1 transferring dockerfile: 1.08kB 0.0s done
#1 DONE 0.0s

#2 [internal] load .dockerignore
#2 transferring context: 203B 0.0s done
#2 DONE 0.0s

#3 [internal] load metadata for docker.io/library/amazoncorretto:11-alpine
#3 DONE 0.9s

#4 [internal] load metadata for docker.io/library/amazoncorretto:11
#4 DONE 2.2s

#5 [stage-1 1/4] FROM docker.io/library/amazoncorretto:11-alpine@sha256:048...
#5 DONE 0.0s

#8 [builder 1/7] FROM docker.io/library/amazoncorretto:11@sha256:75be50f146...
#8 resolve docker.io/library/amazoncorretto:11@sha256:75be50f146c5d36d11348960359457e2e9303706785cf273739f0dbbea1ba429 done
#8 sha256:f964900200fc1f8473ac70d9da14cde8bae251ffb4a8f4792e2bf9baf6aaac70 0B / 62.24MB 0.1s
#8 sha256:75be50f146c5d36d11348960359457e2e9303706785cf273739f0dbbea1ba429 547B / 547B done
#8 sha256:e878e893d995681f88254eb134ff6ba0bf921aefb7303aa6ef3b5864dd80e45c 742B / 742B done
#8 sha256:6e8a5ad94e6eed735b1da93109529df475d74f360b60d69ce8e40afc15088aed 3.07kB / 3.07kB done
#8 ...

#10 [internal] load build context
#10 transferring context: 15.13MB 0.2s done
#10 ERROR: error from sender: open client\src\app\components\portfolio\portfolioSettings\portfolioSettingsContent\editHierarchy\portfolioSettingsGrid\gridContentMenu: Access is denied.

#8 [builder 1/7] FROM docker.io/library/amazoncorretto:11@sha256:75be50f146...
#8 CANCELED
------
 > [internal] load build context:
------
error from sender: open client\src\app\components\portfolio\portfolioSettings\portfolioSettingsContent\editHierarchy\portfolioSettingsGrid\gridContentMenu: Access is denied.

 ❌  pwcore-dev failed: Error: Failed to publish one or more assets. See the error messages above for more information.
    at Object.publishAssets (C:\Users\rarora\AppData\Roaming\npm\node_modules\aws-cdk\lib\util\asset-publishing.ts:25:11)
    at runMicrotasks (<anonymous>)
    at processTicksAndRejections (internal/process/task_queues.js:97:5)
    at CloudFormationDeployments.publishStackAssets (C:\Users\rarora\AppData\Roaming\npm\node_modules\aws-cdk\lib\api\cloudformation-deployments.ts:305:7)
    at CloudFormationDeployments.deployStack (C:\Users\rarora\AppData\Roaming\npm\node_modules\aws-cdk\lib\api\cloudformation-deployments.ts:202:5)
    at CdkToolkit.deploy (C:\Users\rarora\AppData\Roaming\npm\node_modules\aws-cdk\lib\cdk-toolkit.ts:199:24)
    at initCommandLine (C:\Users\rarora\AppData\Roaming\npm\node_modules\aws-cdk\bin\cdk.ts:267:9)
Failed to publish one or more assets. See the error messages above for more information.
</code>```

Update 1:
Triaged the issue with an AWS rep. While the underlying root cause is still a mystery, the problem may be Docker related. When we do a CDK deploy, it copies the contents to cdk.out/assets.<some_unique_hash_code>. If we do a native Docker build there, we get the same problem implying that it is related to Docker.

```<code>C:\git_ws\cdk-service\cdk.out\asset.597677384344d1483275063cf834a0e0fef9a332625cc06b13b39aa9f192da5f>docker build -t service .
[+] Building 0.4s (5/6)
 => [internal] load build definition from Dockerfile                                                                                0.0s
 => => transferring dockerfile: 99B                                                                                0.0s
 => [internal] load .dockerignore                                                                                0.0s
 => => transferring context: 176B                                                                                0.0s
 => [internal] load metadata for docker.io/library/amazoncorretto:11                                                                                0.0s
 => ERROR [internal] load build context                                                                                0.3s
 => => transferring context: 32.27MB                                                                                0.3s
 => CACHED [1/2] FROM docker.io/library/amazoncorretto:11                                                                                0.0s
------
 > [internal] load build context:
------
error from sender: open client\src\app\components\portfolio\portfolioSettings\portfolioSettingsContent\editHierarchy\portfolioSettingsGrid\gridContentMenu: Access is denied.
</code>```

Renaming the assets directory solves the problem. It does not seem to be related to long file path name as adding more characters to the asset directory also solves the problem

答:
The problem seems to be coming from Docker using BuildKit which is default now.
https://github.com/moby/buildkit/issues/1366

Disabling the BuildKit fixes the problem.

Body:
While using the ContainerImage.fromAsset() which builds the Docker image, I am running into an Access denied error during the copy operation (COPY client $APP_HOME/client). There is no error if I build the Docker image as is using the docker build command.

I have checked the file permissions and there is nothing wrong. It also does not seem to be related to the long path name and renaming anything in the path fixes the problem.

Tried checking out the code on another computer but same problem.

#1 transferring dockerfile: 1.08kB 0.0s done
#1 DONE 0.0s

#2 [internal] load .dockerignore
#2 transferring context: 203B 0.0s done
#2 DONE 0.0s

#3 [internal] load metadata for docker.io/library/amazoncorretto:11-alpine
#3 DONE 0.9s

#4 [internal] load metadata for docker.io/library/amazoncorretto:11
#4 DONE 2.2s

#5 [stage-1 1/4] FROM docker.io/library/amazoncorretto:11-alpine@sha256:048...
#5 DONE 0.0s

#8 [builder 1/7] FROM docker.io/library/amazoncorretto:11@sha256:75be50f146...
#8 resolve docker.io/library/amazoncorretto:11@sha256:75be50f146c5d36d11348960359457e2e9303706785cf273739f0dbbea1ba429 done
#8 sha256:f964900200fc1f8473ac70d9da14cde8bae251ffb4a8f4792e2bf9baf6aaac70 0B / 62.24MB 0.1s
#8 sha256:75be50f146c5d36d11348960359457e2e9303706785cf273739f0dbbea1ba429 547B / 547B done
#8 sha256:e878e893d995681f88254eb134ff6ba0bf921aefb7303aa6ef3b5864dd80e45c 742B / 742B done
#8 sha256:6e8a5ad94e6eed735b1da93109529df475d74f360b60d69ce8e40afc15088aed 3.07kB / 3.07kB done
#8 ...

#10 [internal] load build context
#10 transferring context: 15.13MB 0.2s done
#10 ERROR: error from sender: open client\src\app\components\portfolio\portfolioSettings\portfolioSettingsContent\editHierarchy\portfolioSettingsGrid\gridContentMenu: Access is denied.

#8 [builder 1/7] FROM docker.io/library/amazoncorretto:11@sha256:75be50f146...
#8 CANCELED
------
 > [internal] load build context:
------
error from sender: open client\src\app\components\portfolio\portfolioSettings\portfolioSettingsContent\editHierarchy\portfolioSettingsGrid\gridContentMenu: Access is denied.

 ❌  pwcore-dev failed: Error: Failed to publish one or more assets. See the error messages above for more information.
    at Object.publishAssets (C:\Users\rarora\AppData\Roaming\npm\node_modules\aws-cdk\lib\util\asset-publishing.ts:25:11)
    at runMicrotasks (<anonymous>)
    at processTicksAndRejections (internal/process/task_queues.js:97:5)
    at CloudFormationDeployments.publishStackAssets (C:\Users\rarora\AppData\Roaming\npm\node_modules\aws-cdk\lib\api\cloudformation-deployments.ts:305:7)
    at CloudFormationDeployments.deployStack (C:\Users\rarora\AppData\Roaming\npm\node_modules\aws-cdk\lib\api\cloudformation-deployments.ts:202:5)
    at CdkToolkit.deploy (C:\Users\rarora\AppData\Roaming\npm\node_modules\aws-cdk\lib\cdk-toolkit.ts:199:24)
    at initCommandLine (C:\Users\rarora\AppData\Roaming\npm\node_modules\aws-cdk\bin\cdk.ts:267:9)
Failed to publish one or more assets. See the error messages above for more information.

Update 1:
Triaged the issue with an AWS rep. While the underlying root cause is still a mystery, the problem may be Docker related. When we do a CDK deploy, it copies the contents to cdk.out/assets.<some_unique_hash_code>. If we do a native Docker build there, we get the same problem implying that it is related to Docker.

C:\git_ws\cdk-service\cdk.out\asset.597677384344d1483275063cf834a0e0fef9a332625cc06b13b39aa9f192da5f>docker build -t service .
[+] Building 0.4s (5/6)
 => [internal] load build definition from Dockerfile                                                                                0.0s
 => => transferring dockerfile: 99B                                                                                0.0s
 => [internal] load .dockerignore                                                                                0.0s
 => => transferring context: 176B                                                                                0.0s
 => [internal] load metadata for docker.io/library/amazoncorretto:11                                                                                0.0s
 => ERROR [internal] load build context                                                                                0.3s
 => => transferring context: 32.27MB                                                                                0.3s
 => CACHED [1/2] FROM docker.io/library/amazoncorretto:11                                                                                0.0s
------
 > [internal] load build context:
------
error from sender: open client\src\app\components\portfolio\portfolioSettings\portfolioSettingsContent\editHierarchy\portfolioSettingsGrid\gridContentMenu: Access is denied.

Renaming the assets directory solves the problem. It does not seem to be related to long file path name as adding more characters to the asset directory also solves the problem


问:
recommend a Flash MP3 player supporting starting playing from a specific time
I need a Flash player which can start my mp3 file from a specific time based on the embedding properties or on URL or just anything. </p>

答:
Check out JWplayer. it has a great JS api which you can use to move around the current position.

http://www.longtailvideo.com/


问:
How to quickly deallocate an entire subtree?
I'm implementing an Alpha-Beta pruning (MiniMax) algorithm for a board game. I have a Board class with GetAvailableMoves(), PlayMove(Move x) and UndoMove() which all modify the game position inside the Board class. To implement Alpha-Beta I need a tree structure to keep track of the alpha and beta values of every position.

Since I'll want to calculate the best move multiple times in a game, I want to reuse the part of the tree that I already calculated and throw away the rest. If I implement the tree as doubly-linked nodes, then I'll have to call delete on every node in all subtrees that I want to delete. This can be very expensive.

How can I implement a tree that allows me to quickly cut and destroy an entire branch, possibly in O(1) time?

答:
You can implement a datapool for your data. To get an allocated node you get it from the pool, and when you delete you put it back in the pool. Then you only allocate new memory when your pool is empty, and you only delete at the end of your runtime.

This will still need to move all the out of data objects back to the pool when you cut a subtree, so not O(1). But no delete calls.

Alternatively, if you have plenty of memory available and you just want a O(1) way to delete your subtrees, you can move the root of your subtree to a ToDeleteLater queue. And at the end of your run or whenever your program has free time, it can clear out this queue by running through trees deleting.

Unless the subtrees are huge, deleting honestly should not take too long, so instead of using pointers that you need to delete. You can implement destructors that take care of the deleting (RAII) So you don't have to write a complicated deleter.

Note: It is usually recommended that you post some code or more details so users can give more specific advice.


问:
DateTime difference in Days has same result for 27th to 18th of May and 28th to 18th May (both 9 days)
I'm having some issues with Duration.inDays. When I compute the difference in Days between 27th of May to the 18th of May, it is the as the difference in Days between 27th of May to the 18th of May. Here is a code snipped:

```<code>final firstDate = DateTime(2022, 3, 18, 0, 0, 0, 0, 0);
final secondDate = DateTime(2022, 3, 27, 0, 0, 0, 0, 0);
final thirdDate = DateTime(2022, 3, 28, 0, 0, 0, 0, 0);

final firstDif = firstDate.difference(secondDate);
final secondDif = firstDate.difference(thirdDate);

print("First Days: ${firstDif.inDays} First Hours: ${firstDif.inHours} Second Days: ${secondDif.inDays} Second Hours: ${secondDif.inHours}");
</code>```

This is the print statement:

First Days: -9 First Hours: -216 Second Days: -9 Second Hours: -239

As you can see, the difference in hours for the 28th is only -239 hours, not -240 as I would expect. Thus the resulting difference in days is -9 in both cases.

Why is this happening and how can I fix this issue?

答:
The reason that you get 239 hours is that Daylight Savings Time kicked in between the two dates, so one day was 'shorter' by an hour.  See the various caveats in the documentation of DateTime and Duration.

To avoid summer time issues, use UTC dates. Replace all your constructors with DateTime.utc.

```<code>final firstDate = DateTime.utc(2022, 3, 18, 0, 0, 0, 0, 0);
final secondDate = DateTime.utc(2022, 3, 27, 0, 0, 0, 0, 0);
final thirdDate = DateTime.utc(2022, 3, 28, 0, 0, 0, 0, 0);
</code>```

Body:
I'm having some issues with Duration.inDays. When I compute the difference in Days between 27th of May to the 18th of May, it is the as the difference in Days between 27th of May to the 18th of May. Here is a code snipped:

final firstDate = DateTime(2022, 3, 18, 0, 0, 0, 0, 0);
final secondDate = DateTime(2022, 3, 27, 0, 0, 0, 0, 0);
final thirdDate = DateTime(2022, 3, 28, 0, 0, 0, 0, 0);

final firstDif = firstDate.difference(secondDate);
final secondDif = firstDate.difference(thirdDate);

print("First Days: ${firstDif.inDays} First Hours: ${firstDif.inHours} Second Days: ${secondDif.inDays} Second Hours: ${secondDif.inHours}");

This is the print statement:

First Days: -9 First Hours: -216 Second Days: -9 Second Hours: -239

As you can see, the difference in hours for the 28th is only -239 hours, not -240 as I would expect. Thus the resulting difference in days is -9 in both cases.

Why is this happening and how can I fix this issue?

Body:
The reason that you get 239 hours is that Daylight Savings Time kicked in between the two dates, so one day was 'shorter' by an hour.  See the various caveats in the documentation of DateTime and Duration.

To avoid summer time issues, use UTC dates. Replace all your constructors with DateTime.utc.

final firstDate = DateTime.utc(2022, 3, 18, 0, 0, 0, 0, 0);
final secondDate = DateTime.utc(2022, 3, 27, 0, 0, 0, 0, 0);
final thirdDate = DateTime.utc(2022, 3, 28, 0, 0, 0, 0, 0);


问:
Live Server Extension in VS Code is not working in WSL
I have been working with visual studio a long of time ago in Windows without any problems.
I installed WSL in my PC, all perfect.

But now I migrated one of my webpages directory to the WSL root
\wsl$\Ubuntu\home\user\webPage

And when I click on "Live Server" extension, it loads propertly in:
http://127.0.0.1:5500/index.html

But when I make a change and save, is not working

Do I have to change something else? Of course all the extensions are installed, seems to be the same

答:
You have to install this extension Remote Developer Extenson Pack

Once you do this, open your Visual Studio normally and you will be able to develop, there are some extensions not compatible.

More references here

It is important to see in your VS code in the left-down side, that you are in WSL:Ubuntu in color green, You can also open in that sideWSL UBUNTU


问:
Django : How do we automatically hide the parts of a form that requests information that we have already entered?
Saying that, I have two classes (service and product) which are linked with a foreign key. Each class contains a number of forms.
I want that each information entered in the form of the product class is no longer requested in the form of the service class and if it has detected it I want to hide the fields which request it in the template! (to avoid repetition)
Do you have a method for doing this pleaaaaaase?
Product :
model.py

```<code>class Product :
    name = models.CharField(max_length=100, null=True)
    length = models.CharField(max_length=2, null=True)
    type = models.CharField(max_length=2, null=True)

</code>```

Service :
model.py

```<code>class Service :
    date_creation = models.DateTimeField(auto_now_add=True)
    product = models.ForeignKey(Product, on_delete=models.PROTECT, null=True,  blank=True)
</code>```

答:
You can programatically remove form fields by overriding it's init method in the forms.py.

Refer: https://stackoverflow.com/a/32128961/4618758

Body:
Saying that, I have two classes (service and product) which are linked with a foreign key. Each class contains a number of forms.
I want that each information entered in the form of the product class is no longer requested in the form of the service class and if it has detected it I want to hide the fields which request it in the template! (to avoid repetition)
Do you have a method for doing this pleaaaaaase?
Product :
model.py

class Product :
    name = models.CharField(max_length=100, null=True)
    length = models.CharField(max_length=2, null=True)
    type = models.CharField(max_length=2, null=True)

Service :
model.py

class Service :
    date_creation = models.DateTimeField(auto_now_add=True)
    product = models.ForeignKey(Product, on_delete=models.PROTECT, null=True,  blank=True)


问:
how to preset a dropdown list in reporting services?
I have a report done in reporting services with some drop down lists. What I want to do is preset one of these lists so that when the report runs, it is automatically selected. How can I do this? Whenever I run the report I have to select an item from the list otherwise it won't let me run it.

Can you help me?

Thank you!!

I add screenshots:

答:
You need to make sure that you set the default value to a valid value. The value must appear in the field stated in your available values 'value field' .

So in your case the string "TODOS" must appear in your Code field in the DS_Sector dataset.

I suspect you either need to select the Code for "TODOS" or if TODOS is a valid Code, remove the quotes from the default value.


问:
How to check if any word in a string has special characters and conditions in Pandas
I have a dataframe, where one column contains a tweet. I want to get the rows of this dataframe, where this "tweet" column contains any words that start with "#" and have 2 or more capital letters.

So for example, I want to retreive such rows:

I love coding in python. #CodingSession

I am not scared of #COVID19 anymore.

However, these would not classify under my conditions:

I love coding in python. #Coding #Session

I love coding in python. #Codingsession

I am not scared of #Covid19 anymore.

答:
Try str.contains:

```<code>df['Match'] = df['tweet'].str.contains(r'#[A-Z][^A-Z#]*[A-Z]')
print(df)

# Output
                                       tweet  Match
0    I love coding in python. #CodingSession   True
1        I am not scared of #COVID19 anymore   True
2  I love coding in python. #Coding #Session  False
3    I love coding in python. #Codingsession  False
4       I am not scared of #Covid19 anymore.  False
</code>```

[A-Z] for a capital letter

[^A-Z#]* for anything else except capital letter or #

[A-Z] and again a capital letter

Regex101

Body:
Try str.contains:

df['Match'] = df['tweet'].str.contains(r'#[A-Z][^A-Z#]*[A-Z]')
print(df)

# Output
                                       tweet  Match
0    I love coding in python. #CodingSession   True
1        I am not scared of #COVID19 anymore   True
2  I love coding in python. #Coding #Session  False
3    I love coding in python. #Codingsession  False
4       I am not scared of #Covid19 anymore.  False

[A-Z] for a capital letter

[^A-Z#]* for anything else except capital letter or #

[A-Z] and again a capital letter

Regex101


问:
Visual studio code
I installed, desinstalled and installed again the Visual Studio Code and in may computer it can`t appear the bar in the Y axix in left side of the screem. Someone can help me?enter image description here</p>

答: In VS Code, at the top menu, go to View -> Appearance -> Show Activity Bar. This will toggle the menu you're looking for.</p>

Title: Visual studio code


问:
Maven error "Failure to transfer..."
I am trying to set up a project using Maven (m2eclipse), but I get this error in Eclipse:

Description    Resource    Path    Location    Type
  Could not calculate build plan: Failure to transfer org.apache.maven.plugins:maven-compiler-plugin:pom:2.0.2 from http://repo1.maven.org/maven2 was cached in the local repository, resolution will not be reattempted until the update interval of central has elapsed or updates are forced. Original error: Could not transfer artifact org.apache.maven.plugins:maven-compiler-plugin:pom:2.0.2 from/to central (http://repo1.maven.org/maven2): No response received after 60000   ExampleProject      Unknown Maven Problem

Any ideas?
It would be helpful if you could show me how to check if everything is configured fine...

答:
Remove all your failed downloads:

```<code>find ~/.m2  -name "*.lastUpdated" -exec grep -q "Could not transfer" {} \; -print -exec rm {} \;
</code>```

For windows:

```<code>cd %userprofile%\.m2\repository
for /r %i in (*.lastUpdated) do del %i
</code>```

Then rightclick on your project in eclipse and choose Maven->"Update Project ...", make sure "Update Dependencies" is checked in the resulting dialog and click OK.

Title: Maven error "Failure to transfer..."

Body:
Remove all your failed downloads:

find ~/.m2  -name "*.lastUpdated" -exec grep -q "Could not transfer" {} \; -print -exec rm {} \;

For windows:

cd %userprofile%\.m2\repository
for /r %i in (*.lastUpdated) do del %i

Then rightclick on your project in eclipse and choose Maven->"Update Project ...", make sure "Update Dependencies" is checked in the resulting dialog and click OK.


问:
Adding hours to dates in Presto
In a Presto db table, I have two string fields, a date of the form, '2022-01-01', and an hour of the form, 22, for 22:00. I'm trying to combine these two elements into a proper timestamp, with date, hours, minutes, seconds. How can I accomplish this?

What I've tried so far

```<code>SELECT DATE_ADD('hour', 22, DATE(d) ) AS dt
FROM table
</code>```

However, I get the error that 'hour' is not the proper DATE field. However, from documentation, my arguments appear to the in the proper order.
https://prestodb.io/docs/current/functions/datetime.html

答:
You need to either cast your date to timestamp:

-- sample data
WITH dataset(x, y) AS (
    VALUES (22,  '2022-01-01')
)

-- query
SELECT date_add('hour', x, cast(date(y) as timestamp))
FROM dataset
```
<p>Or parse the string as timestamp:</p>
<pre class="lang-sql prettyprint-override"><code>SELECT date_add('hour', x, date_parse(y, '%Y-%m-%d'))
FROM dataset
</code>```

Output:

_col0

2022-01-01 22:00:00.000

Title: Adding hours to dates in Presto

Body:
In a Presto db table, I have two string fields, a date of the form, '2022-01-01', and an hour of the form, 22, for 22:00. I'm trying to combine these two elements into a proper timestamp, with date, hours, minutes, seconds. How can I accomplish this?

What I've tried so far

SELECT DATE_ADD('hour', 22, DATE(d) ) AS dt
FROM table

However, I get the error that 'hour' is not the proper DATE field. However, from documentation, my arguments appear to the in the proper order.
https://prestodb.io/docs/current/functions/datetime.html

Body:
You need to either cast your date to timestamp:

-- sample data
WITH dataset(x, y) AS (
    VALUES (22,  '2022-01-01')
)

-- query
SELECT date_add('hour', x, cast(date(y) as timestamp))
FROM dataset

Or parse the string as timestamp:

SELECT date_add('hour', x, date_parse(y, '%Y-%m-%d'))
FROM dataset

Output:

_col0

2022-01-01 22:00:00.000


问:
Python - Django - Heroku - ImportError - cannot import name 'fromshare' from 'socket'
I successfully deployed my app to heroku but now I am getting an error:

```<code>ImportError at /
cannot import name 'fromshare' from 'socket' (/app/.heroku/python/lib/python3.9/socket.py)
</code>```

Looks like it traces back to:

```<code>File "/app/users/forms.py" in <module>
  1. from socket import fromshare
</code>```

I have looked everywhere I can online and have not seen anyone run into this. Any idea how I would fix this?

答: Try removing from socket import fromshare from the file. Seeing how it's for a forms.py file, I don't think you need to import that module.

Body:
I successfully deployed my app to heroku but now I am getting an error:

ImportError at /
cannot import name 'fromshare' from 'socket' (/app/.heroku/python/lib/python3.9/socket.py)

Looks like it traces back to:

File "/app/users/forms.py" in <module>
  1. from socket import fromshare

I have looked everywhere I can online and have not seen anyone run into this. Any idea how I would fix this?