问:
"SMTP Error: Could not authenticate" in Phpmailer library
I am trying to this to work using the phpmailer. Unfortunately I keep getting errors. my password contains an ! so I added the \ to allow special characters. My code below.

```<code><?php
//Import PHPMailer classes into the global namespace
//These must be at the top of your script, not inside a function
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;

require_once 'phpmailer/Exception.php';
require_once 'phpmailer/PHPMailer.php';
require_once 'phpmailer/SMTP.php';

//Create an instance; passing `true` enables exceptions
$mail = new PHPMailer(true);
$mail->SMTPOptions = array(
                        'ssl' => array(
                        'verify_peer' => false,
                        'verify_peer_name' => false,
                        'allow_self_signed' => true
                        )
                        );
$alert = '';
if(isset($_POST['submit'])) {
$name = $_POST['name'];
$visitor_email = $_POST['email'];
$message = $_POST['message'];

Try {
    //Server settings
    $mail->isSMTP();
    $mail->CharSet = "UTF-8";
    $mail->Host      = gethostbyname('smtp.gmail.com');   //Set the SMTP server to send through
    //$mail->SMTPDebug = 2;
    $mail->SMTPAuth   = true;                                   //Enable SMTP authentication
    $mail->Username   = 'myemail@gmail.com';                   //SMTP username
    $mail->Password   = 'password\!';                               //SMTP password
    $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
    $mail->Port       = '587';

    $mail->setFrom('myemail@gmail.com');
    $mail->addAddress('myemail@gmail.com'); //Sent email from this
    $mail->isHTML(true);

    $mail->Subject = 'Material Request Form';
    $mail->Body    = '<h3>Name: $name <br>Email: $visitor_email <br>Message: $message </h3>';

    $mail->send();
    $alert = '<div class ="alert-success">
    <span>Message Sent! Thnk you for Contacting us.</span>
    </div>';
   }

   catch (Exception $e){
     $alert = '<div class ="alert-error">
     <span>'.$e->getMessage().'</span>
     </div>';
   }
 }

 ?>
</code>```

I tried many things such as changing to ssl and changing ports, I also know about the secure apps. I have that turned on using Gmail.

答:
You do not need to add a \ before a !. Thats why it fails to authenticate, because the password is wrong.
A backslash removes the "function" of a special character. For example print '\n' would be a line break, however print '\\n' will remove the "function" of the 2nd backslash so it will actually print \n instead of a linebreak.

Body:
I am trying to this to work using the phpmailer. Unfortunately I keep getting errors. my password contains an ! so I added the \ to allow special characters. My code below.

<?php
//Import PHPMailer classes into the global namespace
//These must be at the top of your script, not inside a function
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;

require_once 'phpmailer/Exception.php';
require_once 'phpmailer/PHPMailer.php';
require_once 'phpmailer/SMTP.php';

//Create an instance; passing `true` enables exceptions
$mail = new PHPMailer(true);
$mail->SMTPOptions = array(
                        'ssl' => array(
                        'verify_peer' => false,
                        'verify_peer_name' => false,
                        'allow_self_signed' => true
                        )
                        );
$alert = '';
if(isset($_POST['submit'])) {
$name = $_POST['name'];
$visitor_email = $_POST['email'];
$message = $_POST['message'];

Try {
    //Server settings
    $mail->isSMTP();
    $mail->CharSet = "UTF-8";
    $mail->Host      = gethostbyname('smtp.gmail.com');   //Set the SMTP server to send through
    //$mail->SMTPDebug = 2;
    $mail->SMTPAuth   = true;                                   //Enable SMTP authentication
    $mail->Username   = 'myemail@gmail.com';                   //SMTP username
    $mail->Password   = 'password\!';                               //SMTP password
    $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
    $mail->Port       = '587';

    $mail->setFrom('myemail@gmail.com');
    $mail->addAddress('myemail@gmail.com'); //Sent email from this
    $mail->isHTML(true);

    $mail->Subject = 'Material Request Form';
    $mail->Body    = '
Name: $name
Email: $visitor_email
Message: $message
';

    $mail->send();
    $alert = '

    Message Sent! Thnk you for Contacting us.

';
   }

   catch (Exception $e){
     $alert = '

     '.$e->getMessage().'

';
   }
 }

 ?>

I tried many things such as changing to ssl and changing ports, I also know about the secure apps. I have that turned on using Gmail.


来源: stackexchange

问:
Diskpart batch file with user input selecting disk and partition number
I am trying to creating batch file. How to use user input in selecting partition no? I want to format some partitions only using diskpart. I already learn how to select disk number but I want to learn select  partition number also. Sometimes partition number changed. So how can I user input for selecting partition number?

I am doing below now. But I want at time of selecting partition, it should ask me to select partition number also, but how?

```<code>@echo off

cd /d"%~dp0"
rem == List Disk and List Partitions ======================
echo >diskpart.txt List Disk
diskpart /s diskpart.txt

set /p Disk=Please enter the disk number:
if "%Disk%"=="" goto :eof
echo > diskpart.txt Select disk %disk%
echo >> diskpart.txt list partition
diskpart /s diskpart.txt

echo ============= Please check your Disk and all Partition numbers before continue =============

pause

rem == List Disk Again for Final Confirmation ======================
echo >diskpart.txt List Disk
diskpart /s diskpart.txt

set /p Disk=Please enter the disk number:
if "%Disk%"=="" goto :eof
echo > diskpart.txt Select disk %disk%

rem == 1. Format System partition ======================
echo >> diskpart.txt select partition 1
echo >> diskpart.txt format quick fs=fat32 label="System"

rem == 2. Format Windows partition ========================
echo >> diskpart.txt select partition 3
echo >> diskpart.txt format quick fs=ntfs label="Windows"

rem == 3. Format Recovery tools partition ================
echo >> diskpart.txt select partition 4
echo >> diskpart.txt format quick fs=ntfs label="Recovery"

echo >> diskpart.txt list partition

diskpart /s diskpart.txt

pause
</code>```

答:
(Since I'm a new to stackoverflow I cannot use comment for clarification.)

at time of selecting partition, it should ask me to select partition
Is the first "partition" is ment to be "disk" ?

As I understood you present the user the diskpart output of list disk and want him to select the disk AND the partition at the same time?

Fetch all availabel disks and keep them in a list an than call diskpart for each disk and do list partition. That way the user sees all disks with all their partitions and can enter disk and partition number at once.

```<code>setlocal ENABLEDELAYEDEXPANSION
set DiskList=
for /F "skip=9 tokens=1,2,*" %%A in ('^(echo.list disk^) ^| diskpart') do (
    set DiskList=!DiskList! %%B
)

for %%a in (%DiskList%) do (
    echo.
    echo.Disk %%a
    for /F "skip=12 delims=" %%A in ('^(echo.select disk %%a ^^^& echo.list partition ^) ^| diskpart') do (
        if /i not "%%A" == "DISKPART> " echo.    %%A
    )
)
</code>```

Additionally you may keep track of alls disk and partition numbers like in %DiskList% and verify that the user input makes sense.

With this diskpart-for-loops you could also use detail disk and detail volume after the disk selection to use those informations for further verification.

Another way to select disk and partition at once is to use select volume. This requires the partition to have a drive letter assigned which does not apply to the "System" (boot) partition.

EDIT
You almost found the answer youself. You have already listed the disks and asked the user for a disk number. Do the same for the partition number. The only difference is that you need to select a disk before you can select a partition.

```<code>echo >diskpart.txt List Disk
diskpart /s diskpart.txt
set /p Disk=Please enter the disk number:

rem - listing partition needs a selected disk
echo >diskpart.txt select %Disk%
echo >diskpart.txt list partition
diskpart /s diskpart.txt
set /p Part=Please enter the partition number:

echo >diskpart.txt select %Disk%
echo >diskpart.txt select %Part%
rem - do whatever you want to do, e.g. like
echo >diskpart.txt format ...
diskpart /s diskpart.txt
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am trying to creating batch file. How to use user input in selecting partition no? I want to format some partitions only using diskpart. I already learn how to select disk number but I want to learn select  partition number also. Sometimes partition number changed. So how can I user input for selecting partition number?

I am doing below now. But I want at time of selecting partition, it should ask me to select partition number also, but how?

@echo off

cd /d"%~dp0"
rem == List Disk and List Partitions ======================
echo >diskpart.txt List Disk
diskpart /s diskpart.txt

set /p Disk=Please enter the disk number:
if "%Disk%"=="" goto :eof
echo > diskpart.txt Select disk %disk%
echo >> diskpart.txt list partition
diskpart /s diskpart.txt

echo ============= Please check your Disk and all Partition numbers before continue =============

pause

rem == List Disk Again for Final Confirmation ======================
echo >diskpart.txt List Disk
diskpart /s diskpart.txt

set /p Disk=Please enter the disk number:
if "%Disk%"=="" goto :eof
echo > diskpart.txt Select disk %disk%

rem == 1. Format System partition ======================
echo >> diskpart.txt select partition 1
echo >> diskpart.txt format quick fs=fat32 label="System"

rem == 2. Format Windows partition ========================
echo >> diskpart.txt select partition 3
echo >> diskpart.txt format quick fs=ntfs label="Windows"

rem == 3. Format Recovery tools partition ================
echo >> diskpart.txt select partition 4
echo >> diskpart.txt format quick fs=ntfs label="Recovery"

echo >> diskpart.txt list partition

diskpart /s diskpart.txt

pause

Body:
(Since I'm a new to stackoverflow I cannot use comment for clarification.)

at time of selecting partition, it should ask me to select partition
Is the first "partition" is ment to be "disk" ?

As I understood you present the user the diskpart output of list disk and want him to select the disk AND the partition at the same time?

Fetch all availabel disks and keep them in a list an than call diskpart for each disk and do list partition. That way the user sees all disks with all their partitions and can enter disk and partition number at once.

setlocal ENABLEDELAYEDEXPANSION
set DiskList=
for /F "skip=9 tokens=1,2,*" %%A in ('^(echo.list disk^) ^| diskpart') do (
    set DiskList=!DiskList! %%B
)

for %%a in (%DiskList%) do (
    echo.
    echo.Disk %%a
    for /F "skip=12 delims=" %%A in ('^(echo.select disk %%a ^^^& echo.list partition ^) ^| diskpart') do (
        if /i not "%%A" == "DISKPART> " echo.    %%A
    )
)

Additionally you may keep track of alls disk and partition numbers like in %DiskList% and verify that the user input makes sense.

With this diskpart-for-loops you could also use detail disk and detail volume after the disk selection to use those informations for further verification.

Another way to select disk and partition at once is to use select volume. This requires the partition to have a drive letter assigned which does not apply to the "System" (boot) partition.

EDIT
You almost found the answer youself. You have already listed the disks and asked the user for a disk number. Do the same for the partition number. The only difference is that you need to select a disk before you can select a partition.

echo >diskpart.txt List Disk
diskpart /s diskpart.txt
set /p Disk=Please enter the disk number:

rem - listing partition needs a selected disk
echo >diskpart.txt select %Disk%
echo >diskpart.txt list partition
diskpart /s diskpart.txt
set /p Part=Please enter the partition number:

echo >diskpart.txt select %Disk%
echo >diskpart.txt select %Part%
rem - do whatever you want to do, e.g. like
echo >diskpart.txt format ...
diskpart /s diskpart.txt


问:
Action mode bar pushing down the Toolbar
In my app I'm using the Toolbar as explained in the official documentation (v7 appcompat support library, Theme.Appcompat.Light.NoActionBar, android.support.v7.widget.Toolbar, setSupportActionBar(myToolbar)):
http://developer.android.com/training/appbar/index.html

I have an ExpandableListView and I'd like to implement the contextual action mode when I long-click on an item. To achieve this I use:
setMultiChoiceModeListener(new MultiChoiceModeListener()).
This way, however, the action mode bar is displayed at the top of the screen, pushing down the Toolbar (I think it's because the system uses the ordinary action mode, and not the support action mode). I want it to be displayed on the Toolbar.

I tried this solution:

```<code>windowActionBarOverlay = true
</code>```

but it doesn't work.

答:
This worked for me...
If you are using custom toolbar, then instead of removing the default toolbar from manifest using   android:theme="@style/Theme.Design.NoActionBar" try

```<code> <style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
   <item name="windowActionBarOverlay">true</item>
 </style>
</code>```

in styles and remove that code from Manifest file.

Body:
In my app I'm using the Toolbar as explained in the official documentation (v7 appcompat support library, Theme.Appcompat.Light.NoActionBar, android.support.v7.widget.Toolbar, setSupportActionBar(myToolbar)):
http://developer.android.com/training/appbar/index.html

I have an ExpandableListView and I'd like to implement the contextual action mode when I long-click on an item. To achieve this I use:
setMultiChoiceModeListener(new MultiChoiceModeListener()).
This way, however, the action mode bar is displayed at the top of the screen, pushing down the Toolbar (I think it's because the system uses the ordinary action mode, and not the support action mode). I want it to be displayed on the Toolbar.

I tried this solution:

windowActionBarOverlay = true

but it doesn't work.

Body:
This worked for me...
If you are using custom toolbar, then instead of removing the default toolbar from manifest using   android:theme="@style/Theme.Design.NoActionBar" try

 <style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
   <item name="windowActionBarOverlay">true</item>
 </style>

in styles and remove that code from Manifest file.


问:
InstallShield 2011 Immediate execution in System Context
I want to write a custom action which will execute above all other custom actions and execute in system context. If I use "immediate execution" then it executes in logged in users context and if I use "deferred execution in system context" then this custom action executes after other custom actions. What should I do to handle this kind of scenario?</p>

答:
Only deferred actions can be executed in system context. It is executed at its scheduled sequence between other deferred actions. If this action must be the first action run, you would need a bootstrapper which will elevate permissions and the start your installation.

Note also: Deferred actions have very limited access to the properties of the install.

ContentLicense: CC BY-SA 3.0


问:
How many official xbrl concepts in its term?
A taxonomy element that provides the meaning for a fact. For example, "Profit", "Turnover", and "Assets" would be typical concepts.

https://www.xbrl.org/guidance/xbrl-glossary/

How many xbrl concepts in the specified company?Call it in a company with sec's api.

https://data.sec.gov/api/xbrl/companyfacts/CIK0001318605.json

```<code>def number_concept_used(cik):
    import requests
    url = 'https://data.sec.gov/api/xbrl/companyfacts/CIK{:>010s}.json'.format(cik)
    headers = {
        "User-Agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/95.0.4638.69 Safari/537.36"
              }
    #call sec's RESTful api
    res = requests.get(url=url,headers=headers)
    result = res.json()
    data = result['facts']['us-gaap']
    concepts = data.keys()
    return len(concepts)
</code>```

Now call the function written in python:

```<code>number_concept_used('1318605')
552
number_concept_used('320193')
486
</code>```

There are 552 official xbrl concepts in tesla's financial statements,486 official xbrl concepts in apple's financial statements.Different company use different official xbrl concepts in their financial statement.I have find the webpage where we can search xbrl concept :

```<code>https://xbrlview.fasb.org/yeti/resources/yeti-gwt/Yeti.jsp#tax~(id~174*v~7350)!net~(a~3474*l~832)!lang~(code~en-us)!rg~(rg~32*p~12)
</code>```

It does not tell the total numbers.How many offical xbrl concepts in all listed companies?Or say,how many xbrl concepts shared by all listed companies exclude customized concept by company itself?

答:
Maybe it is 7300 or more,i am a bit sure,downloaded financial statement data set on 2020 ,create a database and num table to store num.txt file ,extract the downloaded file and write num.txt into num table.

https://www.sec.gov/dera/data/financial-statement-data-sets.html

Enter the database:

```<code>select distinct(tag) from num where version='us-gaap/2020';
7300
</code>```

I want to get the official handbook which listing all these concepts,where is it?

Body:
A taxonomy element that provides the meaning for a fact. For example, "Profit", "Turnover", and "Assets" would be typical concepts.

https://www.xbrl.org/guidance/xbrl-glossary/

How many xbrl concepts in the specified company?Call it in a company with sec's api.

https://data.sec.gov/api/xbrl/companyfacts/CIK0001318605.json

def number_concept_used(cik):
    import requests
    url = 'https://data.sec.gov/api/xbrl/companyfacts/CIK{:>010s}.json'.format(cik)
    headers = {
        "User-Agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/95.0.4638.69 Safari/537.36"
              }
    #call sec's RESTful api
    res = requests.get(url=url,headers=headers)
    result = res.json()
    data = result['facts']['us-gaap']
    concepts = data.keys()
    return len(concepts)

Now call the function written in python:

number_concept_used('1318605')
552
number_concept_used('320193')
486

There are 552 official xbrl concepts in tesla's financial statements,486 official xbrl concepts in apple's financial statements.Different company use different official xbrl concepts in their financial statement.I have find the webpage where we can search xbrl concept :

https://xbrlview.fasb.org/yeti/resources/yeti-gwt/Yeti.jsp#tax~(id~174*v~7350)!net~(a~3474*l~832)!lang~(code~en-us)!rg~(rg~32*p~12)

It does not tell the total numbers.How many offical xbrl concepts in all listed companies?Or say,how many xbrl concepts shared by all listed companies exclude customized concept by company itself?

Body:
Maybe it is 7300 or more,i am a bit sure,downloaded financial statement data set on 2020 ,create a database and num table to store num.txt file ,extract the downloaded file and write num.txt into num table.

https://www.sec.gov/dera/data/financial-statement-data-sets.html

Enter the database:

select distinct(tag) from num where version='us-gaap/2020';
7300

I want to get the official handbook which listing all these concepts,where is it?


问:
How can I detect whether a tooltip is visible at a given moment?
I'm looking for a way to detect whether a Qt widget's ToolTip is visible at the moment when a particular key combination is pressed. If it is, I want to copy the ToolTip's text to the clipboard.

Specifically, I have a QListView containing abbreviated strings, which is set up (via the Qt::ToolTipRole of the associated model) to show the full string of the appropriate list item when the mouse is hovered over it. The behaviour I'm looking for is that if the user presses CTRL-C (as detected by a QShortcut) while the tooltip is visible, then the tooltip text is copied to the clipboard.

My original idea was to use the children() method of the QListView widget to see if there was a tooltip preset among them:

```<code>// Inisde the slot connected to QShortcut::activated...
auto children = _ui -> myListView -> children();
QString selectionText;
for (const auto & child : children)
{
    if (qobject_cast<QToolTip *>(child))
    {
        selectionText = qobject_cast<QToolTip *>(child) -> text();
        break;
    }
}
</code>```

...but this failed because it turns out that QToolTip does not inherit from QObject.

I've also thought of screening for QEvent::QToolTip events in the ListView's main event handler, and while I could probably get this to work it seems excessively low-level; I'd need to use screen co-ordinates to determine which item in the list was being hovered over and look for the widget's timeout to check that the tooltip hadn't disappeared again by the time that the QShortcut was fired. I'd be disappointed if there weren't a simpler way.

Is there an obvious way forward that I've failed to see?

答:
There are probably several possible solutions, but I am afraid none of them is simple. What I would do is to use the implementation detail that the tooltip actual widget is called QTipLabel. See https://code.woboq.org/qt5/qtbase/src/widgets/kernel/qtooltip.cpp.html#QTipLabel and it inherits from QLabel so you can easily get the text from it.

I am afraid the following solution is just a savage hack. I have not tested it, but it should work.

I would override the data model for your view, specifically override method data() which would call the data() method of the original model class but cache the last value which was returned when this method is called with role == Qt::ToolTipRole.

Then you need to catch the shortcut you are interested in. After it is caught, you get all qApp->topLevelWidgets() https://doc.qt.io/qt-5/qapplication.html#topLevelWidgets` and go through them and check if any of them has class name equal to QTipLabel (use QMetaObject::className()) and is visible, i.e. isVisible() == true.

If you get this visible QTipLabel widget (you hold it via QWidget*), qobject_cast it to QLabel* (you cannot cast it to QTipLabel beause you do not have access to the definition of QTipLabel class because it is in private Qt source file) and get the text with QLabel::text(). If the text is the same as the text which you stored in step 1, then yes, this is the text you are looking for and you can copy it to clipboard or do whatever yo want with it.

Nasty, isn't it? But it is the simplest what I can think of.

PS: I believe that step 1 can be implemented also by catching QEvent::QToolTip for your view and then do some magic to get the text, but I think that overriding data() for model can be a bit easier.

PPS: One obvious drawback is that Qt can rename QTipLabel class in the future. But I would not be worry about it. That won't happen becaus ethey do not change QtWidgets module any more. And if it happens, then you just rename the class in your code. No problem.

PPPS: Another potential corner-case is that some other widget (whose tooltip you do NOT want to capture with that shortcut) actually has the same tooltip text as any of the items in your list view (which you DO want to capture). Then if you display tooltip for your list item, then you move your mouse over to that other widget and hover so that its tooltip gets shown (but you do NOT want to capture it) and then you press that shortcut... But I guess that in reality this will not be your case. I doubt there will be this unlikely clash of tooltips.

Body:
I'm looking for a way to detect whether a Qt widget's ToolTip is visible at the moment when a particular key combination is pressed. If it is, I want to copy the ToolTip's text to the clipboard.

Specifically, I have a QListView containing abbreviated strings, which is set up (via the Qt::ToolTipRole of the associated model) to show the full string of the appropriate list item when the mouse is hovered over it. The behaviour I'm looking for is that if the user presses CTRL-C (as detected by a QShortcut) while the tooltip is visible, then the tooltip text is copied to the clipboard.

My original idea was to use the children() method of the QListView widget to see if there was a tooltip preset among them:

// Inisde the slot connected to QShortcut::activated...
auto children = _ui -> myListView -> children();
QString selectionText;
for (const auto & child : children)
{
    if (qobject_cast<QToolTip *>(child))
    {
        selectionText = qobject_cast<QToolTip *>(child) -> text();
        break;
    }
}

...but this failed because it turns out that QToolTip does not inherit from QObject.

I've also thought of screening for QEvent::QToolTip events in the ListView's main event handler, and while I could probably get this to work it seems excessively low-level; I'd need to use screen co-ordinates to determine which item in the list was being hovered over and look for the widget's timeout to check that the tooltip hadn't disappeared again by the time that the QShortcut was fired. I'd be disappointed if there weren't a simpler way.

Is there an obvious way forward that I've failed to see?


问:
Handle back button actions inside android fragments
i needed to override the default back button behavior so that i could go to the previous fragment instead of closing the entire application.

Below is the implementation of this function

```<code>class DataFragment : Fragment() {

private lateinit var fragment: Fragment
private lateinit var fm: FragmentManager
private lateinit var transaction: FragmentTransaction

override fun onCreateView(
    inflater: LayoutInflater,
    @Nullable container: ViewGroup?,
    savedInstanceState: Bundle?
): View {
    requireActivity().onBackPressedDispatcher.addCallback(viewLifecycleOwner,object : OnBackPressedCallback(true){
        override fun handleOnBackPressed() {
            fragment = PreviousFragment()
            fm = parentFragmentManager
            transaction = fm.beginTransaction()
            transaction.replace(R.id.contentFragment, fragment)
            transaction.commit()
        }
    })
return binding.rootView
 }
}
</code>```

答:
When you perform a FragmentTransaction, you can call addToBackStack to put that transaction on the back stack. When the user hits the back button, the last transaction on the stack is popped off, and all the changes in that transaction are reverted.

So if a transaction replaces Fragment A with Fragment B, and also adds Fragment C, popping that transaction with the back button (or popBackStack()) will undo that and restore it back to how it was, with just Fragment A. So you can build up specific history states the user can step back through (like a web browser) and control exactly what the back button does.

You can also provide a label with addToBackStack (use null if you don't care),
and then call popBackStack with that label to jump back to that transaction (or the one before it) in one go. So you can create a workflow where the user can back through steps one at a time, or hit a button that jumps right back to a specific step you've marked, like the start of some task, or an overview, etc

Body:
i needed to override the default back button behavior so that i could go to the previous fragment instead of closing the entire application.

Below is the implementation of this function

class DataFragment : Fragment() {

private lateinit var fragment: Fragment
private lateinit var fm: FragmentManager
private lateinit var transaction: FragmentTransaction

override fun onCreateView(
    inflater: LayoutInflater,
    @Nullable container: ViewGroup?,
    savedInstanceState: Bundle?
): View {
    requireActivity().onBackPressedDispatcher.addCallback(viewLifecycleOwner,object : OnBackPressedCallback(true){
        override fun handleOnBackPressed() {
            fragment = PreviousFragment()
            fm = parentFragmentManager
            transaction = fm.beginTransaction()
            transaction.replace(R.id.contentFragment, fragment)
            transaction.commit()
        }
    })
return binding.rootView
 }
}


问:
MonetDB Crashes When Connecting. Will Not Restart. Large Logs
I recently migrated an instance of MonetDB to a machine with a more memory and a larger hard drive by transferring a machine image from one location to another. The database worked briefly but now when attempting to connect with mclient I get the following error:

$ mclient warehouse
user(monetdb):monetdb
password:
monetdbd: internal error while starting mserver 'database 'warehouse' has crashed after starting, manual intervention needed, check monetdbd's logfile (merovingian.log) for details'
```
<p>Upon checking merovingian.log I can see that the database started, but crashed when mclient attempted to connect:</p>
<pre class="lang-sh prettyprint-override"><code>2022-02-09 14:11:29 MSG merovingian[4368]: database 'warehouse' has crashed after start on 2022-02-09 14:03:23, attempting restart, up min/avg/max: 2m/6w/22w, crash average: 1.00 1.00 0.97 (135-6=129)
</code>```

The database then attempts to restart and appears normal until attempting to read through something referred to the write-ahead log.

2022-02-09 14:11:29 MSG warehouse[4403]: arguments:
2022-02-09 14:11:29 MSG warehouse[4403]: /usr/bin/mserver5 --dbpath=/home/db_user/monetDBDatabase/warehouse/warehouse --set merovingian_uri=mapi:monetdb://dev:50000/warehouse --set mapi_listenaddr=none --set mapi_usock=/home/db_user/monetDBDatabase/warehouse/warehouse/.mapi.sock --set monet_vault_key=/home/db_user/monetDBDatabase/warehouse/warehouse/.vaultkey --set
2022-02-09 14:11:29 MSG warehouse[4403]: gdk_nr_threads=36 --set max_clients=64 --set sql_optimizer=default_pipe
2022-02-09 14:11:40 MSG warehouse[4403]: # MonetDB 5 server v11.39.17 (Oct2020-SP5)
2022-02-09 14:11:40 MSG warehouse[4403]: # Serving database 'warehouse', using 36 threads
2022-02-09 14:11:40 MSG warehouse[4403]: # Compiled for x86_64-pc-linux-gnu/64bit with 128bit integers
2022-02-09 14:11:40 MSG warehouse[4403]: # Found 125.609 GiB available main-memory of which we use 102.371 GiB
2022-02-09 14:11:40 MSG warehouse[4403]: # Copyright (c) 1993 - July 2008 CWI.
2022-02-09 14:11:40 MSG warehouse[4403]: # Copyright (c) August 2008 - 2021 MonetDB B.V., all rights reserved
2022-02-09 14:11:40 MSG warehouse[4403]: # Visit https://www.monetdb.org/ for further information
2022-02-09 14:11:40 MSG warehouse[4403]: # Listening for UNIX domain connection requests on mapi:monetdb:///home/db_user/monetDBDatabase/warehouse/warehouse/.mapi.sock
2022-02-09 14:11:40 MSG warehouse[4403]: # still reading write-ahead log "/home/db_user/monetDBDatabase/warehouse/warehouse/sql_logs/sql/log.95638" (22% done)
2022-02-09 14:11:51 MSG warehouse[4403]: # still reading write-ahead log "/home/db_user/monetDBDatabase/warehouse/warehouse/sql_logs/sql/log.95638" (44% done)
2022-02-09 14:12:02 MSG warehouse[4403]: # still reading write-ahead log "/home/db_user/monetDBDatabase/warehouse/warehouse/sql_logs/sql/log.95638" (67% done)
```
<p>This process continues until the system appears to run out of virtual memory as seen in the log extract below:</p>
<pre class="lang-sh prettyprint-override"><code>2022-02-09 14:18:52 MSG warehouse[4403]: # still reading write-ahead log "/home/db_user/monetDBDatabase/warehouse/warehouse/sql_logs/sql/log.95650" (92% done)
2022-02-09 14:18:56 ERR warehouse[4403]: #main thread: GDKmmap: !ERROR: requested too much virtual memory; memory requested: 43317329920, memory in use: 208390400, virtual memory in use: 4354888091904
</code>```

I've monitored the system throughout this and the memory usage is well within acceptable limits with the most being used about 1GB out of 126GB. What is strange is the size of the files being produced by MonetDB.

The original database was about 5Tb in size, although I can also see that the write-ahead log(s) found in warehouse/sql_logs/sql are 65GB with another file warehouse/mdbtrace.log taking up another 5Tb.

If I try to remove the write-ahead log(s) then the database does not start citing that the files are missing and the same for mdbtrace.log (I can recreate and post the exact messages if required). Other than this I've tried rebooting the machine. I get the impression that the large size of mdbtrace.log is preventing the virtual memory space to read the write-ahead log(s) by using up space that is needed for virtual memory.

Any assistance in solving these errors so that I can start and connect to the database with mclient would be most appreciated.

Regards,

James

答: First of all, the file mdbtrace.log is not part of the database, so it can be (re)moved.  What is part of the database is the write-ahead log, the files in the sql_logs directory.  Those are the ones that are being processed during startup.

Body:
I recently migrated an instance of MonetDB to a machine with a more memory and a larger hard drive by transferring a machine image from one location to another. The database worked briefly but now when attempting to connect with mclient I get the following error:

$ mclient warehouse
user(monetdb):monetdb
password:
monetdbd: internal error while starting mserver 'database 'warehouse' has crashed after starting, manual intervention needed, check monetdbd's logfile (merovingian.log) for details'

Upon checking merovingian.log I can see that the database started, but crashed when mclient attempted to connect:

2022-02-09 14:11:29 MSG merovingian[4368]: database 'warehouse' has crashed after start on 2022-02-09 14:03:23, attempting restart, up min/avg/max: 2m/6w/22w, crash average: 1.00 1.00 0.97 (135-6=129)

The database then attempts to restart and appears normal until attempting to read through something referred to the write-ahead log.

2022-02-09 14:11:29 MSG warehouse[4403]: arguments:
2022-02-09 14:11:29 MSG warehouse[4403]: /usr/bin/mserver5 --dbpath=/home/db_user/monetDBDatabase/warehouse/warehouse --set merovingian_uri=mapi:monetdb://dev:50000/warehouse --set mapi_listenaddr=none --set mapi_usock=/home/db_user/monetDBDatabase/warehouse/warehouse/.mapi.sock --set monet_vault_key=/home/db_user/monetDBDatabase/warehouse/warehouse/.vaultkey --set
2022-02-09 14:11:29 MSG warehouse[4403]: gdk_nr_threads=36 --set max_clients=64 --set sql_optimizer=default_pipe
2022-02-09 14:11:40 MSG warehouse[4403]: # MonetDB 5 server v11.39.17 (Oct2020-SP5)
2022-02-09 14:11:40 MSG warehouse[4403]: # Serving database 'warehouse', using 36 threads
2022-02-09 14:11:40 MSG warehouse[4403]: # Compiled for x86_64-pc-linux-gnu/64bit with 128bit integers
2022-02-09 14:11:40 MSG warehouse[4403]: # Found 125.609 GiB available main-memory of which we use 102.371 GiB
2022-02-09 14:11:40 MSG warehouse[4403]: # Copyright (c) 1993 - July 2008 CWI.
2022-02-09 14:11:40 MSG warehouse[4403]: # Copyright (c) August 2008 - 2021 MonetDB B.V., all rights reserved
2022-02-09 14:11:40 MSG warehouse[4403]: # Visit https://www.monetdb.org/ for further information
2022-02-09 14:11:40 MSG warehouse[4403]: # Listening for UNIX domain connection requests on mapi:monetdb:///home/db_user/monetDBDatabase/warehouse/warehouse/.mapi.sock
2022-02-09 14:11:40 MSG warehouse[4403]: # still reading write-ahead log "/home/db_user/monetDBDatabase/warehouse/warehouse/sql_logs/sql/log.95638" (22% done)
2022-02-09 14:11:51 MSG warehouse[4403]: # still reading write-ahead log "/home/db_user/monetDBDatabase/warehouse/warehouse/sql_logs/sql/log.95638" (44% done)
2022-02-09 14:12:02 MSG warehouse[4403]: # still reading write-ahead log "/home/db_user/monetDBDatabase/warehouse/warehouse/sql_logs/sql/log.95638" (67% done)

This process continues until the system appears to run out of virtual memory as seen in the log extract below:

2022-02-09 14:18:52 MSG warehouse[4403]: # still reading write-ahead log "/home/db_user/monetDBDatabase/warehouse/warehouse/sql_logs/sql/log.95650" (92% done)
2022-02-09 14:18:56 ERR warehouse[4403]: #main thread: GDKmmap: !ERROR: requested too much virtual memory; memory requested: 43317329920, memory in use: 208390400, virtual memory in use: 4354888091904

I've monitored the system throughout this and the memory usage is well within acceptable limits with the most being used about 1GB out of 126GB. What is strange is the size of the files being produced by MonetDB.

The original database was about 5Tb in size, although I can also see that the write-ahead log(s) found in warehouse/sql_logs/sql are 65GB with another file warehouse/mdbtrace.log taking up another 5Tb.

If I try to remove the write-ahead log(s) then the database does not start citing that the files are missing and the same for mdbtrace.log (I can recreate and post the exact messages if required). Other than this I've tried rebooting the machine. I get the impression that the large size of mdbtrace.log is preventing the virtual memory space to read the write-ahead log(s) by using up space that is needed for virtual memory.

Any assistance in solving these errors so that I can start and connect to the database with mclient would be most appreciated.

Regards,

James


问:
Mapping where clause generic type (of SelectConditionStep) to my own class in jooq
So I have an abstract class that prepares my query up to after where clause. It looks something like this:

SelectConditionStep<Record2<Integer, String>> whereQuery = dslContext.select(FOO.DIGITS, FOO.WORD)
                                                                .from(FOO)
                                                                .where(/*some conditions*/);
```

It then returns whereQuery and that instance is used by concrete implementations to add stuff onto it.

Is it possible to make this call return SelectConditionStep<MyClass> so that I don't have to write all Record types in method signature (note that this is a simplified version, imagine having Record10). MyClass would, in this example, have two fields, Integer and String fields.
Or if not that, is there any other way to do it.

I am using Postgres as a db

答:
Assuming you have an immutable POJO MyClass, e.g. a Java 16 record:

record MyClass(int digits, String word) {}
```
<p>You could use a nested record to achieve something similar:</p>
<pre class="lang-java prettyprint-override"><code>Select<Record1<MyClass>> whereQuery =
ctx.select(row(FOO.DIGITS, FOO.WORD).mapping(MyClass::new))
   .from(FOO)
   .where(...)
</code>```

Body:
So I have an abstract class that prepares my query up to after where clause. It looks something like this:

SelectConditionStep<Record2<Integer, String>> whereQuery = dslContext.select(FOO.DIGITS, FOO.WORD)
                                                                .from(FOO)
                                                                .where(/*some conditions*/);

It then returns whereQuery and that instance is used by concrete implementations to add stuff onto it.

Is it possible to make this call return SelectConditionStep<MyClass> so that I don't have to write all Record types in method signature (note that this is a simplified version, imagine having Record10). MyClass would, in this example, have two fields, Integer and String fields.
Or if not that, is there any other way to do it.

I am using Postgres as a db

Body:
Assuming you have an immutable POJO MyClass, e.g. a Java 16 record:

record MyClass(int digits, String word) {}

You could use a nested record to achieve something similar:

Select<Record1<MyClass>> whereQuery =
ctx.select(row(FOO.DIGITS, FOO.WORD).mapping(MyClass::new))
   .from(FOO)
   .where(...)


问:
How to plot a Pandas dataframe by filtering a column
I have the following Pandas df:

And I want to generate seven different histogram plots according to the weekday to show the attendance to a place in each hour of the day.

Thanks.

答:
Here is an example for the weekday friday:</p>
```<code>import matplotlib.pyplot as plt

plt.bar(x = 'at_what_time', height = 'visit_weight', data = df[df['weekday']=='friday'])
</code>```

Body:
Here is an example for the weekday friday:

import matplotlib.pyplot as plt

plt.bar(x = 'at_what_time', height = 'visit_weight', data = df[df['weekday']=='friday'])


问:
Adding two complex numbers using java generics
Below i have been given a class 'Fclass' according to which i have to create constructors and methods which i have done above the 'Fclass' but i am constantly getting error in the 'add' method in which i have to return sum of two complex numbers. Can someone please point out where am i going wrong? Format of returning value is '10.0 + 20.0i + 13.3 + 5.12i = 23.3 + 25.12i'</p>
```<code>import java.util.Scanner;
class ComplexNum<T>{
        T r;
        T i;
        public ComplexNum(T r2,T i2) {
            this.r = r2;
            this.i = i2;
        }

        public ComplexNum<Double> add(ComplexNum<Double> c2){
            ComplexNum<Double> res = new ComplexNum(r, i);
            res.r =  r +c2.r;
            res.i = i + c2.i
            return res;

        }
        public String toString() {
            return r + "+" + i + "i";
        }

    }

 class FClass{
    public static void main(String[] args) {
            Scanner sc = new Scanner(System.in);
            int n1, n2;
            double d1, d2;
            n1 = sc.nextInt();
            n2 = sc.nextInt();
            d1 = sc.nextDouble();
            d2 = sc.nextDouble();
            ComplexNum<Integer> c1 = new ComplexNum<Integer>(n1, n2);
            ComplexNum<Double> c2 = new ComplexNum<Double>(d1, d2);
            ComplexNum<Double> c3 = c1.add(c2);
            System.out.println(c1 + " + " + c2 + " = " + c3);
        }
    }
</code>```

答:
First, you need to constraint T to subtype of Number.  Number can be Integer or Double.  Only then, you can actually retrieve the values from r and i.

See below:

```<code>class ComplexNum < T extends Number > {
  private T r;
  private T i;

  public ComplexNum (T r2, T i2){
    this.r = r2;
    this.i = i2;
  }

  public ComplexNum < Double > add (ComplexNum < T > c){
    return new ComplexNum < Double > (
                  r.doubleValue () + c.r.doubleValue (),
                      i.doubleValue () + c.i.doubleValue ()
                  );
  }

  public String toString (){
    return r + "+" + i + "i";
  }
}

public class Main{
  public static void main (String[]args){
    ComplexNum < Integer > c1 = new ComplexNum <> (2, 3);
    ComplexNum < Integer > c2 = new ComplexNum <> (1, 2);
    ComplexNum < Double > c3 = c1.add (c2);
    System.out.println (c1);
  }
}
</code>```

Body:
Below i have been given a class 'Fclass' according to which i have to create constructors and methods which i have done above the 'Fclass' but i am constantly getting error in the 'add' method in which i have to return sum of two complex numbers. Can someone please point out where am i going wrong? Format of returning value is '10.0 + 20.0i + 13.3 + 5.12i = 23.3 + 25.12i'

import java.util.Scanner;
class ComplexNum<T>{
        T r;
        T i;
        public ComplexNum(T r2,T i2) {
            this.r = r2;
            this.i = i2;
        }

        public ComplexNum<Double> add(ComplexNum<Double> c2){
            ComplexNum<Double> res = new ComplexNum(r, i);
            res.r =  r +c2.r;
            res.i = i + c2.i
            return res;

        }
        public String toString() {
            return r + "+" + i + "i";
        }

    }

 class FClass{
    public static void main(String[] args) {
            Scanner sc = new Scanner(System.in);
            int n1, n2;
            double d1, d2;
            n1 = sc.nextInt();
            n2 = sc.nextInt();
            d1 = sc.nextDouble();
            d2 = sc.nextDouble();
            ComplexNum<Integer> c1 = new ComplexNum<Integer>(n1, n2);
            ComplexNum<Double> c2 = new ComplexNum<Double>(d1, d2);
            ComplexNum<Double> c3 = c1.add(c2);
            System.out.println(c1 + " + " + c2 + " = " + c3);
        }
    }

Body:
First, you need to constraint T to subtype of Number.  Number can be Integer or Double.  Only then, you can actually retrieve the values from r and i.

See below:

class ComplexNum < T extends Number > {
  private T r;
  private T i;

  public ComplexNum (T r2, T i2){
    this.r = r2;
    this.i = i2;
  }

  public ComplexNum < Double > add (ComplexNum < T > c){
    return new ComplexNum < Double > (
                  r.doubleValue () + c.r.doubleValue (),
                      i.doubleValue () + c.i.doubleValue ()
                  );
  }

  public String toString (){
    return r + "+" + i + "i";
  }
}

public class Main{
  public static void main (String[]args){
    ComplexNum < Integer > c1 = new ComplexNum <> (2, 3);
    ComplexNum < Integer > c2 = new ComplexNum <> (1, 2);
    ComplexNum < Double > c3 = c1.add (c2);
    System.out.println (c1);
  }
}


问:
Why does my `#If Not Win64 Then` code get executed on 32-bit Office?
I have the following code which I only want executed on 32-bit Office (not 64-bit Office):

```<code>#If Not Win64 Then
    DoSomethingOnlyIn32BitOffice
#End If
</code>```

According to the documentation, the compile-time constant Win64 should be True in 64-bit Office. However, debugging this code in 64-bit Office (tested with 2016) confirms that DoSomethingOnlyIn32BitOffice is actually called. What did I do wrong?

答:
You found a bug in the documentation.

The documentation claims that the VBA compile-time constants Win64, Win32, etc. are initialized to either True of False. This, however, seems to be incorrect. Consider the following example code:

```<code>#If Win32 Then
    Debug.Print "Win32"
#End If
#If Not Win32 Then
    Debug.Print "Not Win32"
#End If
#If Win32 = True Then
    Debug.Print "Win32 = True"
#End If
#If Win32 = False Then
    Debug.Print "Win32 = False"
#End If
#If Win32 = 1 Then
    Debug.Print "Win32 = 1"
#End If
#If Win32 = 2 Then
    Debug.Print "Win32 = 2"
#End If
</code>```

which yields the following result in Office 2016 (32-bit):

```<code>Win32
Not Win32
Win32 = 1
</code>```

Apparently, those constants are set to 1 when "truth-y", not to -1 (= the VBA True value). This is inconvenient, since it leads to both #If Not Win32 and #If Win32 = True doing something completely different than the developer intended.

My suggested fix would be to write

```<code>#If Win64 Then
    ' No action needed in 64-Bit Office
#Else
    DoSomethingOnlyIn32BitOffice
#End If
</code>```

instead, since all the other options (Win64 <> 1, etc.) rely on the (undocumented) fact that the "truth-y" value is 1.

Body:
I have the following code which I only want executed on 32-bit Office (not 64-bit Office):

#If Not Win64 Then
    DoSomethingOnlyIn32BitOffice
#End If

According to the documentation, the compile-time constant Win64 should be True in 64-bit Office. However, debugging this code in 64-bit Office (tested with 2016) confirms that DoSomethingOnlyIn32BitOffice is actually called. What did I do wrong?

Body:
You found a bug in the documentation.

The documentation claims that the VBA compile-time constants Win64, Win32, etc. are initialized to either True of False. This, however, seems to be incorrect. Consider the following example code:

#If Win32 Then
    Debug.Print "Win32"
#End If
#If Not Win32 Then
    Debug.Print "Not Win32"
#End If
#If Win32 = True Then
    Debug.Print "Win32 = True"
#End If
#If Win32 = False Then
    Debug.Print "Win32 = False"
#End If
#If Win32 = 1 Then
    Debug.Print "Win32 = 1"
#End If
#If Win32 = 2 Then
    Debug.Print "Win32 = 2"
#End If

which yields the following result in Office 2016 (32-bit):

Win32
Not Win32
Win32 = 1

Apparently, those constants are set to 1 when "truth-y", not to -1 (= the VBA True value). This is inconvenient, since it leads to both #If Not Win32 and #If Win32 = True doing something completely different than the developer intended.

My suggested fix would be to write

#If Win64 Then
    ' No action needed in 64-Bit Office
#Else
    DoSomethingOnlyIn32BitOffice
#End If

instead, since all the other options (Win64 <> 1, etc.) rely on the (undocumented) fact that the "truth-y" value is 1.


问:
Why am I getting repetitive output while trying to scrape data from Google Scholar?
I am trying to scrape the PDF links from the search results from Google Scholar. I have tried to set a page counter based on the change in URL, but after the first eight output links, I am getting repetitive links as output.</p>

```<code>#!/usr/bin/env python
from mechanize import Browser
from BeautifulSoup import BeautifulSoup
from bs4 import BeautifulSoup
import urllib2
import requests

#modifying the url as per page
urlCounter = 0
while urlCounter <=30:
    urlPart1 = "http://scholar.google.com/scholar?start="
    urlPart2 = "&q=%22entity+resolution%22&hl=en&as_sdt=0,4"
    url = urlPart1 + str(urlCounter) + urlPart2
    page = urllib2.Request(url,None,{"User-Agent":"Mozilla/5.0 (X11; U; Linux i686) Gecko/20071127 Firefox/2.0.0.11"})
    resp = urllib2.urlopen(page)
    html = resp.read()
    soup = BeautifulSoup(html)
    urlCounter = urlCounter + 10

    recordCount = 0
    while recordCount <=9:
        recordPart1 = "gs_ggsW"
        finRecord = recordPart1 + str(recordCount)
        recordCount = recordCount+1

    #printing the links
        for link in soup.find_all('div', id = finRecord):
            linkstring = str(link)
            soup1 = BeautifulSoup(linkstring)
        for link in soup1.find_all('a'):
            print(link.get('href'))
</code>```

答:
Have a look at the SelectorGadget Chrome extension to grab CSS selectors by clicking on the desired element in your browser.

Code and example in the online IDE to extract PDF's:

from bs4 import BeautifulSoup
import requests, lxml

params = {
    "q": "entity resolution", # search query
    "hl": "en"                # language
}

# https://requests.readthedocs.io/en/master/user/quickstart/#custom-headers
headers = {
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3538.102 Safari/537.36 Edge/18.19582",
}

html = requests.get("https://scholar.google.com/scholar", params=params, headers=headers, timeout=30)
soup = BeautifulSoup(html.text, "lxml")

for pdf_link in soup.select(".gs_or_ggsm a"):
  pdf_file_link = pdf_link["href"]
  print(pdf_file_link)

# output from the first page:
'''
https://linqs.github.io/linqs-website/assets/resources/getoor-vldb12-slides.pdf
http://ilpubs.stanford.edu:8090/859/1/2008-7.pdf
https://drum.lib.umd.edu/bitstream/handle/1903/4241/umi-umd-4070.pdf;sequence=1
https://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.169.9535&rep=rep1&type=pdf
https://arxiv.org/pdf/1208.1927
https://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.77.6875&rep=rep1&type=pdf
http://da.qcri.org/ntang/pubs/vldb18-deeper.pdf
'''
```
<hr />
<p>Alternatively, you can achieve the same thing by using Google Scholar Organic Results API from SerpApi. It's a paid API with a free plan.</p>
<p>The main difference is that you only need to grab the data from structured JSON instead of figuring out how to extract the data from HTML, how to bypass blocks from search engines.</p>
<p>Code to integrate:</p>
<pre class="lang-py prettyprint-override"><code>from serpapi import GoogleSearch

params = {
    "api_key": "YOUR_API_KEY",   # SerpApi API key
    "engine": "google_scholar",  # Google Scholar organic reuslts
    "q": "entity resolution",    # search query
    "hl": "en"                   # language
}

search = GoogleSearch(params)
results = search.get_dict()

for pdfs in results["organic_results"]:
    for link in pdfs.get("resources", []):
        pdf_link = link["link"]
        print(pdf_link)

# output:
'''
https://linqs.github.io/linqs-website/assets/resources/getoor-vldb12-slides.pdf
http://ilpubs.stanford.edu:8090/859/1/2008-7.pdf
https://drum.lib.umd.edu/bitstream/handle/1903/4241/umi-umd-4070.pdf;sequence=1
https://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.169.9535&rep=rep1&type=pdf
https://arxiv.org/pdf/1208.1927
https://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.77.6875&rep=rep1&type=pdf
http://da.qcri.org/ntang/pubs/vldb18-deeper.pdf
'''
</code>```

If you want to scrape more data from organic results, there's a dedicated Scrape Google Scholar with Python blog post of mine.

Disclaimer, I work for SerpApi.

Body:
I am trying to scrape the PDF links from the search results from Google Scholar. I have tried to set a page counter based on the change in URL, but after the first eight output links, I am getting repetitive links as output.

#!/usr/bin/env python
from mechanize import Browser
from BeautifulSoup import BeautifulSoup
from bs4 import BeautifulSoup
import urllib2
import requests

#modifying the url as per page
urlCounter = 0
while urlCounter <=30:
    urlPart1 = "http://scholar.google.com/scholar?start="
    urlPart2 = "&q=%22entity+resolution%22&hl=en&as_sdt=0,4"
    url = urlPart1 + str(urlCounter) + urlPart2
    page = urllib2.Request(url,None,{"User-Agent":"Mozilla/5.0 (X11; U; Linux i686) Gecko/20071127 Firefox/2.0.0.11"})
    resp = urllib2.urlopen(page)
    html = resp.read()
    soup = BeautifulSoup(html)
    urlCounter = urlCounter + 10

    recordCount = 0
    while recordCount <=9:
        recordPart1 = "gs_ggsW"
        finRecord = recordPart1 + str(recordCount)
        recordCount = recordCount+1

    #printing the links
        for link in soup.find_all('div', id = finRecord):
            linkstring = str(link)
            soup1 = BeautifulSoup(linkstring)
        for link in soup1.find_all('a'):
            print(link.get('href'))

Body:
Have a look at the SelectorGadget Chrome extension to grab CSS selectors by clicking on the desired element in your browser.

Code and example in the online IDE to extract PDF's:

from bs4 import BeautifulSoup
import requests, lxml

params = {
    "q": "entity resolution", # search query
    "hl": "en"                # language
}

# https://requests.readthedocs.io/en/master/user/quickstart/#custom-headers
headers = {
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3538.102 Safari/537.36 Edge/18.19582",
}

html = requests.get("https://scholar.google.com/scholar", params=params, headers=headers, timeout=30)
soup = BeautifulSoup(html.text, "lxml")

for pdf_link in soup.select(".gs_or_ggsm a"):
  pdf_file_link = pdf_link["href"]
  print(pdf_file_link)

# output from the first page:
'''
https://linqs.github.io/linqs-website/assets/resources/getoor-vldb12-slides.pdf
http://ilpubs.stanford.edu:8090/859/1/2008-7.pdf
https://drum.lib.umd.edu/bitstream/handle/1903/4241/umi-umd-4070.pdf;sequence=1
https://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.169.9535&rep=rep1&type=pdf
https://arxiv.org/pdf/1208.1927
https://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.77.6875&rep=rep1&type=pdf
http://da.qcri.org/ntang/pubs/vldb18-deeper.pdf
'''

Alternatively, you can achieve the same thing by using Google Scholar Organic Results API from SerpApi. It's a paid API with a free plan.

The main difference is that you only need to grab the data from structured JSON instead of figuring out how to extract the data from HTML, how to bypass blocks from search engines.

Code to integrate:

from serpapi import GoogleSearch

params = {
    "api_key": "YOUR_API_KEY",   # SerpApi API key
    "engine": "google_scholar",  # Google Scholar organic reuslts
    "q": "entity resolution",    # search query
    "hl": "en"                   # language
}

search = GoogleSearch(params)
results = search.get_dict()

for pdfs in results["organic_results"]:
    for link in pdfs.get("resources", []):
        pdf_link = link["link"]
        print(pdf_link)

# output:
'''
https://linqs.github.io/linqs-website/assets/resources/getoor-vldb12-slides.pdf
http://ilpubs.stanford.edu:8090/859/1/2008-7.pdf
https://drum.lib.umd.edu/bitstream/handle/1903/4241/umi-umd-4070.pdf;sequence=1
https://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.169.9535&rep=rep1&type=pdf
https://arxiv.org/pdf/1208.1927
https://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.77.6875&rep=rep1&type=pdf
http://da.qcri.org/ntang/pubs/vldb18-deeper.pdf
'''

If you want to scrape more data from organic results, there's a dedicated Scrape Google Scholar with Python blog post of mine.

Disclaimer, I work for SerpApi.


问:
How to filter foreingkey choices in Django Admin?
I have 3 simple models:

```<code>class Department(models.Model):
name = models.CharField(
    max_length=30
)

class Company(models.Model):
    name = models.CharField(
        max_length=30
    )
    department = models.ManyToManyField(Department)

class Employee(models.Model):
    name = models.CharField(
        max_length=30
    )

    company = models.ForeignKey(Company,
                                on_delete=SET_NULL,
                                null=True,
                                blank=True,
                                )

    department = models.ForeignKey(to=Department,
                                   on_delete=DO_NOTHING)
</code>```

I want to restrict department options in Django Admin panel to those which are related to Employee's company. For example:

Departments:

HR, DevOpps, WebApps, TVApps

Companies:

Company_1 with departments - HR, DevOpps, WebApp

Company_2 with departments - HR, DevOpps, TVApps

Add Employee:

if Company_1 is selected, the options for department to be: HR, DevOpps, WebApp

if Company_2 is selected, the options for department to be: HR, DevOpps, TVApps

答:
It sounds like you are looking to implement dependent dropdown in your forms?

Here is a great article I have followed in the past which you can use to address this by essentially filtering the options using ajax.

I have also seen this issue addressed nicely into htmx if you'd like to try that out. Their examples page shows the value-select being implemented.

Body:
I have 3 simple models:

class Department(models.Model):
name = models.CharField(
    max_length=30
)

class Company(models.Model):
    name = models.CharField(
        max_length=30
    )
    department = models.ManyToManyField(Department)

class Employee(models.Model):
    name = models.CharField(
        max_length=30
    )

    company = models.ForeignKey(Company,
                                on_delete=SET_NULL,
                                null=True,
                                blank=True,
                                )

    department = models.ForeignKey(to=Department,
                                   on_delete=DO_NOTHING)

I want to restrict department options in Django Admin panel to those which are related to Employee's company. For example:

Departments:

HR, DevOpps, WebApps, TVApps

Companies:

Company_1 with departments - HR, DevOpps, WebApp

Company_2 with departments - HR, DevOpps, TVApps

Add Employee:

if Company_1 is selected, the options for department to be: HR, DevOpps, WebApp

if Company_2 is selected, the options for department to be: HR, DevOpps, TVApps


问:
Group rows in a multidimensional array and sum the "count" elements in each group
I have an array of associative arrays and I would like to group them by the rows by the values for A, B, and C and sum the count value for each group.

```<code>$array = [
    ['A' => 'O',    'B' => 'O',     'C' => 1, 'count' => 1],
    ['A' => 'Test', 'B' => 'Test',  'C' => 1, 'count' => 1],
    ['A' => 'O',    'B' => 'O',     'C' => 1, 'count' => 1],
    ['A' => 'Test', 'B' => 'Test',  'C' => 1, 'count' => 1],
    ['A' => 'Test', 'B' => 'test1', 'C' => 2, 'count' => 1],
];
</code>```

I need a result like this:

```<code>[
    ["A" => "O",    "B" => "O",     "C" => 1, "count" => 2],
    ["A" => "Test", "B" => "Test",  "C" => 1, "count" => 2],
    ["A" => "Test", "B" => "test1", "C" => 2, "count" => 1]
]
</code>```

In order to make this you need to loop through the array and check where the attributes "A", "B", "C" are equal.  I tried doing this, but I couldn't fix it.

```<code>$countedArray[0] = $array[0];
foreach ($array as $item) {
    $occKey = array_filter(
        $countedArray,
        function ($countedItem, $key) use ($array) {
            if ($countedItem['A'] == $item['A']
                && $countedItem['B'] == $item['B']
                && $countedItem['C'] == $item['C']
            ) {
                $countedItem[$key]['count'] = countedItem[$key]['count'] + 1
            } else {
                array_push(
                    $countedArray,
                    [
                        'A' => $item['A'],
                        'B' => $item['B'],
                        'C' => $item['C'],
                        'count' => 1
                    ]
                );
            }
        },
        ARRAY_FILTER_USE_BOTH
    );
}
</code>```

答:
The accepted answer is working waaaaay too hard for what is a basic task.

You merely need to use temporary, composite keys (based on the first three elements' values) to form grouped results.  When a new row matches a pre-existing group, simply add its count to the stored count for the group. When the loop finishes, call array_values() to re-index the first level of the result array.

Code: (Demo)

```<code>$array = [
    ['A' => 'O', 'B' => 'O', 'C' => 1, 'count' => 1],
    ['A' => 'Test', 'B' => 'Test', 'C' => 1, 'count' => 1],
    ['A' => 'O', 'B' => 'O', 'C' => 1, 'count' => 1],
    ['A' => 'Test', 'B' => 'Test', 'C' => 1, 'count' => 1],
    ['A' => 'Test', 'B' => 'test1', 'C' => 2, 'count' => 1],
];

$result = [];
foreach ($array as $row) {
    $key = implode('~', array_slice($row, 0, 3));
    if (!isset($result[$key])) {
        $result[$key] = $row;
    } else {
        $result[$key]['count'] += $row['count'];
    }
}

var_export(array_values($result));
</code>```

Body:
I have an array of associative arrays and I would like to group them by the rows by the values for A, B, and C and sum the count value for each group.

$array = [
    ['A' => 'O',    'B' => 'O',     'C' => 1, 'count' => 1],
    ['A' => 'Test', 'B' => 'Test',  'C' => 1, 'count' => 1],
    ['A' => 'O',    'B' => 'O',     'C' => 1, 'count' => 1],
    ['A' => 'Test', 'B' => 'Test',  'C' => 1, 'count' => 1],
    ['A' => 'Test', 'B' => 'test1', 'C' => 2, 'count' => 1],
];

I need a result like this:

[
    ["A" => "O",    "B" => "O",     "C" => 1, "count" => 2],
    ["A" => "Test", "B" => "Test",  "C" => 1, "count" => 2],
    ["A" => "Test", "B" => "test1", "C" => 2, "count" => 1]
]

In order to make this you need to loop through the array and check where the attributes "A", "B", "C" are equal.  I tried doing this, but I couldn't fix it.

$countedArray[0] = $array[0];
foreach ($array as $item) {
    $occKey = array_filter(
        $countedArray,
        function ($countedItem, $key) use ($array) {
            if ($countedItem['A'] == $item['A']
                && $countedItem['B'] == $item['B']
                && $countedItem['C'] == $item['C']
            ) {
                $countedItem[$key]['count'] = countedItem[$key]['count'] + 1
            } else {
                array_push(
                    $countedArray,
                    [
                        'A' => $item['A'],
                        'B' => $item['B'],
                        'C' => $item['C'],
                        'count' => 1
                    ]
                );
            }
        },
        ARRAY_FILTER_USE_BOTH
    );
}

Body:
The accepted answer is working waaaaay too hard for what is a basic task.

You merely need to use temporary, composite keys (based on the first three elements' values) to form grouped results.  When a new row matches a pre-existing group, simply add its count to the stored count for the group. When the loop finishes, call array_values() to re-index the first level of the result array.

Code: (Demo)

$array = [
    ['A' => 'O', 'B' => 'O', 'C' => 1, 'count' => 1],
    ['A' => 'Test', 'B' => 'Test', 'C' => 1, 'count' => 1],
    ['A' => 'O', 'B' => 'O', 'C' => 1, 'count' => 1],
    ['A' => 'Test', 'B' => 'Test', 'C' => 1, 'count' => 1],
    ['A' => 'Test', 'B' => 'test1', 'C' => 2, 'count' => 1],
];

$result = [];
foreach ($array as $row) {
    $key = implode('~', array_slice($row, 0, 3));
    if (!isset($result[$key])) {
        $result[$key] = $row;
    } else {
        $result[$key]['count'] += $row['count'];
    }
}

var_export(array_values($result));


问:
How to use revised array again in loop python
The below code is about, dividing the even elements of list  by 2 till if reaches 1 if the element is odd then remove the element .

I just now started this program. What doubt I have means I need to use the revised array again in the loop. But it showing error.

```<code>Input:

   4
   32 60 8 200

Needed Output:

  16 30 4 100
    8 15 2 50
    4 1 25
    1

 n=int(input())
    l=list(map(int,input().split()))
    leg=len(l)
    rv=[]

    for i in range(0,leg):
      if l[i]%2==0:
        rv.append(l[i]//2)
        l=rv
</code>```

error:

```<code>    Traceback (most recent call last):
  File "HelloWorld.py", line 7, in <module>
    if l[i]%2==0:
IndexError: list index out of range
</code>```

In my above code what i am trying to do means i append the even elements of list 'l' to 'rv'
and i need to use 'rv' for the loop instead of 'l' but it showing error why??

答:
I think this code calculates what you want correctly. However, it breaks if not all the numbers are divisible by two.

n = int(input('set lenght of input'))
l = []

for k in range(n):
    l.append(int(input()))

running = True

while(running):
    print(l)
    for i in l[len(l)-n:len(l)]:
        if(i % 2 == 0):
            z = int(i / 2)
            l.append(z)
            if z == 1: running = False

l = l[n+1:]
print(l)
```

Body:
The below code is about, dividing the even elements of list  by 2 till if reaches 1 if the element is odd then remove the element .

I just now started this program. What doubt I have means I need to use the revised array again in the loop. But it showing error.

Input:

   4
   32 60 8 200

Needed Output:

  16 30 4 100
    8 15 2 50
    4 1 25
    1

 n=int(input())
    l=list(map(int,input().split()))
    leg=len(l)
    rv=[]

    for i in range(0,leg):
      if l[i]%2==0:
        rv.append(l[i]//2)
        l=rv

error:

    Traceback (most recent call last):
  File "HelloWorld.py", line 7, in <module>
    if l[i]%2==0:
IndexError: list index out of range

In my above code what i am trying to do means i append the even elements of list 'l' to 'rv'
and i need to use 'rv' for the loop instead of 'l' but it showing error why??


问:
See chmod permissions in windows?
I'm developing a site on my local environment and I'm running windows. I need to set chmod file permissions (eg 666, 777, etc). Is there a way in Windows to see file permissions as chmod numbers?

Thanks

答:
The Windows file-security model is very different from the (old?) simple Unix approach.

In Windows you can define the access per user, per group, even per computer, and there are many more access-types than just read, write and execute.

If you want to support all Windows file-security aspects, take a look at the specific Windows security functions.

Visual Studio's C-Run-time however, has some functions that 'emulate' (in a minimal way) the Unix security approach.  Look for _chmod and _access (http://msdn.microsoft.com/en-us/library/1w06ktdy(v=vs.80).aspx should get you started).

Title: See chmod permissions in windows?


问:
ASP.NET Core 6 Configuration problem with docker
I have a problem with configuration my service with docker. I using VS 2022 to create my server by template "ASP.NET Core Web API". I added two libraries to the solution and they are connected to a main project by reference. Then I used docker plugin to generate "dockerfile" and i get something like this.

```<code>#See https://aka.ms/containerfastmode to understand how Visual Studio uses this Dockerfile to build your images for faster debugging.

FROM mcr.microsoft.com/dotnet/aspnet:6.0 AS base
WORKDIR /app
EXPOSE 80
EXPOSE 443

FROM mcr.microsoft.com/dotnet/sdk:6.0 AS build
WORKDIR /src
COPY ["AVM.Core.csproj", "."]
COPY ["../AVM.Domain/AVM.Domain.csproj", "../AVM.Domain/"]
COPY ["../AVM.Repository/AVM.Repository.csproj", "../AVM.Repository/"]
RUN dotnet restore "./AVM.Core.csproj"
COPY . .
WORKDIR "/src/."
RUN dotnet build "AVM.Core.csproj" -c Release -o /app/build

FROM build AS publish
RUN dotnet publish "AVM.Core.csproj" -c Release -o /app/publish

FROM base AS final
WORKDIR /app
COPY --from=publish /app/publish .
ENTRYPOINT ["dotnet", "AVM.Core.dll"]
</code>```

I use a sample .dockerignore

```<code>**/.classpath
**/.dockerignore
**/.env
**/.git
**/.gitignore
**/.project
**/.settings
**/.toolstarget
**/.vs
**/.vscode
**/*.*proj.user
**/*.dbmdl
**/*.jfm
**/azds.yaml
**/bin
**/charts
**/docker-compose*
**/Dockerfile*
**/node_modules
**/npm-debug.log
**/obj
**/secrets.dev.yaml
**/values.dev.yaml
LICENSE
README.md
</code>```

When i try to build my image with command docker build -t avmcore i got error like this

```<code>=> [internal] load build definition from Dockerfile                                                               0.0s
 => => transferring dockerfile: 818B                                                                               0.0s
 => [internal] load .dockerignore                                                                                0.0s
 => => transferring context: 34B                                                                                0.0s
 => [internal] load metadata for mcr.microsoft.com/dotnet/sdk:6.0                                                  0.1s
 => [internal] load metadata for mcr.microsoft.com/dotnet/aspnet:6.0                                               0.1s
 => [base 1/2] FROM mcr.microsoft.com/dotnet/aspnet:6.0@sha256:84fc4202a1f38fd440b718aeeb4e8cfe046e9f19ef977a28c0  0.0s
 => => resolve mcr.microsoft.com/dotnet/aspnet:6.0@sha256:84fc4202a1f38fd440b718aeeb4e8cfe046e9f19ef977a28c01827d  0.0s
 => [internal] load build context                                                                                0.6s
 => => transferring context: 17.69MB                                                                               0.6s
 => [build 1/9] FROM mcr.microsoft.com/dotnet/sdk:6.0@sha256:76dbd63a33da6510787e97c0943c4c4a2136936ce360cf925386  0.0s
 => CACHED [base 2/2] WORKDIR /app                                                                                0.0s
 => CACHED [final 1/2] WORKDIR /app                                                                                0.0s
 => CACHED [build 2/9] WORKDIR /src                                                                                0.0s
 => CACHED [build 3/9] COPY [AVM.Core.csproj, .]                                                                   0.0s
 => ERROR [build 4/9] COPY [../AVM.Domain/AVM.Domain.csproj, ../AVM.Domain/]                                       0.0s
 => ERROR [build 5/9] COPY [../AVM.Repository/AVM.Repository.csproj, ../AVM.Repository/]                           0.0s
------
 > [build 4/9] COPY [../AVM.Domain/AVM.Domain.csproj, ../AVM.Domain/]:
------
------
 > [build 5/9] COPY [../AVM.Repository/AVM.Repository.csproj, ../AVM.Repository/]:
------
failed to compute cache key: "/AVM.Domain/AVM.Domain.csproj" not found: not found
</code>```

Thanks for all answers guys.

答:
I had the same issue.

Visual Studio uses a bit different approach with Docker images.

Try to move to the parent folder where the .sln is and run docker build and specify the Dockerfile using the -f option.

```<code>docker build -f ./ProjectFolder/Dockerfile ...
</code>```

Body:
I have a problem with configuration my service with docker. I using VS 2022 to create my server by template "ASP.NET Core Web API". I added two libraries to the solution and they are connected to a main project by reference. Then I used docker plugin to generate "dockerfile" and i get something like this.

#See https://aka.ms/containerfastmode to understand how Visual Studio uses this Dockerfile to build your images for faster debugging.

FROM mcr.microsoft.com/dotnet/aspnet:6.0 AS base
WORKDIR /app
EXPOSE 80
EXPOSE 443

FROM mcr.microsoft.com/dotnet/sdk:6.0 AS build
WORKDIR /src
COPY ["AVM.Core.csproj", "."]
COPY ["../AVM.Domain/AVM.Domain.csproj", "../AVM.Domain/"]
COPY ["../AVM.Repository/AVM.Repository.csproj", "../AVM.Repository/"]
RUN dotnet restore "./AVM.Core.csproj"
COPY . .
WORKDIR "/src/."
RUN dotnet build "AVM.Core.csproj" -c Release -o /app/build

FROM build AS publish
RUN dotnet publish "AVM.Core.csproj" -c Release -o /app/publish

FROM base AS final
WORKDIR /app
COPY --from=publish /app/publish .
ENTRYPOINT ["dotnet", "AVM.Core.dll"]

I use a sample .dockerignore

**/.classpath
**/.dockerignore
**/.env
**/.git
**/.gitignore
**/.project
**/.settings
**/.toolstarget
**/.vs
**/.vscode
**/*.*proj.user
**/*.dbmdl
**/*.jfm
**/azds.yaml
**/bin
**/charts
**/docker-compose*
**/Dockerfile*
**/node_modules
**/npm-debug.log
**/obj
**/secrets.dev.yaml
**/values.dev.yaml
LICENSE
README.md

When i try to build my image with command docker build -t avmcore i got error like this

=> [internal] load build definition from Dockerfile                                                               0.0s
 => => transferring dockerfile: 818B                                                                               0.0s
 => [internal] load .dockerignore                                                                                0.0s
 => => transferring context: 34B                                                                                0.0s
 => [internal] load metadata for mcr.microsoft.com/dotnet/sdk:6.0                                                  0.1s
 => [internal] load metadata for mcr.microsoft.com/dotnet/aspnet:6.0                                               0.1s
 => [base 1/2] FROM mcr.microsoft.com/dotnet/aspnet:6.0@sha256:84fc4202a1f38fd440b718aeeb4e8cfe046e9f19ef977a28c0  0.0s
 => => resolve mcr.microsoft.com/dotnet/aspnet:6.0@sha256:84fc4202a1f38fd440b718aeeb4e8cfe046e9f19ef977a28c01827d  0.0s
 => [internal] load build context                                                                                0.6s
 => => transferring context: 17.69MB                                                                               0.6s
 => [build 1/9] FROM mcr.microsoft.com/dotnet/sdk:6.0@sha256:76dbd63a33da6510787e97c0943c4c4a2136936ce360cf925386  0.0s
 => CACHED [base 2/2] WORKDIR /app                                                                                0.0s
 => CACHED [final 1/2] WORKDIR /app                                                                                0.0s
 => CACHED [build 2/9] WORKDIR /src                                                                                0.0s
 => CACHED [build 3/9] COPY [AVM.Core.csproj, .]                                                                   0.0s
 => ERROR [build 4/9] COPY [../AVM.Domain/AVM.Domain.csproj, ../AVM.Domain/]                                       0.0s
 => ERROR [build 5/9] COPY [../AVM.Repository/AVM.Repository.csproj, ../AVM.Repository/]                           0.0s
------
 > [build 4/9] COPY [../AVM.Domain/AVM.Domain.csproj, ../AVM.Domain/]:
------
------
 > [build 5/9] COPY [../AVM.Repository/AVM.Repository.csproj, ../AVM.Repository/]:
------
failed to compute cache key: "/AVM.Domain/AVM.Domain.csproj" not found: not found

Thanks for all answers guys.

Body:
I had the same issue.

Visual Studio uses a bit different approach with Docker images.

Try to move to the parent folder where the .sln is and run docker build and specify the Dockerfile using the -f option.

docker build -f ./ProjectFolder/Dockerfile ...


问:
Unity script crashes editor
Here is my code:

```<code>void Update()
    {
        if (shipController.Mode == ShipController.ShipMode.Build)
        {
            var mouseInWorld = Camera.main.ScreenToWorldPoint(Mouse.current.position.ReadValue());
            Debug.Log(mouseInWorld);
            var mousePos = new Vector2(mouseInWorld.x, mouseInWorld.y);
            var currentPos = new Vector2(transform.position.x, transform.position.y);
            var posToTarget = mousePos - currentPos;
            var oldPosToTarget = posToTarget;
            var oldPos = currentPos;
            var shotPastTargetOrExact = false;
            var iter = 0;
            while (!shotPastTargetOrExact)
            {
                iter++;
                Debug.Log(iter);
                oldPos = currentPos;
                oldPosToTarget = posToTarget;
                if (posToTarget == Vector2.zero) shotPastTargetOrExact = true;
                if (Mathf.Abs(posToTarget.x) >= Mathf.Abs(posToTarget.y))
                {
                    if (posToTarget.x > 0) currentPos = new Vector2(currentPos.x += blockdistance, currentPos.y);
                    else currentPos = new Vector2(currentPos.x -= blockdistance, currentPos.y);
                }
                else
                {
                    if (posToTarget.y > 0) currentPos = new Vector2(currentPos.x, currentPos.y += blockdistance);
                    else currentPos = new Vector2(currentPos.x, currentPos.y -= blockdistance);
                }
                posToTarget = mousePos - currentPos;
                if (posToTarget.sqrMagnitude > oldPosToTarget.sqrMagnitude)
                {
                    shotPastTargetOrExact = true;
                    currentPos = oldPos;
                }
            }

            if (currentSlot != null && currentSlot.CurrentItemDragAndDrop != null && currentSlot.CurrentItemDragAndDrop.Item != null)
            {
                var item = currentSlot.CurrentItemDragAndDrop.Item;
                if (currentPlacementBlock == null)
                {
                    currentPlacementBlock = Instantiate(item.BlockPrefab);
                }
                currentPlacementBlock.transform.localPosition = currentPos;
                currentPlacementBlock.transform.rotation = shipController.transform.rotation;
            }
            else if (currentPlacementBlock != null)
            {
                Destroy(currentPlacementBlock);
                currentPlacementBlock = null;
            }
        }
    }
</code>```

It crashes when I try to stop the game with the play button in the editor. It has also crashed when starting build mode (see shipController.Mode)

The script works as intended but crashes when stopping the game.
I loged the iterations to try and see if it was looping forever but it doesnt seem to be that as it always comes out with a small iter number in the console

答:
I fixed it by checking if the mouse was in the window before going ahead and performing the rest of the update</p>
```<code>bool IsMouseOverGameWindow { get { var mousePosition = Mouse.current.position.ReadValue(); return !(0 > mousePosition.x || 0 > mousePosition.y || Screen.width < mousePosition.x || Screen.height < mousePosition.y); } }
</code>```

Title: Unity script crashes editor

Body:
Here is my code:

void Update()
    {
        if (shipController.Mode == ShipController.ShipMode.Build)
        {
            var mouseInWorld = Camera.main.ScreenToWorldPoint(Mouse.current.position.ReadValue());
            Debug.Log(mouseInWorld);
            var mousePos = new Vector2(mouseInWorld.x, mouseInWorld.y);
            var currentPos = new Vector2(transform.position.x, transform.position.y);
            var posToTarget = mousePos - currentPos;
            var oldPosToTarget = posToTarget;
            var oldPos = currentPos;
            var shotPastTargetOrExact = false;
            var iter = 0;
            while (!shotPastTargetOrExact)
            {
                iter++;
                Debug.Log(iter);
                oldPos = currentPos;
                oldPosToTarget = posToTarget;
                if (posToTarget == Vector2.zero) shotPastTargetOrExact = true;
                if (Mathf.Abs(posToTarget.x) >= Mathf.Abs(posToTarget.y))
                {
                    if (posToTarget.x > 0) currentPos = new Vector2(currentPos.x += blockdistance, currentPos.y);
                    else currentPos = new Vector2(currentPos.x -= blockdistance, currentPos.y);
                }
                else
                {
                    if (posToTarget.y > 0) currentPos = new Vector2(currentPos.x, currentPos.y += blockdistance);
                    else currentPos = new Vector2(currentPos.x, currentPos.y -= blockdistance);
                }
                posToTarget = mousePos - currentPos;
                if (posToTarget.sqrMagnitude > oldPosToTarget.sqrMagnitude)
                {
                    shotPastTargetOrExact = true;
                    currentPos = oldPos;
                }
            }

            if (currentSlot != null && currentSlot.CurrentItemDragAndDrop != null && currentSlot.CurrentItemDragAndDrop.Item != null)
            {
                var item = currentSlot.CurrentItemDragAndDrop.Item;
                if (currentPlacementBlock == null)
                {
                    currentPlacementBlock = Instantiate(item.BlockPrefab);
                }
                currentPlacementBlock.transform.localPosition = currentPos;
                currentPlacementBlock.transform.rotation = shipController.transform.rotation;
            }
            else if (currentPlacementBlock != null)
            {
                Destroy(currentPlacementBlock);
                currentPlacementBlock = null;
            }
        }
    }

It crashes when I try to stop the game with the play button in the editor. It has also crashed when starting build mode (see shipController.Mode)

The script works as intended but crashes when stopping the game.
I loged the iterations to try and see if it was looping forever but it doesnt seem to be that as it always comes out with a small iter number in the console

Body:
I fixed it by checking if the mouse was in the window before going ahead and performing the rest of the update

bool IsMouseOverGameWindow { get { var mousePosition = Mouse.current.position.ReadValue(); return !(0 > mousePosition.x || 0 > mousePosition.y || Screen.width < mousePosition.x || Screen.height < mousePosition.y); } }


问:
Difference between datetime and timestamp in sqlserver?
What is the difference between Timestamp and Datetime SQL Server?

I thought Both formats are capable of storing date + time. Then, Where the difference is lying between them?

But Timestamp is not capable of storing date, time information.

Still Whats the difference?

答:
According to the documentation, timestamp is a synonym for rowversion - it's automatically generated and guaranteed1 to be unique. datetime isn't - it's just a data type which handles dates and times, and can be client-specified on insert etc.

1 Assuming you use it properly, of course. See comments.


问:
urllib.request.urlopen Type Error can't concat str to bytes
I'm running python 3.9 and I'm having this issue with my code:

I'm getting TypeError: can't concat str to bytes

Here's my code

try:
   with urllib.request.urlopen(link, headers) as f:
      print(f.read().decode('utf-8'))
except urllib.error.URLError as e:
   print(e.reason)
```

Any ideas on how to solve this error?

答:
You have so many typos in there. The main one is read should be read().

```<code>try:
    with urllib.request.urlopen(link) as response:
        data = response.read().decode('utf-8')
        print(data)
except Exception as e:
   print(e)
</code>```

Body:
I'm running python 3.9 and I'm having this issue with my code:

I'm getting TypeError: can't concat str to bytes

Here's my code

try:
   with urllib.request.urlopen(link, headers) as f:
      print(f.read().decode('utf-8'))
except urllib.error.URLError as e:
   print(e.reason)

Any ideas on how to solve this error?

Body:
You have so many typos in there. The main one is read should be read().

try:
    with urllib.request.urlopen(link) as response:
        data = response.read().decode('utf-8')
        print(data)
except Exception as e:
   print(e)


问:
Python 3 while loop can't show list keys?
Ok so i am trying to do some basic while loop to show text formated in this way:

A - 80%-100%

B - 60%-80%

C - 50-60%

D - less then 50%

with this code:

```<code>dictionary={'A':'80%-100%','B':'60%-80%','C':'50-60%','D':'less then 50%'}
klucze=list(dictionary.keys())
q=0
while q<4:
print(klucze[q]," - ",dictionary[q])
q+=1
</code>```

It's working with klucze[q] only, but when i try to print dictionary[q] too, i get the error

答:
Well dictionary accepts key to give you value at that key.
Your dictionary has keys 'A', 'B', etc. But you are using numeric value to access dictionary values thus it does not works.

```<code>print(klucze[q]," - ",dictionary[klucze[q]])
</code>```

Now the dictionary is getting key values you created as input so it will give you the correct output.

Body:
Ok so i am trying to do some basic while loop to show text formated in this way:

A - 80%-100%

B - 60%-80%

C - 50-60%

D - less then 50%

with this code:

dictionary={'A':'80%-100%','B':'60%-80%','C':'50-60%','D':'less then 50%'}
klucze=list(dictionary.keys())
q=0
while q<4:
print(klucze[q]," - ",dictionary[q])
q+=1

It's working with klucze[q] only, but when i try to print dictionary[q] too, i get the error

Body:
Well dictionary accepts key to give you value at that key.
Your dictionary has keys 'A', 'B', etc. But you are using numeric value to access dictionary values thus it does not works.

print(klucze[q]," - ",dictionary[klucze[q]])

Now the dictionary is getting key values you created as input so it will give you the correct output.


问:
Find JavaScript function with regex
take a look at my following regex: https://regex101.com/r/HMya54/2

I only want to find the javascript-function with "_tsid" in it, not all JavaScript functions, and to replace that whole function by an HTML-Comment .

I tried something like: /

答:
The simplest way is to use your current (or its optimized version, see below) and use a callback as the replacement argument where you can check if the match contains the string of your choice, and if it is there, perform the replacement:

let text = '\n\n\n\n';
text = text.replace(/</g, '<').replace(/, and then the text containing _tsid only is replaced, else, the match is reinserted into the resulting string.

Title: Find JavaScript function with regex

Body:
The simplest way is to use your current (or its optimized version, see below) and use a callback as the replacement argument where you can check if the match contains the string of your choice, and if it is there, perform the replacement:

let text = '&lt;script type="text/javacript">alert("First one!");&lt;/script>\n\n&lt;script>console.log("Hello World");&lt;/script>\n\n&lt;script type="text/javascript">\n                (function () {\n                    var _tsid = \'XFE5AF4B9ADDACA0E60017B1BC4D16AE2\';\n                    _tsConfig = {\n                        \'yOffset\': \'0\', /* offset from page bottom */\n                        \'variant\': \'reviews\', /* reviews, default, custom, custom_reviews */\n                        \'customElementId\': \'\', /* required for variants custom and custom_reviews */\n                        \'trustcardDirection\': \'\', /* for custom variants: topRight, topLeft, bottomRight, bottomLeft */\n                        \'customBadgeWidth\': \'\', /* for custom variants: 40 - 90 (in pixels) */\n                        \'customBadgeHeight\': \'\', /* for custom variants: 40 - 90 (in pixels) */\n                        \'disableResponsive\': \'false\', /* deactivate responsive behaviour */\n                                                \'disableTrustbadge\': \'false\', /* deactivate Trustbadge® */\n                                                \'responsive\': {\n                            \'variant\': \'\', /* floating, custom */\n                            \'customElementId\': \'\' /* required for variant custom */\n                        }\n                    };\n                    var _ts = document.createElement(\'script\');\n                    _ts.type = \'text/javascript\';\n                    _ts.charset = \'utf-8\';\n                    _ts.async = true;\n                    _ts.src = \'//widgets.trustedshops.com/js/\' + _tsid + \'.js\';\n                    var __ts = document.getElementsByTagName(\'script\')[0];\n                    __ts.parentNode.insertBefore(_ts, __ts);\n                })();\n&lt;/script>';
text = text.replace(/&lt;/g, '<').replace(/<script[^>]*>[^<]*(?:<(?!\/?script[\s>])[^<]*)*<\/script>/g, (x) => x.includes("_tsid") ? "<!-- here was my function -->" : x);
console.log(text);

The regex is now /<script[^>]*>[^<]*(?:<(?!\/?script[\s>])[^<]*)*<\/script>/g, it matches <script, anu zero or more chars other than >, then a >, then any zero or more non-< chars, then zero or more sequences of < not followed with an optional / and then script followed with a whitespace or > and then zero or more non-< chars, and then </script>, and then the text containing _tsid only is replaced, else, the match is reinserted into the resulting string.


问:
Add content to a new open window
I don't know how to solve this issue, I've trying reading many post but no one answer to it.

I need to open a new window with a page already coded (inside the same domain) and add some content.

The problem is that if I use OpenWindow.write() the page is not loaded yet or it overrides everything and only the code added through write appears.

```<code>var OpenWindow = window.open('mypage.html','_blank','width=335,height=330,resizable=1');
OpenWindow.document.write(output);
</code>```

output is the code I need to append.

I need it to work at least on Firefox, IE and GC.

It is not a problem if I need to use JQuery.

答:
it is even more simple!

Just put the code below in between the   of your code and all of your links will open in a new window:

```<code><base target="_blank">
</code>```

Title: Add content to a new open window

Body:
I don't know how to solve this issue, I've trying reading many post but no one answer to it.

I need to open a new window with a page already coded (inside the same domain) and add some content.

The problem is that if I use OpenWindow.write() the page is not loaded yet or it overrides everything and only the code added through write appears.

var OpenWindow = window.open('mypage.html','_blank','width=335,height=330,resizable=1');
OpenWindow.document.write(output);

output is the code I need to append.

I need it to work at least on Firefox, IE and GC.

It is not a problem if I need to use JQuery.

Body:
it is even more simple!

Just put the code below in between the <head> </head> of your code and all of your links will open in a new window:

<base target="_blank">


问:
implicit "popd" on batch exit
Is there a way to undo all pushd at the end of script. What I have is:

```<code>pushd somwhere
rem doing stuff
goto end

:end
popd
goto :EOF
</code>```

What I'd like to have is:

```<code>setlocal
pushd somwhere
rem doing stuff
goto :EOF
</code>```

But that doesn't work, the directory stays "pushd". Another try where I can't say how many pushd will occur would be:

```<code>set CurrentDir=%CD%
rem doing a lot of pushd and popd
pushd somwhere

:POPBACK
if /i not "%CD%" == "%CurrentDir%" popd & goto POPBACK
</code>```

But that looks like I can easily get stuck at :POPBACK. Adding a counter to exit that loop is a bit uncertain at which dir I end up.

In that context I'd like to know if a can see the stack of pushd directories. The only thing I found was $+ in prompt $P$+$G which adds a '+' for each pushd directory e.g. D:\CMD++>. But I can't see a way how to make use of that.

EDIT:
I just noticed there is something wrong with the $+ of prompt that confused me.
The setlocal in the example above actually makes the script return to the initial directory, but the prompt shows a '+' indicating a missing popd.

```<code>D:\CMD>test.cmd
D:\CMD>prompt $P$+$g
D:\CMD>setlocal
D:\CMD>pushd e:\DATA
e:\DATA+>goto :EOF
D:\CMD+>popd
D:\CMD>
</code>```

EDIT:
Due to the hint to the difference between local environment and directory stack I expanded the example form above, pushing to C:\DATA before calling the script. the script returns to where it has been called from (C:\DATA). So far so good. The first popd shows no effect as it removes the last pushd from stack but not changing the directory, since the directory change has been undone by the (implicit) endlocal. The second popd returns to initial directory as expected.

```<code>D:\CMD>pushd C:\DATA
C:\DATA+>d:\cmd\test.cmd
C:\DATA+>prompt $P$+$g
C:\DATA+>setlocal
C:\DATA+>pushd e:\DATA
e:\DATA++>goto :EOF
C:\DATA++>popd
C:\DATA+>popd
D:\CMD>
</code>```

答:
Two points here:

1. Setlocal/Endlocal commands save/restore current directory!

This means that when Endlocal command is executed, the current directory is returned to the point it has when the previous Setlocal command was executed. This happens no matter if the Endlocal is explicitly executed, or it is implicitly executed by the termination of the called subroutine (via exit /B or goto :EOF commands).

This behaviour could be used to solve your problem, because all changes of the current directory are reverted when endlocal command is executed. That is:

```<code>setlocal
cd somwhere
rem doing stuff
goto :EOF
</code>```

However note that this behavior is not related to pushd/popd commands! You can not mix the use of this feature with pushd/popd commands. You would need to complete several tests until the mechanism of the interaction between these two features be comprehended.

This is an undocumented behavior discussed here.

2. POPD command sets the Exit Code when there is no previous PUSHD

As described below Exit Code management section at this answer, there are some commands that does not set the ErrorLevel when an error happens, but sets an internal value we could call "Exit Code". This value can be tested via the && || construct this way:

```<code>command && Then command when Exit Code == 0 || Else command when Exit code != 0
</code>```

POPD is one of this type of commands (described under Table 5), so we could use this feature to execute POPD several times until there is not a matching PUSHD previously executed:

```<code>@echo off
setlocal

echo Enter in:
for /L %%i in (1,1,%1) do echo %%i & pushd ..

echo Leave out:
set "n=0"
:nextLevel
popd || goto exitLevels
   set /A n+=1
   echo %n%
   goto nextLevel
:exitLevels

echo Done
</code>```

Bottom line: a simple popd && goto POPBACK line solves your problem...

Title: implicit "popd" on batch exit

Body:
Is there a way to undo all pushd at the end of script. What I have is:

pushd somwhere
rem doing stuff
goto end

:end
popd
goto :EOF

What I'd like to have is:

setlocal
pushd somwhere
rem doing stuff
goto :EOF

But that doesn't work, the directory stays "pushd". Another try where I can't say how many pushd will occur would be:

set CurrentDir=%CD%
rem doing a lot of pushd and popd
pushd somwhere

:POPBACK
if /i not "%CD%" == "%CurrentDir%" popd & goto POPBACK

But that looks like I can easily get stuck at :POPBACK. Adding a counter to exit that loop is a bit uncertain at which dir I end up.

In that context I'd like to know if a can see the stack of pushd directories. The only thing I found was $+ in prompt $P$+$G which adds a '+' for each pushd directory e.g. D:\CMD++>. But I can't see a way how to make use of that.

EDIT:
I just noticed there is something wrong with the $+ of prompt that confused me.
The setlocal in the example above actually makes the script return to the initial directory, but the prompt shows a '+' indicating a missing popd.

D:\CMD>test.cmd
D:\CMD>prompt $P$+$g
D:\CMD>setlocal
D:\CMD>pushd e:\DATA
e:\DATA+>goto :EOF
D:\CMD+>popd
D:\CMD>

EDIT:
Due to the hint to the difference between local environment and directory stack I expanded the example form above, pushing to C:\DATA before calling the script. the script returns to where it has been called from (C:\DATA). So far so good. The first popd shows no effect as it removes the last pushd from stack but not changing the directory, since the directory change has been undone by the (implicit) endlocal. The second popd returns to initial directory as expected.

D:\CMD>pushd C:\DATA
C:\DATA+>d:\cmd\test.cmd
C:\DATA+>prompt $P$+$g
C:\DATA+>setlocal
C:\DATA+>pushd e:\DATA
e:\DATA++>goto :EOF
C:\DATA++>popd
C:\DATA+>popd
D:\CMD>

Body:
Two points here:

1. Setlocal/Endlocal commands save/restore current directory!

This means that when Endlocal command is executed, the current directory is returned to the point it has when the previous Setlocal command was executed. This happens no matter if the Endlocal is explicitly executed, or it is implicitly executed by the termination of the called subroutine (via exit /B or goto :EOF commands).

This behaviour could be used to solve your problem, because all changes of the current directory are reverted when endlocal command is executed. That is:

setlocal
cd somwhere
rem doing stuff
goto :EOF

However note that this behavior is not related to pushd/popd commands! You can not mix the use of this feature with pushd/popd commands. You would need to complete several tests until the mechanism of the interaction between these two features be comprehended.

This is an undocumented behavior discussed here.

2. POPD command sets the Exit Code when there is no previous PUSHD

As described below Exit Code management section at this answer, there are some commands that does not set the ErrorLevel when an error happens, but sets an internal value we could call "Exit Code". This value can be tested via the && || construct this way:

command && Then command when Exit Code == 0 || Else command when Exit code != 0

POPD is one of this type of commands (described under Table 5), so we could use this feature to execute POPD several times until there is not a matching PUSHD previously executed:

@echo off
setlocal

echo Enter in:
for /L %%i in (1,1,%1) do echo %%i & pushd ..

echo Leave out:
set "n=0"
:nextLevel
popd || goto exitLevels
   set /A n+=1
   echo %n%
   goto nextLevel
:exitLevels

echo Done

Bottom line: a simple popd && goto POPBACK line solves your problem...


问:
Git commit with no commit message
How can I commit changes without specifying commit message? Why is it required by default?</p>

答:
Building upon some other answers, I came up with the following:

```<code>git config --global alias.gromit '!git add --all && git commit --allow-empty-message -m ""'
</code>```

This differs from the answer by dalvarezmartinez1 in that git add --all also adds new files, while the -a flag in git commit leaves them be. Also, I think that this alias fits the command much better. :-)

Future self, forgive me all the silent, quick, great commits to come.

Title: Git commit with no commit message

Body:
Building upon some other answers, I came up with the following:

git config --global alias.gromit '!git add --all && git commit --allow-empty-message -m ""'

This differs from the answer by dalvarezmartinez1 in that git add --all also adds new files, while the -a flag in git commit leaves them be. Also, I think that this alias fits the command much better. :-)

Future self, forgive me all the silent, quick, great commits to come.