问:
PHP | if stament always false
I have a small problem with an if loop, I am building an appointment booking area, the directives are:

Appointments can be made from Monday to Friday

Appointment times: 11:00 - 13:00 and 15:00 - 18:00

the variables that take the value from the datepicker and timepicker are:

datepicker:

```<code>$app_to_data = $connessione->real_escape_string($_POST['data']);
</code>```

timepicker:

```<code>$app_to_orario = $connessione->real_escape_string($_POST['orario']);
</code>```

no problem to prevent the chosen day from being confirmed when the user chooses to book an appointment on Saturday or Sunday:

```<code>if(date('w', strtotime($app_to_data)) == 6 || date('w', strtotime($app_to_data)) == 0) {
    ?>
    <script type="text/javascript">
        var errore_appto = "<?php echo $id_pa ?>";
        window.location = "prendi_appto_errore.php?errore_appto=" + errore_appto;
    </script>
<?php
exit;
}
</code>```

the problem now comes when I have to initiate if cycles to check the time slot chosen for the appointment:

```<code>   /*VERIFICA CHE L' APPUNTAMENTO NON VENGA PRESO PRIMA DELLE ORE 11:00*/
    if($app_to_orario < '11:00'){
    ?>
        <script type="text/javascript">
            var errore_appto = "<?php echo $id_pa ?>";
            window.location = "prendi_appto_errore.php?errore_appto=" + errore_appto;
        </script>
    <?php
    exit;
    }

    /*VERIFICA CHE L' APPUNTAMENTO NON VENGA PRESO DOPO LE ORE 13:00*/
    elseif($app_to_orario > '13:00'){
    ?>
        <script type="text/javascript">
            var errore_appto = "<?php echo $id_pa ?>";
            window.location = "prendi_appto_errore.php?errore_appto=" + errore_appto;
        </script>
    <?php
    exit;
    }

    /*VERIFICA CHE L' APPUNTAMENTO NON VENGA PRESO PRIMA DELLE ORE 15:00*/
    elseif($app_to_orario < '15:00'){
    ?>
        <script type="text/javascript">
            var errore_appto = "<?php echo $id_pa ?>";
            window.location = "prendi_appto_errore.php?errore_appto=" + errore_appto;
        </script>
    <?php
    exit;
    }

    /*VERIFICA CHE L' APPUNTAMENTO NON VENGA PRESO DOPO LE ORE 18:00*/
    elseif($app_to_orario > '18:00'){
    ?>
        <script type="text/javascript">
            var errore_appto = "<?php echo $id_pa ?>";
            window.location = "prendi_appto_errore.php?errore_appto=" + errore_appto;
        </script>
    <?php
    exit;
    }
</code>```

the problem I have is that if for example the user chooses to book an appointment for 16:00, the chosen time is correct, but I always get an error because for example in the second cycle 16:00 it is greater than 13:00 even if it falls correctly in the remaining 3 control cycles, so how do I perform a time check allowing the appointment in the time slots indicated in the question, without always running into a false result?

答:
In your case, $app_to_orario is a string, not a DateTime. To compare with other date/time, it needs to be converted to DateTime first:

```<code>$ato = new DateTime($app_to_orario);
</code>```

Or use Carbon:

```<code>$ato = new Carbon($app_to_orario);
</code>```

Then compare the time(with Carbon):

```<code>if($ato->hour<11){
    ...
}
</code>```

Or without Carbon:

```<code>if(intval($ato->format('H'))<11){
    ...
}
</code>```

Title: PHP | if stament always false

Body:
I have a small problem with an if loop, I am building an appointment booking area, the directives are:

Appointments can be made from Monday to Friday

Appointment times: 11:00 - 13:00 and 15:00 - 18:00

the variables that take the value from the datepicker and timepicker are:

datepicker:

$app_to_data = $connessione->real_escape_string($_POST['data']);

timepicker:

$app_to_orario = $connessione->real_escape_string($_POST['orario']);

no problem to prevent the chosen day from being confirmed when the user chooses to book an appointment on Saturday or Sunday:

if(date('w', strtotime($app_to_data)) == 6 || date('w', strtotime($app_to_data)) == 0) {
    ?>

<?php
exit;
}

the problem now comes when I have to initiate if cycles to check the time slot chosen for the appointment:

   /*VERIFICA CHE L' APPUNTAMENTO NON VENGA PRESO PRIMA DELLE ORE 11:00*/
    if($app_to_orario < '11:00'){
    ?>

    <?php
    exit;
    }

    /*VERIFICA CHE L' APPUNTAMENTO NON VENGA PRESO DOPO LE ORE 13:00*/
    elseif($app_to_orario > '13:00'){
    ?>

    <?php
    exit;
    }

    /*VERIFICA CHE L' APPUNTAMENTO NON VENGA PRESO PRIMA DELLE ORE 15:00*/
    elseif($app_to_orario < '15:00'){
    ?>

    <?php
    exit;
    }

    /*VERIFICA CHE L' APPUNTAMENTO NON VENGA PRESO DOPO LE ORE 18:00*/
    elseif($app_to_orario > '18:00'){
    ?>

    <?php
    exit;
    }

the problem I have is that if for example the user chooses to book an appointment for 16:00, the chosen time is correct, but I always get an error because for example in the second cycle 16:00 it is greater than 13:00 even if it falls correctly in the remaining 3 control cycles, so how do I perform a time check allowing the appointment in the time slots indicated in the question, without always running into a false result?

Body:
In your case, $app_to_orario is a string, not a DateTime. To compare with other date/time, it needs to be converted to DateTime first:

$ato = new DateTime($app_to_orario);

Or use Carbon:

$ato = new Carbon($app_to_orario);

Then compare the time(with Carbon):

if($ato->hour<11){
    ...
}

Or without Carbon:

if(intval($ato->format('H'))<11){
    ...
}


来源: stackexchange

问:
Scheduled Sql Server Policy against Central Management Server group
Does anyone know of a way to run a policy against a Central Management Server group?  In other words, run one policy off the Central Management Server that evaluates against x number of servers.  I want to run this on a scheduled basis.  It seems like a fairly common scenario to me, yet I can't seem to get it figured.

Apologies if this has been asked before, my stack-fu and google-fu seem to be missing the mark tonight.

B

答: Take a look at the Enterprise Policy Management Framework on codeplex http://epmframework.codeplex.com/. There's a bunch of reports which go with it as well.</p>

ContentLicense: CC BY-SA 3.0


问:
Combining two "for" to integrate a progress bar while deleting line in a text file in Python?
I manage to make two python script to work independently. The first one is about looking for a string in a text file and deleting all lines with this string.

```<code>bad_words = ['first.com','second.org','third.io']

with open('input.txt') as oldfile, open('output.txt', 'w') as newfile:
    for line in oldfile:
        if not any(bad_word in line for bad_word in bad_words):
            newfile.write(line)
</code>```

The process is quite long because the input as nearly 1 000 000 lines and the bad_words are close to 100 entries.

So I would like to show a progress bar in the terminal while proceeding. I found this, and it is working, incrementing the bar every 1/10 of a second.

```<code>import time

# Print iterations progress
def printProgressBar (iteration, total, prefix = '', suffix = '', decimals = 1, length = 100, fill = '█', printEnd = "\r"):
    """
    Call in a loop to create terminal progress bar
    @params:
        iteration   - Required  : current iteration (Int)
        total       - Required  : total iterations (Int)
        prefix      - Optional  : prefix string (Str)
        suffix      - Optional  : suffix string (Str)
        decimals    - Optional  : positive number of decimals in percent complete (Int)
        length      - Optional  : character length of bar (Int)
        fill        - Optional  : bar fill character (Str)
        printEnd    - Optional  : end character (e.g. "\r", "\r\n") (Str)
    """
    percent = ("{0:." + str(decimals) + "f}").format(100 * (iteration / float(total)))
    filledLength = int(length * iteration // total)
    bar = fill * filledLength + '-' * (length - filledLength)
    print('\r%s |%s| %s%% %s' % (prefix, bar, percent, suffix), end = printEnd)
    # Print New Line on Complete
    if iteration == total:
        print()

# A List of Items
items = list(range(0, 57))
l = len(items)

# Initial call to print 0% progress
printProgressBar(0, l, prefix = 'Progress:', suffix = 'Complete', length = 50)
for i, item in enumerate(items):
    # Do stuff...
    time.sleep(0.1)
    # Update Progress Bar
    printProgressBar(i + 1, l, prefix = 'Progress:', suffix = 'Complete', length = 50)
</code>```

Instead of a time sleep, I want the progress bar to move forward while each word from bad_words is being processed.

So I came up with that :

```<code>def printProgressBar (iteration, total, prefix = '', suffix = '', decimals = 1, length = 100, fill = '█', printEnd = "\r"):

    percent = ("{0:." + str(decimals) + "f}").format(100 * (iteration / float(total)))
    filledLength = int(length * iteration // total)
    bar = fill * filledLength + '-' * (length - filledLength)
    print('\r%s |%s| %s%% %s' % (prefix, bar, percent, suffix), end = printEnd)
    # Print New Line on Complete
    if iteration == total:
        print()

items = ['first.com','second.org','third.io']
l = len(items)

printProgressBar(0, l, prefix = 'Progress:', suffix = 'Complete', length = 50)
with open('input.txt') as oldfile, open('output.txt', 'w') as newfile:
    for line in oldfile:
        if not any(items in line for item in items):
            newfile.write(line)
    for i, item in enumerate(items):
    # Update Progress Bar
        printProgressBar(i + 1, l, prefix = 'Progress:', suffix = 'Complete', length = 50)
</code>```

It seems combining the "For If" isn't proper.

答:
As @KarlKnechtel suggested the way to do it is to count processed lines and not the "bad_words" as they are processed all together at the time.

Adding the progress bar makes the whole script much slower so I will try to make it more efficient.

```<code>import time

# Print iterations progress
def printProgressBar (iteration, total, prefix = '', suffix = '', decimals = 1, length = 100, fill = '█', printEnd = "\r"):
    """
    Call in a loop to create terminal progress bar
    @params:
        iteration   - Required  : current iteration (Int)
        total       - Required  : total iterations (Int)
        prefix      - Optional  : prefix string (Str)
        suffix      - Optional  : suffix string (Str)
        decimals    - Optional  : positive number of decimals in percent complete (Int)
        length      - Optional  : character length of bar (Int)
        fill        - Optional  : bar fill character (Str)
        printEnd    - Optional  : end character (e.g. "\r", "\r\n") (Str)
    """
    percent = ("{0:." + str(decimals) + "f}").format(100 * (iteration / float(total)))
    filledLength = int(length * iteration // total)
    bar = fill * filledLength + '-' * (length - filledLength)
    print('\r%s |%s| %s%% %s' % (prefix, bar, percent, suffix), end = printEnd)
    # Print New Line on Complete
    if iteration == total:
        print()

fname = "A+B_net.txt"
count = 0
with open(fname, 'r') as f:
    for line in f:
        count += 1
print("Total number of lines is:", count)

l = count

bad_words = ['geovisite.com','cable.dyn.cableonline.com.mx']
printProgressBar(0, l, prefix = 'Avancement:', suffix = 'Completé', length = 50)

with open('A+B_net.txt') as oldfile, open('A+B_sub.txt', 'w') as newfile:
        # for i, line in oldfile:
        for i, line in enumerate(oldfile, 1):
        # for i, item in enumerate(items):
            if not any(bad_word in line for bad_word in bad_words):
                newfile.write(line)
                printProgressBar(i + 1, l, prefix = 'Avancement:', suffix = 'Completé', length = 50)
print("suppression des sous domaines terminé")
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I manage to make two python script to work independently. The first one is about looking for a string in a text file and deleting all lines with this string.

bad_words = ['first.com','second.org','third.io']

with open('input.txt') as oldfile, open('output.txt', 'w') as newfile:
    for line in oldfile:
        if not any(bad_word in line for bad_word in bad_words):
            newfile.write(line)

The process is quite long because the input as nearly 1 000 000 lines and the bad_words are close to 100 entries.

So I would like to show a progress bar in the terminal while proceeding. I found this, and it is working, incrementing the bar every 1/10 of a second.

import time

# Print iterations progress
def printProgressBar (iteration, total, prefix = '', suffix = '', decimals = 1, length = 100, fill = '█', printEnd = "\r"):
    """
    Call in a loop to create terminal progress bar
    @params:
        iteration   - Required  : current iteration (Int)
        total       - Required  : total iterations (Int)
        prefix      - Optional  : prefix string (Str)
        suffix      - Optional  : suffix string (Str)
        decimals    - Optional  : positive number of decimals in percent complete (Int)
        length      - Optional  : character length of bar (Int)
        fill        - Optional  : bar fill character (Str)
        printEnd    - Optional  : end character (e.g. "\r", "\r\n") (Str)
    """
    percent = ("{0:." + str(decimals) + "f}").format(100 * (iteration / float(total)))
    filledLength = int(length * iteration // total)
    bar = fill * filledLength + '-' * (length - filledLength)
    print('\r%s |%s| %s%% %s' % (prefix, bar, percent, suffix), end = printEnd)
    # Print New Line on Complete
    if iteration == total:
        print()

# A List of Items
items = list(range(0, 57))
l = len(items)

# Initial call to print 0% progress
printProgressBar(0, l, prefix = 'Progress:', suffix = 'Complete', length = 50)
for i, item in enumerate(items):
    # Do stuff...
    time.sleep(0.1)
    # Update Progress Bar
    printProgressBar(i + 1, l, prefix = 'Progress:', suffix = 'Complete', length = 50)

Instead of a time sleep, I want the progress bar to move forward while each word from bad_words is being processed.

So I came up with that :

def printProgressBar (iteration, total, prefix = '', suffix = '', decimals = 1, length = 100, fill = '█', printEnd = "\r"):

    percent = ("{0:." + str(decimals) + "f}").format(100 * (iteration / float(total)))
    filledLength = int(length * iteration // total)
    bar = fill * filledLength + '-' * (length - filledLength)
    print('\r%s |%s| %s%% %s' % (prefix, bar, percent, suffix), end = printEnd)
    # Print New Line on Complete
    if iteration == total:
        print()

items = ['first.com','second.org','third.io']
l = len(items)

printProgressBar(0, l, prefix = 'Progress:', suffix = 'Complete', length = 50)
with open('input.txt') as oldfile, open('output.txt', 'w') as newfile:
    for line in oldfile:
        if not any(items in line for item in items):
            newfile.write(line)
    for i, item in enumerate(items):
    # Update Progress Bar
        printProgressBar(i + 1, l, prefix = 'Progress:', suffix = 'Complete', length = 50)

It seems combining the "For If" isn't proper.

Body:
As @KarlKnechtel suggested the way to do it is to count processed lines and not the "bad_words" as they are processed all together at the time.

Adding the progress bar makes the whole script much slower so I will try to make it more efficient.

import time

# Print iterations progress
def printProgressBar (iteration, total, prefix = '', suffix = '', decimals = 1, length = 100, fill = '█', printEnd = "\r"):
    """
    Call in a loop to create terminal progress bar
    @params:
        iteration   - Required  : current iteration (Int)
        total       - Required  : total iterations (Int)
        prefix      - Optional  : prefix string (Str)
        suffix      - Optional  : suffix string (Str)
        decimals    - Optional  : positive number of decimals in percent complete (Int)
        length      - Optional  : character length of bar (Int)
        fill        - Optional  : bar fill character (Str)
        printEnd    - Optional  : end character (e.g. "\r", "\r\n") (Str)
    """
    percent = ("{0:." + str(decimals) + "f}").format(100 * (iteration / float(total)))
    filledLength = int(length * iteration // total)
    bar = fill * filledLength + '-' * (length - filledLength)
    print('\r%s |%s| %s%% %s' % (prefix, bar, percent, suffix), end = printEnd)
    # Print New Line on Complete
    if iteration == total:
        print()

fname = "A+B_net.txt"
count = 0
with open(fname, 'r') as f:
    for line in f:
        count += 1
print("Total number of lines is:", count)

l = count

bad_words = ['geovisite.com','cable.dyn.cableonline.com.mx']
printProgressBar(0, l, prefix = 'Avancement:', suffix = 'Completé', length = 50)

with open('A+B_net.txt') as oldfile, open('A+B_sub.txt', 'w') as newfile:
        # for i, line in oldfile:
        for i, line in enumerate(oldfile, 1):
        # for i, item in enumerate(items):
            if not any(bad_word in line for bad_word in bad_words):
                newfile.write(line)
                printProgressBar(i + 1, l, prefix = 'Avancement:', suffix = 'Completé', length = 50)
print("suppression des sous domaines terminé")


问:
Not Acceptable! An appropriate representation of the requested resource could not be found on this server. This error was generated by Mod_Security
I'm new to moodle environment and I'm having this error:

Not Acceptable!

An appropriate representation of the requested resource could not be
  found on this server. This error was generated by Mod_Security.

I haven't done anything, I'm just viewing the registered users in my website:

http://www.joyfementira.com/dnsc/it14lms
 I've noticed that my profile picture is not properly loaded so I clicked on it (picture's position), and after that the error came out.

What probably caused this error and how would I fix it?

答:
Just to add to the answers. If this happens while you are trying to login to a WordPress website admin and you are using any type of VPN on your machine, you'd have to turn it off to solve the problem.

If you turn off your VPN, you'd be able to login without experiencing the issue.


问:
Two-way data binding using custom attributes on a Switch component using MVVM Android
I'm trying to create a two-way data binding on a Switch component, using MVVM and LiveData, but I always receive a

error: cannot find symbol

on DataBinderMapperImpl.java, and also i have:

A failure occurred while executing org.jetbrains.kotlin.gradle.internal.KaptExecution

Any help? Thanks

The property in the ViewModel

```<code>private val _numbers = MutableLiveData<Boolean>()
val numbers: LiveData<Boolean>
    get() = _numbers
</code>```

BindingAdapter

```<code>@BindingAdapter("numberSwitchAttrChanged")
fun setListeners(view: CompoundButton, attrChange: InverseBindingListener) {
    view.setOnCheckedChangeListener { _, _ -> attrChange.onChange() }
}

@BindingAdapter("numbersSwitch")
fun setNumbersSwitch(view: CompoundButton, isChecked: Boolean) {
    if (view.isChecked != isChecked) {
        view.isChecked = isChecked
    }
}

@InverseBindingAdapter(attribute = "numbersSwitch")
fun getNumbersSwitch(view: CompoundButton): Boolean {
    return view.isChecked
}
</code>```

XML

```<code><Switch
    android:id="@+id/numbersSwitch"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginTop="24dp"
    app:numbersSwitch="@={viewModel.numbers}"
    app:layout_constraintEnd_toStartOf="@+id/guideline3"
    app:layout_constraintLeft_toRightOf="@+id/lengthText"
    app:layout_constraintTop_toBottomOf="@+id/lengthText" />
</code>```

答:
I resolved whit added onCheckedChanged property on XML

```<code><Switch
    android:id="@+id/numbersSwitch"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginTop="24dp"
    android:checked="@{viewModel.numbersSwitch}"
    android:onCheckedChanged="@{(button, on)-> viewModel.setNumbersSwitch(on)}"
    app:layout_constraintEnd_toStartOf="@+id/guideline3"
    app:layout_constraintLeft_toRightOf="@+id/lengthText"
    app:layout_constraintTop_toBottomOf="@+id/lengthText" />
</code>```

and define the function setNumbersSwitch in ViewModel and removed BindingAdapter

```<code>fun setNumbersSwitch(isChecked: Boolean) {
    when (isChecked) {
        true -> _numbersSwitch.value = true
        false -> _numbersSwitch.value = false
    }
}
</code>```

Body:
I'm trying to create a two-way data binding on a Switch component, using MVVM and LiveData, but I always receive a

error: cannot find symbol

on DataBinderMapperImpl.java, and also i have:

A failure occurred while executing org.jetbrains.kotlin.gradle.internal.KaptExecution

Any help? Thanks

The property in the ViewModel

private val _numbers = MutableLiveData<Boolean>()
val numbers: LiveData<Boolean>
    get() = _numbers

BindingAdapter

@BindingAdapter("numberSwitchAttrChanged")
fun setListeners(view: CompoundButton, attrChange: InverseBindingListener) {
    view.setOnCheckedChangeListener { _, _ -> attrChange.onChange() }
}

@BindingAdapter("numbersSwitch")
fun setNumbersSwitch(view: CompoundButton, isChecked: Boolean) {
    if (view.isChecked != isChecked) {
        view.isChecked = isChecked
    }
}

@InverseBindingAdapter(attribute = "numbersSwitch")
fun getNumbersSwitch(view: CompoundButton): Boolean {
    return view.isChecked
}

XML

<Switch
    android:id="@+id/numbersSwitch"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginTop="24dp"
    app:numbersSwitch="@={viewModel.numbers}"
    app:layout_constraintEnd_toStartOf="@+id/guideline3"
    app:layout_constraintLeft_toRightOf="@+id/lengthText"
    app:layout_constraintTop_toBottomOf="@+id/lengthText" />

Body:
I resolved whit added onCheckedChanged property on XML

<Switch
    android:id="@+id/numbersSwitch"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginTop="24dp"
    android:checked="@{viewModel.numbersSwitch}"
    android:onCheckedChanged="@{(button, on)-> viewModel.setNumbersSwitch(on)}"
    app:layout_constraintEnd_toStartOf="@+id/guideline3"
    app:layout_constraintLeft_toRightOf="@+id/lengthText"
    app:layout_constraintTop_toBottomOf="@+id/lengthText" />

and define the function setNumbersSwitch in ViewModel and removed BindingAdapter

fun setNumbersSwitch(isChecked: Boolean) {
    when (isChecked) {
        true -> _numbersSwitch.value = true
        false -> _numbersSwitch.value = false
    }
}


问:
Azure pipelines: error MSB4019 WebApplication.targets was not found
I created an episerver alloy project, which builds and runs fine in visual studio after setting up some nuget packages, and I can deploy to azure and run in azure from VS without issue.

I am now trying to get the build to work in pipelines.

Following the instructions, I added a "nuget restore" task, and pointed it at a NuGet.config.
This works.

Then it gets to the build stage, and gives:

D:\a\1\s\DxcAlloy.csproj(335,3): error MSB4019: The imported project "C:\Program Files\dotnet\sdk\3.1.202\Microsoft\VisualStudio\v16.0\WebApplications\Microsoft.WebApplication.targets" was not found. Confirm that the expression in the Import declaration "C:\Program Files\dotnet\sdk\3.1.202\Microsoft\VisualStudio\v16.0\WebApplications\Microsoft.WebApplication.targets" is correct, and that the file exists on disk.

I have no idea how to debug this.  Some posts say that error can happen if you dont have visual studio installed, but I cant install visual studio on azure pipelines...

I removed the existing ".net restore" task, as it failed, and am guessing that just my nuget restore is all I need - this is a guess.

The pipeline "agent specification" is vs2017-win16

The project was created in VS 2019.

In desperation, I added a "Use .NET core" task, and set the version to the one which build is complaining is missing, i.e. 3.1.202.

This didn't help.

Any ideas?

答:
If you build your project using dotnet build task. Below configuration in your .csproj file will be evaluated to C:\Program Files\dotnet\sdk\3.1.202\Microsoft\VisualStudio\v16.0\WebApplications\Microsoft.WebApplication.targets (What you see from the error)

<VSToolsPath Condition="'$(VSToolsPath)' == ''">$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v16.0</VSToolsPath>
<Import Project="$(VSToolsPath)\WebApplications\Microsoft.WebApplication.targets" />

Microsoft.WebApplication.targets usually exists in below location. That is why it errors out ...Microsoft.WebApplication.targets not found.

In Visual Studio 2017 "C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\MSBuild\Microsoft\VisualStudio\v15.0\WebApplications\Microsoft.WebApplication.targets"

In Visual Studio 2019 "C:\Program Files (x86)\Microsoft Visual Studio\2019\Enterprise\MSBuild\Microsoft\VisualStudio\v16.0\WebApplications\Microsoft.WebApplication.targets"

The workaround for above issue is using Msbuid task or Visual Studio build task to build your projects. See below example:

```<code>- task: VSBuild@1
    inputs:
      solution: '**/*.csproj'
    enabled: true
</code>```

For your case, you also need to set agent specification to agent windows-latest. For visual studio 2019(v16.0) is only installed in agent windows-latest.

If you have to run your pipeline on agent "vs2017-win16" (only visual studio 2017(v15.0) is installed). You need to change the VSToolsPath in the .csproj file to <VSToolsPath Condition="'$(VSToolsPath)' == ''">$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v15.0</VSToolsPath>

If you have to use dotnet build to build your projects. You can hard code the import path in csproj file as workaround.

<Import Project="C:\Program Files (x86)\Microsoft Visual Studio\2019\Enterprise\MSBuild\Microsoft\VisualStudio\v16.0\WebApplications\Microsoft.WebApplication.targets" />

Body:
If you build your project using dotnet build task. Below configuration in your .csproj file will be evaluated to C:\Program Files\dotnet\sdk\3.1.202\Microsoft\VisualStudio\v16.0\WebApplications\Microsoft.WebApplication.targets (What you see from the error)

<VSToolsPath Condition="'$(VSToolsPath)' == ''">$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v16.0</VSToolsPath>
<Import Project="$(VSToolsPath)\WebApplications\Microsoft.WebApplication.targets" />

Microsoft.WebApplication.targets usually exists in below location. That is why it errors out ...Microsoft.WebApplication.targets not found.

In Visual Studio 2017 "C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\MSBuild\Microsoft\VisualStudio\v15.0\WebApplications\Microsoft.WebApplication.targets"

In Visual Studio 2019 "C:\Program Files (x86)\Microsoft Visual Studio\2019\Enterprise\MSBuild\Microsoft\VisualStudio\v16.0\WebApplications\Microsoft.WebApplication.targets"

The workaround for above issue is using Msbuid task or Visual Studio build task to build your projects. See below example:

- task: VSBuild@1
    inputs:
      solution: '**/*.csproj'
    enabled: true

For your case, you also need to set agent specification to agent windows-latest. For visual studio 2019(v16.0) is only installed in agent windows-latest.

If you have to run your pipeline on agent "vs2017-win16" (only visual studio 2017(v15.0) is installed). You need to change the VSToolsPath in the .csproj file to <VSToolsPath Condition="'$(VSToolsPath)' == ''">$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v15.0</VSToolsPath>

If you have to use dotnet build to build your projects. You can hard code the import path in csproj file as workaround.

<Import Project="C:\Program Files (x86)\Microsoft Visual Studio\2019\Enterprise\MSBuild\Microsoft\VisualStudio\v16.0\WebApplications\Microsoft.WebApplication.targets" />


问:
How to add time zone to specific format in momentjs?
I am trying to get specific format of datetime with time zone

i am getting string of time format which is shown below

```<code>var dateTime = "2020-06-01T01:50:57.000Z CDT"
</code>```

I need to convert the format in to

```<code> const offsetTime = moment(date).add("-0.00", 'hours')
 const formatedDate = moment(offsetTime, 'h:mm:ss A')
.utc()
.format('h:mm A')//(1:50 AM)
</code>```

Required output

```<code>(1:50 AM CDT)
</code>```

Do i need to split the string and get the format or do we have any method to convert it to this format in momentjs

In simple way to say

```<code>YYYY-MM-DDTHH:mm:ss.SSS[Z] z To hh:mm A z //format
</code>```

and if the string contains only 2 character like "CT" instead of CDT how to capture that.

答:
Use the moment-timezone to achieve this. Use the moment constructor to specify the input format, then specifying the required timezone. Finally use moment's format to get the required format

var dateTime = "2020-06-01T01:50:57.000Z CDT";
var timezone = "America/Chicago";
console.log(
  moment(dateTime, "YYYY-MM-DD hh:mm:ss zz")
.tz(timezone)
.format("h:mm A zz")
);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://momentjs.com/downloads/moment.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment-timezone/0.5.23/moment-timezone-with-data-2012-2022.min.js"></script></code>```

Body:
I am trying to get specific format of datetime with time zone

i am getting string of time format which is shown below

var dateTime = "2020-06-01T01:50:57.000Z CDT"

I need to convert the format in to

 const offsetTime = moment(date).add("-0.00", 'hours')
 const formatedDate = moment(offsetTime, 'h:mm:ss A')
.utc()
.format('h:mm A')//(1:50 AM)

Required output

(1:50 AM CDT)

Do i need to split the string and get the format or do we have any method to convert it to this format in momentjs

In simple way to say

YYYY-MM-DDTHH:mm:ss.SSS[Z] z To hh:mm A z //format

and if the string contains only 2 character like "CT" instead of CDT how to capture that.

Body:
Use the moment-timezone to achieve this. Use the moment constructor to specify the input format, then specifying the required timezone. Finally use moment's format to get the required format

var dateTime = "2020-06-01T01:50:57.000Z CDT";
var timezone = "America/Chicago";
console.log(
  moment(dateTime, "YYYY-MM-DD hh:mm:ss zz")
.tz(timezone)
.format("h:mm A zz")
);

<script src="https://momentjs.com/downloads/moment.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment-timezone/0.5.23/moment-timezone-with-data-2012-2022.min.js"></script>


问:
Connect nestjs to redis using Docker Compose
I am trying to connect my Nestjs application to Redis as follows:

This the content of my docker-compose.yml

```<code>version: '3.7'

services:
  main:
    container_name: main
    build:
      context: .
      target: development
    volumes:
      - .:/usr/src/app
      - /usr/src/app/node_modules
    ports:
      - ${PORT}:${PORT}
      - 9229:9229
    command: yarn start:dev
    env_file:
      - .env

    networks:
      - webnet
  redis:
    image: 'redis:alpine'

networks:
  webnet:
</code>```

In order to boostrap redis functionality in my nestjs application, I am using nestjs-redis and the relevant portion of app.module.ts looks like this:

import { RedisModule } from 'nestjs-redis';

@Module({
 imports: [
  RedisModule.register({})
 ]
})
```

However, when I try to run docker-compose up in my setup, I get the following error:

[ioredis] Unhandled error event: Error: connect ECONNREFUSED 127.0.0.1:6379

Thank you for helping!

答:
As you are using docker-compose.yml, try to use the internal links capability.

```<code>version: '3.7'

services:
  main:
    container_name: main
    build:
      context: .
      target: development
    volumes:
      - .:/usr/src/app
      - /usr/src/app/node_modules
    ports:
      - ${PORT}:${PORT}
      - 9229:9229
    command: yarn start:dev
    links:
      - redis
    env_file:
      - .env
    networks:
      - webnet
  redis:
    image: 'redis:alpine'
    ports:
      - 6379:6379
    networks:
      - webnet

networks:
  webnet:
</code>```

and in your snippet, pass the host in the following manner

```<code>import { RedisModule } from 'nestjs-redis';

@Module({
 imports: [
  RedisModule.register({host: "redis"})
 ]
})
</code>```

Body:
I am trying to connect my Nestjs application to Redis as follows:

This the content of my docker-compose.yml

version: '3.7'

services:
  main:
    container_name: main
    build:
      context: .
      target: development
    volumes:
      - .:/usr/src/app
      - /usr/src/app/node_modules
    ports:
      - ${PORT}:${PORT}
      - 9229:9229
    command: yarn start:dev
    env_file:
      - .env

    networks:
      - webnet
  redis:
    image: 'redis:alpine'

networks:
  webnet:

In order to boostrap redis functionality in my nestjs application, I am using nestjs-redis and the relevant portion of app.module.ts looks like this:

import { RedisModule } from 'nestjs-redis';

@Module({
 imports: [
  RedisModule.register({})
 ]
})

However, when I try to run docker-compose up in my setup, I get the following error:

[ioredis] Unhandled error event: Error: connect ECONNREFUSED 127.0.0.1:6379

Thank you for helping!

Body:
As you are using docker-compose.yml, try to use the internal links capability.

version: '3.7'

services:
  main:
    container_name: main
    build:
      context: .
      target: development
    volumes:
      - .:/usr/src/app
      - /usr/src/app/node_modules
    ports:
      - ${PORT}:${PORT}
      - 9229:9229
    command: yarn start:dev
    links:
      - redis
    env_file:
      - .env
    networks:
      - webnet
  redis:
    image: 'redis:alpine'
    ports:
      - 6379:6379
    networks:
      - webnet

networks:
  webnet:

and in your snippet, pass the host in the following manner

import { RedisModule } from 'nestjs-redis';

@Module({
 imports: [
  RedisModule.register({host: "redis"})
 ]
})


问:
How to keep the legend when I save a matplotlib figure as .png
I'm trying to save a matplotlib time series plot as png. When I generate the graph I produce also the legend, but I cannot save it in in the .png figure. I cannot save the legend.

```<code>data_df['point'].plot(linestyle='dashed', label='points')
plt.title('trial')
plt.ylabel('N. of points')
plt.xlabel('Time (days)')
plt.legend(loc='best', frameon=True)
plt.show(block = True)
plt.savefig('figures\\'+'case_1'+'.png', format ='png')
</code>```

The data looks like:

```<code>Date
2010-01-06    7.54
2010-02-06    9.09
2010-03-06    7.91
2010-04-06    13.27
2010-05-06    7.86
               ...
2020-03-19    11.95
2020-03-20    8.17
2020-03-21    10.29
2020-03-22    15.86
2020-03-23    7.36
Name: point, Length: 3324, dtype: float64
</code>```

Does anyone know how to keep the legend in my .png figure?

答: If you pass bbox_inches='tight' to .savefig(), it should keep the legend close enough not to get cut off.

Body:
I'm trying to save a matplotlib time series plot as png. When I generate the graph I produce also the legend, but I cannot save it in in the .png figure. I cannot save the legend.

data_df['point'].plot(linestyle='dashed', label='points')
plt.title('trial')
plt.ylabel('N. of points')
plt.xlabel('Time (days)')
plt.legend(loc='best', frameon=True)
plt.show(block = True)
plt.savefig('figures\\'+'case_1'+'.png', format ='png')

The data looks like:

Date
2010-01-06    7.54
2010-02-06    9.09
2010-03-06    7.91
2010-04-06    13.27
2010-05-06    7.86
               ...
2020-03-19    11.95
2020-03-20    8.17
2020-03-21    10.29
2020-03-22    15.86
2020-03-23    7.36
Name: point, Length: 3324, dtype: float64

Does anyone know how to keep the legend in my .png figure?


问:
Swift: How to transition from Navigation Controller to Tab Bar Controler
SoI have a Tab bar based app, but which is supposed to go trough a login / Signup process first. The Signup and Login works fine and I was able to move to a new ViewController and set it to be the new root VC with a function
`
func transitionToHome(){

```<code>    let homeViewController = storyboard?.instantiateViewController(identifier: Constants.Storybord.HomeViewController) as? homeViewController

    view.window?.rootViewController = homeViewController
    view.window?.makeKeyAndVisible()
}`
</code>```

This was all working fine and I decided to move along and start building the tabbed ui, thats when I ran intro problems. As seen in my Main Storyboard can be seen here, the structure is simple. How do I connect the Login and Signup Buttons with something else than a ViewController, so for example the Tab Bar Controller? I managed to get to one of the Tabs but that didn't cut it either because I would then lose the ability to navigate between them.. I am in my first days of swift so I would love to hear any tips. I bet its not that hard after all.

Right now I am trying to get it to work by giving my Tab Bar Controller a Storyboard ID which I am then looking for in my modified version of the code above. Since i cannot add a ViewController for the Tab Bar Controller I am then starting the Tab Bar Item I want to have as default, but this just gives me a black screen..

答:
Okey I found the issue. Thanks @Paulw11 for pointing out that a Tab Bar Viewcontroller can be used just like a normal view controller. The problem was the part "
as? MainViewController", this had to say as? UITabBarController and voila, it worked. For anyone in the future, thats how you do it. </p>

Body:
SoI have a Tab bar based app, but which is supposed to go trough a login / Signup process first. The Signup and Login works fine and I was able to move to a new ViewController and set it to be the new root VC with a function
`
func transitionToHome(){

    let homeViewController = storyboard?.instantiateViewController(identifier: Constants.Storybord.HomeViewController) as? homeViewController

    view.window?.rootViewController = homeViewController
    view.window?.makeKeyAndVisible()
}`

This was all working fine and I decided to move along and start building the tabbed ui, thats when I ran intro problems. As seen in my Main Storyboard can be seen here, the structure is simple. How do I connect the Login and Signup Buttons with something else than a ViewController, so for example the Tab Bar Controller? I managed to get to one of the Tabs but that didn't cut it either because I would then lose the ability to navigate between them.. I am in my first days of swift so I would love to hear any tips. I bet its not that hard after all.

Right now I am trying to get it to work by giving my Tab Bar Controller a Storyboard ID which I am then looking for in my modified version of the code above. Since i cannot add a ViewController for the Tab Bar Controller I am then starting the Tab Bar Item I want to have as default, but this just gives me a black screen..


问:
How can I create an NSMutableArray of structs?
I created a structure like this

```<code>typedef struct Node {
    NSString* Description;
    NSString* AE;
    NSString* IP;
    NSString*  Port;
} Node;
</code>```

I need to create NSMutableArray of this Node structure I need to know how create object of node path it to the NSMutableArray retrieve it and read for example the port.

答:
You can actually create a custom class (since it holds only NSString pointers) with struct values as instance variables. I think it'd even make more sense.

You can also create an array of NSValues which hold these structures:

```<code>NSValue *structValue = [NSValue value:&myNode objCType:@encode(Node *)];
NSMutableArray *array = [[NSMutableArray alloc] initWithObject:structValue];
</code>```

You can then retreive these structs as follows:

```<code>NSValue *structValue = [array objectAtIndex:0];
Node *myNode = (Node *)[structValue pointerValue];
// or
Node myNode = *(Node *)[structValue pointerValue];
</code>```

Body:
I created a structure like this

typedef struct Node {
    NSString* Description;
    NSString* AE;
    NSString* IP;
    NSString*  Port;
} Node;

I need to create NSMutableArray of this Node structure I need to know how create object of node path it to the NSMutableArray retrieve it and read for example the port.

Body:
You can actually create a custom class (since it holds only NSString pointers) with struct values as instance variables. I think it'd even make more sense.

You can also create an array of NSValues which hold these structures:

NSValue *structValue = [NSValue value:&myNode objCType:@encode(Node *)];
NSMutableArray *array = [[NSMutableArray alloc] initWithObject:structValue];

You can then retreive these structs as follows:

NSValue *structValue = [array objectAtIndex:0];
Node *myNode = (Node *)[structValue pointerValue];
// or
Node myNode = *(Node *)[structValue pointerValue];


问:
Regex Python french accent
I use this code: b = re.sub('[^A-Za-z]+', ' ', a). Nevertheless i need to take account of the french accents: àâéèêëïîôùûç. Can you please help me? :)

Thanks.

答:
Regex for accented characters has been covered before really well over here.

If you're dealing with French accents (not umlauts etc) then you're code could be updated like this:

```<code>b = re.sub('[^A-zÀ-ú]+', ' ', a)
</code>```

That should amend your previous "all upper and lower case letters" to "all upper and lower case letters including accents"

Title: Regex Python french accent

Body:
Regex for accented characters has been covered before really well over here.

If you're dealing with French accents (not umlauts etc) then you're code could be updated like this:

b = re.sub('[^A-zÀ-ú]+', ' ', a)

That should amend your previous "all upper and lower case letters" to "all upper and lower case letters including accents"


问:
Windows forms ToolTip property "ShowAlways" not working when parent object is disabled
According to the Microsoft developer documentation there's a ToolTip property called ShowAlways which according to the documentation;

With the ShowAlways property, you can display a ToolTip window even when the container of the ToolTip is not active. You can use this feature in a modeless window application to enable ToolTip windows to be displayed regardless of which modeless window is active.

With the below example code I can't make this work.

```<code>$Form                            = New-Object system.Windows.Forms.Form
$Form.ClientSize                 = '200,100'
$Form.text                       = "test"
$Form.TopMost                    = $false
$Form.FormBorderStyle            = 'FixedDialog'
$Form.MaximizeBox                = $false
$Form.StartPosition              = 'CenterScreen'

$checkbox1                       = New-Object system.Windows.Forms.CheckBox
$checkbox1.text                  = "Test"
$checkbox1.AutoSize              = $true
$checkbox1.width                 = 100
$checkbox1.height                = 20
$checkbox1.location              = New-Object System.Drawing.Point(10,50)
$checkbox1.Font                  = 'Verdana,7'

#Disable checkbox enabled state
$checkbox1.Enabled               = $false

$tooltip1                        = New-Object System.Windows.Forms.ToolTip
#Showalways property to true
$tooltip1.ShowAlways             = $true
$tooltip1.SetToolTip($checkbox1,"This is a tooltip.")
$Form.controls.AddRange($checkbox1)

$Form.ShowDialog()
</code>```

Am I missing something?

答:
I ended up removing the text from the checkbox and replaced it with a label instead so that I can use the ToolTip on that, and added an OnClick action to the label for QoL if the checkbox state is enabled.

Maybe it isn't the best and most beautiful solution, but it's one that works and gets the job done until (or if) disabled checkboxes support ToolTips in the future.

Body:
According to the Microsoft developer documentation there's a ToolTip property called ShowAlways which according to the documentation;

With the ShowAlways property, you can display a ToolTip window even when the container of the ToolTip is not active. You can use this feature in a modeless window application to enable ToolTip windows to be displayed regardless of which modeless window is active.

With the below example code I can't make this work.

$Form                            = New-Object system.Windows.Forms.Form
$Form.ClientSize                 = '200,100'
$Form.text                       = "test"
$Form.TopMost                    = $false
$Form.FormBorderStyle            = 'FixedDialog'
$Form.MaximizeBox                = $false
$Form.StartPosition              = 'CenterScreen'

$checkbox1                       = New-Object system.Windows.Forms.CheckBox
$checkbox1.text                  = "Test"
$checkbox1.AutoSize              = $true
$checkbox1.width                 = 100
$checkbox1.height                = 20
$checkbox1.location              = New-Object System.Drawing.Point(10,50)
$checkbox1.Font                  = 'Verdana,7'

#Disable checkbox enabled state
$checkbox1.Enabled               = $false

$tooltip1                        = New-Object System.Windows.Forms.ToolTip
#Showalways property to true
$tooltip1.ShowAlways             = $true
$tooltip1.SetToolTip($checkbox1,"This is a tooltip.")
$Form.controls.AddRange($checkbox1)

$Form.ShowDialog()

Am I missing something?


问:
Get name of test method in setUp (Xcode)
I want to append a message to a log that includes the name of the test method that is about to be run. I want to do this in my setUp method in my test superclass so I don't have repeated code everywhere.

I wanted to do something like this:

```<code>- (void) setUp {
    [super setUp];
    [self log:@NSStringFromSelector(_cmd)];
}
</code>```

However, _cmd always gives "setUp" as its string, whereas I want "test00TestTheThing"

Is there a way to do this?

答:
Don't know if it's still relevant but if someone needs it:

you can use the self.name and then you'll get the name of the class with the name of the test.

To remove the class name and just stay with the test name, use the replacingOccurrences func

example:

```<code>class ClassName: XCTestCase {
    override func setUp() {
      // get the name and remove the class name and what comes before the class name
      var currentTestName = self.name.replacingOccurrences(of: "-[ClassName ", with: "")

      // And then you'll need to remove the closing square bracket at the end of the test name

      currentTestName = currentTestName.replacingOccurrences(of: "]", with: "")
    }
</code>```

Body:
I want to append a message to a log that includes the name of the test method that is about to be run. I want to do this in my setUp method in my test superclass so I don't have repeated code everywhere.

I wanted to do something like this:

- (void) setUp {
    [super setUp];
    [self log:@NSStringFromSelector(_cmd)];
}

However, _cmd always gives "setUp" as its string, whereas I want "test00TestTheThing"

Is there a way to do this?

Body:
Don't know if it's still relevant but if someone needs it:

you can use the self.name and then you'll get the name of the class with the name of the test.

To remove the class name and just stay with the test name, use the replacingOccurrences func

example:

class ClassName: XCTestCase {
    override func setUp() {
      // get the name and remove the class name and what comes before the class name
      var currentTestName = self.name.replacingOccurrences(of: "-[ClassName ", with: "")

      // And then you'll need to remove the closing square bracket at the end of the test name

      currentTestName = currentTestName.replacingOccurrences(of: "]", with: "")
    }


问:
Snowflake Stages - Can nt see
We have been loading data through ETL tool to snowflake tables, however when I executed "show stages in account " command in snowflake, it did not return any stages defined. I do not think any one of us have created external stages yet, but I was expecting to see at least the result of Snowflake managed internal stage.

Could it be my access issue ? or something else is happening ? We are connecting to snowflake through ODBC driver while loading the data.

Thank you

答:
To load data to the internal stage, you need to define it. There is no default created stages.

There are 2 types of Stages (Internal, External) - Both are user-defined.

Internal Stages: (User, Table & Named) - User defined & Snowflake Managed

Details: https://docs.snowflake.com/en/user-guide/data-load-local-file-system-copy.html#loading-your-data

External Stages (Public Cloud-based). - User-defined & User-Managed

Details: https://docs.snowflake.com/en/sql-reference/sql/create-stage.html#create-stage

Title: Snowflake Stages - Can nt see


问:
Unable to access suspend Dao function from a CoroutineScope launch
i have a simple Dao interface of Room database in which I have suspend functions to insert and get data from the table.

in my DBHelper class I am trying to insert data using launch - CoroutineScope but does not seem to go within the launch and the functions within the launch are not executed.

any suggestions on what I might be doing wrong please

OfflineDataDao

```<code>@Dao
interface OfflineDataDao {

    @Query("SELECT * FROM offlineDatax")
    suspend fun getOfflineData(): List<OfflineDatax>

    @Insert
    suspend fun insertOfflineData(offlineData: OfflineDatax): Long
}
</code>```

Entity

```<code>@Entity
data class OfflineDatax (
    @PrimaryKey val uid: Int,
    @ColumnInfo(name = "requestJSON") val requestJSON: String?,
    @ColumnInfo(name = "requestCode") val requestCode: String?
)
</code>```

DBHelper
class where I am accessing the dao suspend methods

```<code>class DBHelper @Inject constructor(
    private val userDao: UserDao,
    private val offlineDataDao: OfflineDataDao
) : CoroutineScope {

    private var job: Job = Job()

    override val coroutineContext: CoroutineContext
        get() = Dispatchers.Main + job

    fun accessDBFunction() {

        var offlineDatax =  OfflineDatax(1, "rjson", "rCode")
        addOfflineData(offlineDatax)

        getOfflineData()
    }

    fun addOfflineData(offlineDatax: OfflineDatax): Long {
        var lng: Long = 0L
        launch {
            lng = offlineDataDao.insertOfflineData(offlineDatax) // IS NOT CALLED, DOES NOT GET INTO LAUNCH
        }
        return lng
    }

    fun getOfflineData (): List<OfflineDatax> {
        var offlineData = emptyList<OfflineDatax>()
        launch {
          offlineData = offlineDataDao.getOfflineData(); // IS NOT CALLED, DOES NOT GET INTO LAUNCH
        }
        Timber.d("offlinedata " + offlineData.toString())
        return offlineData
    }
}
</code>```

答:
Just make the function suspend, via suspend modifier and return from them directly they will suspend themselves into their own dispatcher defined in the Room library.

suspend fun addOfflineData(offlineDatax: OfflineDatax): Long =
    offlineDataDao.insertOfflineData(offlineDatax)

suspend fun getOfflineData (): List<OfflineDatax> =
     offlineDataDao.getOfflineData().also { Timber.d("offlinedata " + it.toString()) }
```

And call the function from any coroutine.

Body:
i have a simple Dao interface of Room database in which I have suspend functions to insert and get data from the table.

in my DBHelper class I am trying to insert data using launch - CoroutineScope but does not seem to go within the launch and the functions within the launch are not executed.

any suggestions on what I might be doing wrong please

OfflineDataDao

@Dao
interface OfflineDataDao {

    @Query("SELECT * FROM offlineDatax")
    suspend fun getOfflineData(): List<OfflineDatax>

    @Insert
    suspend fun insertOfflineData(offlineData: OfflineDatax): Long
}

Entity

@Entity
data class OfflineDatax (
    @PrimaryKey val uid: Int,
    @ColumnInfo(name = "requestJSON") val requestJSON: String?,
    @ColumnInfo(name = "requestCode") val requestCode: String?
)

DBHelper
class where I am accessing the dao suspend methods

class DBHelper @Inject constructor(
    private val userDao: UserDao,
    private val offlineDataDao: OfflineDataDao
) : CoroutineScope {

    private var job: Job = Job()

    override val coroutineContext: CoroutineContext
        get() = Dispatchers.Main + job

    fun accessDBFunction() {

        var offlineDatax =  OfflineDatax(1, "rjson", "rCode")
        addOfflineData(offlineDatax)

        getOfflineData()
    }

    fun addOfflineData(offlineDatax: OfflineDatax): Long {
        var lng: Long = 0L
        launch {
            lng = offlineDataDao.insertOfflineData(offlineDatax) // IS NOT CALLED, DOES NOT GET INTO LAUNCH
        }
        return lng
    }

    fun getOfflineData (): List<OfflineDatax> {
        var offlineData = emptyList<OfflineDatax>()
        launch {
          offlineData = offlineDataDao.getOfflineData(); // IS NOT CALLED, DOES NOT GET INTO LAUNCH
        }
        Timber.d("offlinedata " + offlineData.toString())
        return offlineData
    }
}

Body:
Just make the function suspend, via suspend modifier and return from them directly they will suspend themselves into their own dispatcher defined in the Room library.

suspend fun addOfflineData(offlineDatax: OfflineDatax): Long =
    offlineDataDao.insertOfflineData(offlineDatax)

suspend fun getOfflineData (): List<OfflineDatax> =
     offlineDataDao.getOfflineData().also { Timber.d("offlinedata " + it.toString()) }

And call the function from any coroutine.


问:
Increase all cells value that contains number and text
Hi I'm trying to build a macro that can search for cells with any value in and increase the numbers inside them by one.

all my cells have a text and numbers for e.g. ( Movie 1 , Movie 2 , Car )
each cell contains a name and a number .. the name might be one or two words or more.. the number is not always at the end and it's usually from 0 to 200 but not all of the cells have numbers.

Those cells are all over the sheet and I want the macro to search for anything that has value in it and separate the numbers from texts then increase the numbers by one.

after hours of trial and error I reached to this code :

```<code> Sub IncreaseCellValue()
    Dim value As Variant

    'Add 1 to the existing cell value

    If IsNumeric(Range("A1").value) Then
       Range("A1").value = Range("A1") + 1
    Else
       value = Split(Range("A1").value, " ")
       Range("A1").value = value(0) & " " & (CInt(value(1)) + 1)
    End If
End Sub
</code>```

The problem now is this code can only be applied to one specified cell.

答:
Since working directly with excel cells would slow down your executing time (when there are large number of cells to check), working with an array would be the key:</p>

```<code>Option Explicit
Sub IncreaseCellValue()

    Dim arr As Variant
    'This will hold your whole worksheet. Change the sheet name
    arr = ThisWorkbook.Sheets("SheetName").UsedRange.Value

    Dim i As Long, j As Long
    For i = 1 To UBound(arr) 'for every row
        For j = 1 To UBound(arr, 2) 'for every column
            Select Case True
                Case arr(i, j) = vbNullString
                Case arr(i, j) Like "*MyWord*" 'beware Like is Case Sensitive
                Case Else
                    arr(i, j) = AddOne(arr(i, j))
            End Select
        Next j
    Next i

    'Paste you array back to the worksheet
    ThisWorkbook.Sheets("SheetName").UsedRange.Value = arr

    'Note this will paste only values, so if you have formulas they will disappear

End Sub
Private Function AddOne(Value As Variant) As Variant

    Dim MySplit As Variant
    MySplit = Split(Value, " ")
    Dim i As Long
    For i = LBound(MySplit) To UBound(MySplit)
        If IsNumeric(MySplit(i)) Then
            AddOne = AddOne & " " & MySplit(i) + 1
        Else
            AddOne = AddOne & " " & MySplit(i)
        End If
    Next i
    AddOne = Trim(AddOne)

End Function
</code>```

Body:
Hi I'm trying to build a macro that can search for cells with any value in and increase the numbers inside them by one.

all my cells have a text and numbers for e.g. ( Movie 1 , Movie 2 , Car )
each cell contains a name and a number .. the name might be one or two words or more.. the number is not always at the end and it's usually from 0 to 200 but not all of the cells have numbers.

Those cells are all over the sheet and I want the macro to search for anything that has value in it and separate the numbers from texts then increase the numbers by one.

after hours of trial and error I reached to this code :

 Sub IncreaseCellValue()
    Dim value As Variant

    'Add 1 to the existing cell value

    If IsNumeric(Range("A1").value) Then
       Range("A1").value = Range("A1") + 1
    Else
       value = Split(Range("A1").value, " ")
       Range("A1").value = value(0) & " " & (CInt(value(1)) + 1)
    End If
End Sub

The problem now is this code can only be applied to one specified cell.

Body:
Since working directly with excel cells would slow down your executing time (when there are large number of cells to check), working with an array would be the key:

Option Explicit
Sub IncreaseCellValue()

    Dim arr As Variant
    'This will hold your whole worksheet. Change the sheet name
    arr = ThisWorkbook.Sheets("SheetName").UsedRange.Value

    Dim i As Long, j As Long
    For i = 1 To UBound(arr) 'for every row
        For j = 1 To UBound(arr, 2) 'for every column
            Select Case True
                Case arr(i, j) = vbNullString
                Case arr(i, j) Like "*MyWord*" 'beware Like is Case Sensitive
                Case Else
                    arr(i, j) = AddOne(arr(i, j))
            End Select
        Next j
    Next i

    'Paste you array back to the worksheet
    ThisWorkbook.Sheets("SheetName").UsedRange.Value = arr

    'Note this will paste only values, so if you have formulas they will disappear

End Sub
Private Function AddOne(Value As Variant) As Variant

    Dim MySplit As Variant
    MySplit = Split(Value, " ")
    Dim i As Long
    For i = LBound(MySplit) To UBound(MySplit)
        If IsNumeric(MySplit(i)) Then
            AddOne = AddOne & " " & MySplit(i) + 1
        Else
            AddOne = AddOne & " " & MySplit(i)
        End If
    Next i
    AddOne = Trim(AddOne)

End Function


问:
iOS TestFlight build update to AppStore build
I have some scenarios that am not really sure about regarding TestFlight and AppStore:

The user has version 1.0 installed on device from TestFlight and then he updates to the same version 1.0 from AppStore. What happens, the build is just overwritten?

The user has version 1.0 installed on device from TestFlight and then he updates to a newer version 1.1 from AppStore. What happens, the build is just overwritten? What is the difference between this case and the previous one?

The same as case 1. does the user receive any notification that the application is available on AppStore?

Any other observations are appreciated.
Thank you very much! :)

答:
To answer 1 & 2 :-

Yeah the app will be overwritten. It will be like a regular app update from the app store. All the data that is saved in the test flight app also will be preserved when you install the app from app store.

Question 3 - No there will not be any notification in the testflight app if the application is available in the app store.


问:
Error: write EPIPE with wkhtmltopdf + nodejs on Heroku
I'm using wkhtmltopdf as service to download pdf in a web app, in local server work perfectly, but when I send to production on heroku show this error:

```<code>Error: write EPIPE
at WriteWrap.onWriteComplete [as oncomplete] (internal/stream_base_commons.js:66:16)
Emitted 'error' event at:
at errorOrDestroy (internal/streams/destroy.js:98:12)
at onwriteError (_stream_writable.js:436:5)
at onwrite (_stream_writable.js:461:5)
at _destroy (internal/streams/destroy.js:40:7)
at Socket._destroy (net.js:618:3)
at Socket.destroy (internal/streams/destroy.js:32:8)
at WriteWrap.onWriteComplete [as oncomplete] (internal/stream_base_commons.js:67:12)
</code>```

The code that I'm using is this:

```<code>   const htmlToPdf = async ({ body: { html } }, res) => {
        const decodedHTml = decodeURI(html);
        fs.readFile(path.join(__dirname, "", "style.css"), (err, data)=>    {
            if (error) throw error;
            const style = `<style>${data}</style>`
            wkhtmltopdf(style + decodedHTml, { pageSize: "A4" }).pipe(res);
        });
    };
</code>```

答:
The error is caused when you have not installed the command line version of wkhtmltopdf since this is just a wrapper.

Check available builds:

https://wkhtmltopdf.org/downloads.html

Body:
I'm using wkhtmltopdf as service to download pdf in a web app, in local server work perfectly, but when I send to production on heroku show this error:

Error: write EPIPE
at WriteWrap.onWriteComplete [as oncomplete] (internal/stream_base_commons.js:66:16)
Emitted 'error' event at:
at errorOrDestroy (internal/streams/destroy.js:98:12)
at onwriteError (_stream_writable.js:436:5)
at onwrite (_stream_writable.js:461:5)
at _destroy (internal/streams/destroy.js:40:7)
at Socket._destroy (net.js:618:3)
at Socket.destroy (internal/streams/destroy.js:32:8)
at WriteWrap.onWriteComplete [as oncomplete] (internal/stream_base_commons.js:67:12)

The code that I'm using is this:

   const htmlToPdf = async ({ body: { html } }, res) => {
        const decodedHTml = decodeURI(html);
        fs.readFile(path.join(__dirname, "", "style.css"), (err, data)=>    {
            if (error) throw error;
            const style = `<style>${data}</style>`
            wkhtmltopdf(style + decodedHTml, { pageSize: "A4" }).pipe(res);
        });
    };


问:
CMake: Fail to install symlink on ssh-mounted filesystem
I am cross-compiling a project on my desktop, and installing it on a device which is mounted via ssh, using sshfs, like so:

```<code>    sudo sshfs -o allow_other -o follow_symlinks user@192.168.12.100:/ /mnt/remote
</code>```

The build is successful, but when I try to "sudo make install", I receive the following message:

```<code>    -- Installing: /mnt/remote/usr/lib/libprop.so.5.1.5
    -- Installing: /mnt/remote/usr/lib/libprop.so.5
    CMake Error: failed to create symbolic link '/mnt/remote/usr/lib/libprop.so.5': i/o error
    CMake Error at cmake_install.cmake:176 (file):file INSTALL cannot duplicate symlink
      "/home/ubuntu/libprop/build/lib/libprop.so.5" at
      "/mnt/remote/usr/lib/libprop.so.5".
</code>```

The library and the symlink are copied and created. That is, it seems that the installation actually succeeds, but CMake thinks otherwise.

The filesystem is not ro, as can be seen in mount output:

```<code>    user@192.168.12.100:/ on /mnt/remote type fuse.sshfs (rw,nosuid,nodev,relatime,user_id=0,group_id=0,allow_other)
</code>```

And I can see the entry under /mnt/ (I chown'd and chmod'd it for user access, thinking it might solve the problem):

```<code>    drwxrwxr-x 1 ubuntu ubuntu 4096 Mar 11 13:43 remote
</code>```

and I can access it event without root permissions, copying and deleting files without a problem.

This process has been working for me. I have no idea what was changed that it stopped. Could be something in my environment or maybe in the destination platform.

I would be grateful for any assistance.

答: OK, I have found the problem... I shouldn't be using -o follow_symlinks. I guess this can cause other problems (I used it for a reason), but for the purpose of compiling and installing, it works.

Body:
I am cross-compiling a project on my desktop, and installing it on a device which is mounted via ssh, using sshfs, like so:

    sudo sshfs -o allow_other -o follow_symlinks user@192.168.12.100:/ /mnt/remote

The build is successful, but when I try to "sudo make install", I receive the following message:

    -- Installing: /mnt/remote/usr/lib/libprop.so.5.1.5
    -- Installing: /mnt/remote/usr/lib/libprop.so.5
    CMake Error: failed to create symbolic link '/mnt/remote/usr/lib/libprop.so.5': i/o error
    CMake Error at cmake_install.cmake:176 (file):file INSTALL cannot duplicate symlink
      "/home/ubuntu/libprop/build/lib/libprop.so.5" at
      "/mnt/remote/usr/lib/libprop.so.5".

The library and the symlink are copied and created. That is, it seems that the installation actually succeeds, but CMake thinks otherwise.

The filesystem is not ro, as can be seen in mount output:

    user@192.168.12.100:/ on /mnt/remote type fuse.sshfs (rw,nosuid,nodev,relatime,user_id=0,group_id=0,allow_other)

And I can see the entry under /mnt/ (I chown'd and chmod'd it for user access, thinking it might solve the problem):

    drwxrwxr-x 1 ubuntu ubuntu 4096 Mar 11 13:43 remote

and I can access it event without root permissions, copying and deleting files without a problem.

This process has been working for me. I have no idea what was changed that it stopped. Could be something in my environment or maybe in the destination platform.

I would be grateful for any assistance.


问:
Increase quotas at google cloud platform
Recently I am working with google cloud platform in order to training a machine learning model
Unfortunatly I was trying to increase quotas in order to get benefit of GPUs but the request has been rejected on behave That I need to get more billing history
Therefore my question is there any steps I could do to accelerate the process.
In other hand If I would work with other platform like amazon or azure would the process of using GPUs going to be easier.
Thanks in advance.</p>

答:
It happens to some fresh projects and unfortunately Stack Overflow community can do nothing with such issues.

Have a look again at the email from Google Cloud Support, I think it looks similar to this:

Unfortunately, we are unable to grant you additional quota at this
  time. If this is a new project please wait 48h until you resubmit the
  request or until your Billing account has additional history.

Your Sales Rep is a good Escalation Path for these requests, and we
  highly recommend you to reach out to them.

If you have any further questions, please reply to this thread or feel
  free to reach out to us at gc-team@google.com.

To solve this issue you can try steps below:

Try to work for a while with current quotas, if it possible for your use case, to get some history on your account and after that request an increase in quota.

Try to split desired increase in quota into some steps that could be approved like 1 -> 2 -> 4 -> 8.

Try to reach Google Sales Team.

Try to reply again to gc-team@google.com but provide some arguments to clarify your request.

In addition, please have a look at the few similar cases here and here.


问:
Dont allow null or undefined with useState and TypeScript?
I'm adding TypeScript types to React's useState hook.

```<code>const [checked, setChecked] = React.useState<"checked" | un-checked">(null);
</code>```

Is it possible to only allow the checked and un-checked values and not null or undefined so that the code above would error?

答:
You need to enable "strictNullChecks": true in your tsconfig.json

Argument of type 'null' is not assignable to parameter of type
  '"checked" | "un-checked" | (() => "checked" | "un-checked")'.

https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-0.html

Body:
I'm adding TypeScript types to React's useState hook.

const [checked, setChecked] = React.useState<"checked" | un-checked">(null);

Is it possible to only allow the checked and un-checked values and not null or undefined so that the code above would error?


问:
How to use json attribute in a toggle with swiftUI list?

I developed a SwiftUI app for iPhone/iPad/Mac. The app lists my films (first view) with information such as a note of each film and if the film was seen.

I have a JSON file with:

id : Int, unique identifier

nom : String, title of film

idL : String, first charachter of title

note : Int, note of each film (between 0 and 10)

isShow : Bool, indicate if the film was seen or not

I created a toggle to only display films where isShow=false, but I was unable to link this toggle with my JSON property...

Here is my project : https://github.com/thomjlg/Films-APP

JSON file : https://gist.githubusercontent.com/thomjlg/0782e9e8e27c346af3600bff9923f294/raw/9705fb0c6b40eae59578755b86e331bea257972b/films2.json

答:
I believe when you're saving the movies you don't reload the userData.

```<code>Toggle("Film", isOn: self.$movie.isShow)
    .onTapGesture {
        self.userData.fetcher.save(movies: self.userData.movies)
        self.movie.isShow = !self.movie.isShow
        print(self.movie.isShow)
    }
</code>```

fetcher.save(movies:) just saves your movies but UserData is created only once and movies are loaded only in init:

```<code>window.rootViewController = UIHostingController(rootView: contentView
    .environmentObject(UserData())
)
</code>```

```<code>init() {
    fetcher.load { (movies) in
        if let movies = movies {
            self.movies = movies
        }
    }
}
</code>```

Body:
I believe when you're saving the movies you don't reload the userData.

Toggle("Film", isOn: self.$movie.isShow)
    .onTapGesture {
        self.userData.fetcher.save(movies: self.userData.movies)
        self.movie.isShow = !self.movie.isShow
        print(self.movie.isShow)
    }

fetcher.save(movies:) just saves your movies but UserData is created only once and movies are loaded only in init:

window.rootViewController = UIHostingController(rootView: contentView
    .environmentObject(UserData())
)

init() {
    fetcher.load { (movies) in
        if let movies = movies {
            self.movies = movies
        }
    }
}


问:
Why I am getting this error message when I run react js project first time in my system?

When I run npm start, I get this error message:

Error from chokidar (C:): Error: EBUSY: resource busy or locked, lstat 'C:\hiberfil.sys'
Error from chokidar (C:): Error: EBUSY: resource busy or locked, lstat 'C:\pagefile.sys'
Error from chokidar (C:): Error: EBUSY: resource busy or locked, lstat 'C:\swapfile.sys'
Error from chokidar (C:\node_modules): Error: EBUSY: resource busy or locked, lstat 'C:\hiberfil.sys'
Error from chokidar (C:\node_modules): Error: EBUSY: resource busy or locked, lstat 'C:\pagefile.sys'
Error from chokidar (C:\node_modules): Error: EBUSY: resource busy or locked, lstat 'C:\swapfile.sys'
Error from chokidar (C:\node_modules): Error: EBUSY: resource busy or locked, lstat 'C:\hiberfil.sys'
Error from chokidar (C:\node_modules): Error: EBUSY: resource busy or locked, lstat 'C:\pagefile.sys'
Error from chokidar (C:\node_modules): Error: EBUSY: resource busy or locked, lstat 'C:\swapfile.sys'

答: Deleted all my node modules and reinstalled, worked for me</p>


问:
How to find longitude and latitude for multiple addresses
I have a lots of adresses and want to find easier way to find their longitude and latitude?

Have anybody here some idea?

EDIT:
I do not want to find it in the app. I just need to convert them.

Thank you

答: Go to Google Maps and search for the address. When you find it, look for the "copy link" box and grab the URL from there. Paste it into a text editor and look for the part that says &ll=. This is the latitude-longitude pair.</p>


问:
How to run vuejs files on IIS
So am using a vueJS Example as a demo for learning purposes which uses a requirejs-vue as a component loader.
when i run the server on Live-Server extension of VS-code (a simple http server), it run correctly with no problems.
However, when i run this example on IIS server (version 8.5) on windows 8.1, it through 404 Error app.vue does not exist.

```<code>Failed to load resource: the server responded with a status of 404 (Not Found)
</code>```

and in the Network devtool, i can see that every module is loaded correctly, except for *.vue files,

VueJS Example :
https://plnkr.co/edit/Y2cEa3?preview

Web Config for IIS that am using:
https://router.vuejs.org/guide/essentials/history-mode.html#example-server-configurations

```<code><?xml version="1.0" encoding="UTF-8"?>
<configuration>
  <system.webServer>
    <rewrite>
      <rules>
        <rule name="Handle History Mode and custom 404/500" stopProcessing="true">
          <match url="(.*)" />
          <conditions logicalGrouping="MatchAll">
            <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
            <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
          </conditions>
          <action type="Rewrite" url="/" />
        </rule>
      </rules>
    </rewrite>
  </system.webServer>
</configuration>
</code>```

PS: i have also run an other example that uses http-vue-loader instead of requirejs-vue and IIS still throwing the same error.

答:
We need to set mimeType for the “.vue” extension file to use httpvueloader/requiresjs_vue.

In addition, we could manually add it to a Web.Config file, which can be recognized by IIS.

```<code><?xml version="1.0" encoding="UTF-8"?>
<configuration>
 <system.webServer>
    <staticContent>
      <mimeMap fileExtension=".vue" mimeType="application/javascript"/>
    </staticContent>
  </system.webServer>
</configuration>
</code>```

Feel free to let me know if the problem still exists.

Title: How to run vuejs files on IIS

Body:
So am using a vueJS Example as a demo for learning purposes which uses a requirejs-vue as a component loader.
when i run the server on Live-Server extension of VS-code (a simple http server), it run correctly with no problems.
However, when i run this example on IIS server (version 8.5) on windows 8.1, it through 404 Error app.vue does not exist.

Failed to load resource: the server responded with a status of 404 (Not Found)

and in the Network devtool, i can see that every module is loaded correctly, except for *.vue files,

VueJS Example :
https://plnkr.co/edit/Y2cEa3?preview

Web Config for IIS that am using:
https://router.vuejs.org/guide/essentials/history-mode.html#example-server-configurations

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
  <system.webServer>
    <rewrite>
      <rules>
        <rule name="Handle History Mode and custom 404/500" stopProcessing="true">
          <match url="(.*)" />
          <conditions logicalGrouping="MatchAll">
            <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
            <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
          </conditions>
          <action type="Rewrite" url="/" />
        </rule>
      </rules>
    </rewrite>
  </system.webServer>
</configuration>

PS: i have also run an other example that uses http-vue-loader instead of requirejs-vue and IIS still throwing the same error.

Body:
We need to set mimeType for the “.vue” extension file to use httpvueloader/requiresjs_vue.

In addition, we could manually add it to a Web.Config file, which can be recognized by IIS.

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
 <system.webServer>
    <staticContent>
      <mimeMap fileExtension=".vue" mimeType="application/javascript"/>
    </staticContent>
  </system.webServer>
</configuration>

Feel free to let me know if the problem still exists.


问:
Generate Ansible fact once (per host)
I would like to generate a password and some other values when they do not exist yet.

Something like this:

```<code>- name: Retrieve or generate my_password
  generated_fact:
    shell: some shell command
    name: my_password
</code>```

I have a working approach but am really unhappy with it since it is very verbose and error prone:

```<code>- name: Generate my_password
  shell: some shell command
  register: generate_password_task
  when: ansible_local.convoluted.bs.my_password is not defined

- name: Store my_password as local fact
  ini_file:
    path: "/etc/ansible/facts.d/convoluted.fact"
    section: bs
    option: my_password
    value: "{{ generate_password_task.stdout }}"
  when: generate_password_task.changed

- name: Reload Ansible local facts
  setup: filter=ansible_local
  when: generate_password_task.changed
</code>```

Is there a high level abstraction for this task along the lines of the first code snippet? Or some other approach more sane than what I currently have?

答:
The basic approach is the right one. There are few imperfections I see. One of them is 'dependence chain', when different tasks are depend on different conditions. It's hard to debug.

So, improvement one is to make a single condition:

```<code>- block:
  when: ansible_local.convoluted.bs.my_password is not defined
  - name: Generate my_password
    shell: some shell command
    register: generate_password_task

  - name: Store my_password as local fact
    ini_file:
      path: "/etc/ansible/facts.d/convoluted.fact"
      section: bs
      option: my_password
      value: "{{ generate_password_task.stdout }}"

  - name: Reload Ansible local facts
    setup: filter=ansible_local
</code>```

The second trick is to use meta: end_host, it allows to terminate play for the specific host without errors and additional skips.

```<code>- hosts: ...
  tasks:
   - meta: end_play
     when: ansible_local.convoluted.bs.my_password is defined

   - name: Generate my_password
     shell: some shell command
     register: generate_password_task

   - name: Store my_password as local fact
     ini_file:
       path: "/etc/ansible/facts.d/convoluted.fact"
       section: bs
       option: my_password
       value: "{{ generate_password_task.stdout }}"

   - name: Reload Ansible local facts
     setup: filter=ansible_local
</code>```

But you need to keep it as a separate play to use it with 'end_host'.

Title: Generate Ansible fact once (per host)

Body:
I would like to generate a password and some other values when they do not exist yet.

Something like this:

- name: Retrieve or generate my_password
  generated_fact:
    shell: some shell command
    name: my_password

I have a working approach but am really unhappy with it since it is very verbose and error prone:

- name: Generate my_password
  shell: some shell command
  register: generate_password_task
  when: ansible_local.convoluted.bs.my_password is not defined

- name: Store my_password as local fact
  ini_file:
    path: "/etc/ansible/facts.d/convoluted.fact"
    section: bs
    option: my_password
    value: "{{ generate_password_task.stdout }}"
  when: generate_password_task.changed

- name: Reload Ansible local facts
  setup: filter=ansible_local
  when: generate_password_task.changed

Is there a high level abstraction for this task along the lines of the first code snippet? Or some other approach more sane than what I currently have?

Body:
The basic approach is the right one. There are few imperfections I see. One of them is 'dependence chain', when different tasks are depend on different conditions. It's hard to debug.

So, improvement one is to make a single condition:

- block:
  when: ansible_local.convoluted.bs.my_password is not defined
  - name: Generate my_password
    shell: some shell command
    register: generate_password_task

  - name: Store my_password as local fact
    ini_file:
      path: "/etc/ansible/facts.d/convoluted.fact"
      section: bs
      option: my_password
      value: "{{ generate_password_task.stdout }}"

  - name: Reload Ansible local facts
    setup: filter=ansible_local

The second trick is to use meta: end_host, it allows to terminate play for the specific host without errors and additional skips.

- hosts: ...
  tasks:
   - meta: end_play
     when: ansible_local.convoluted.bs.my_password is defined

   - name: Generate my_password
     shell: some shell command
     register: generate_password_task

   - name: Store my_password as local fact
     ini_file:
       path: "/etc/ansible/facts.d/convoluted.fact"
       section: bs
       option: my_password
       value: "{{ generate_password_task.stdout }}"

   - name: Reload Ansible local facts
     setup: filter=ansible_local

But you need to keep it as a separate play to use it with 'end_host'.


问:
iOS swift recorded video deleted but app data still big
I developed recording video for some app but issue is when I delete one or all video app data stay same. And it's always increased when new video is recorded. Because app create video 720p and 1080p app data very quick  become few GB. That's not problem when videos are in photos but when user delete video app data doesn't go down. So, app will make memory issue. How to resolve this? I write in swift 5.0</p>

答: I remove all video with PHPhotoLibrary because I am also adding video with this api. So, I now also delete with FileManager and now it works :)</p>


问:
ADO.NET Entity Framework tutorials
Does anyone know of any good tutorials on ADO.NET Entity Framework?

There are a few useful links here at Stack OverFlow, and I've found one tutorial at Jason's DotNet Architecture Blog, but can anyone recommend any other good tutorials?
Any tutorials available from Microsoft, either online or as part of any conference/course material?

答:
Try this link you may get some best ideas...

http://msdn.microsoft.com/en-us/library/aa697427(VS.80).aspx

http://en.wikipedia.org/wiki/ADO.NET_Entity_Framework

This one is nice try this....

http://davidhayden.com/blog/dave/archive/2007/03/19/ADONETEntityFrameworkObjectServicesTutorial.aspx

http://www.codeguru.com/csharp/.net/net_general/netframeworkclasses/article.php/c15489/..

OwnerDisplayName: Yngvar

ContentLicense: CC BY-SA 2.5

Title: ADO.NET Entity Framework tutorials

LastEditorDisplayName: aku


问:
Converting Image to Bytes and back
I know there is a lot of help already about this subject, but using this help I ran into a problem: I have an image list with icons that I display in a tree view on a windows form and that works.

Now I want to take these icons, put them in a table, clear the image list and then load the image list from the table.  This is to test if I can use a table to maintain the icons.

The problem is that the icons display a black background using this method. I use BytesFromImage to write to an Image column in the table and ImageFromStream and StreamFromBytes to read the data back to an image.

What am I missing?

```<code>public static byte[] BytesFromImage(Image TheImage)
{
    MemoryStream ms = new MemoryStream();
    TheImage.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);
    return ms.ToArray();
}

public static Stream StreamFromBytes(byte[] DataBytes)
{
    MemoryStream stream = new MemoryStream();
    stream.Write(DataBytes, 0, DataBytes.Length);
    stream.Seek(0, SeekOrigin.Begin);
    return stream;
}

public static Image ImageFromStream(Stream DataStream)
{
    return Bitmap.FromStream(DataStream);
}
</code>```

答:
Actually there's nothing wrong with your code. The problem is format specification. I have run into this problem when i was trying to convert an image which I created from Photoshop with a format of PNG to JPEG/JPG. According to popular documentation like Microsoft, PNG images retain high detail of information of an image, JPG doesn't. JPEG is not good as a compression option when you want to compress images that have high transitional borders. Especially when porting from PNG to JPEG. You'll always notice that. I think the problem is that you are using a raw bitmap. Try parsing it to Image instead of Bitmap and see if this works

```<code>Image image = System.Drawing.Image.FromStream(stream);
</code>```

Title: Converting Image to Bytes and back

Body:
I know there is a lot of help already about this subject, but using this help I ran into a problem: I have an image list with icons that I display in a tree view on a windows form and that works.

Now I want to take these icons, put them in a table, clear the image list and then load the image list from the table.  This is to test if I can use a table to maintain the icons.

The problem is that the icons display a black background using this method. I use BytesFromImage to write to an Image column in the table and ImageFromStream and StreamFromBytes to read the data back to an image.

What am I missing?

public static byte[] BytesFromImage(Image TheImage)
{
    MemoryStream ms = new MemoryStream();
    TheImage.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);
    return ms.ToArray();
}

public static Stream StreamFromBytes(byte[] DataBytes)
{
    MemoryStream stream = new MemoryStream();
    stream.Write(DataBytes, 0, DataBytes.Length);
    stream.Seek(0, SeekOrigin.Begin);
    return stream;
}

public static Image ImageFromStream(Stream DataStream)
{
    return Bitmap.FromStream(DataStream);
}

Body:
Actually there's nothing wrong with your code. The problem is format specification. I have run into this problem when i was trying to convert an image which I created from Photoshop with a format of PNG to JPEG/JPG. According to popular documentation like Microsoft, PNG images retain high detail of information of an image, JPG doesn't. JPEG is not good as a compression option when you want to compress images that have high transitional borders. Especially when porting from PNG to JPEG. You'll always notice that. I think the problem is that you are using a raw bitmap. Try parsing it to Image instead of Bitmap and see if this works

Image image = System.Drawing.Image.FromStream(stream);


问:
How to get the same behavior in an object when the value is copied to another variable
In this console:

When B is set to A but A was destroyed afterwards, B.b() throws an error because A is truly undefined.

How can one avoid this?

PS: I am aware that I can simply return this (or change the function in some way) but that doesn't fulfill my purposes.

EDIT: How do I 'localise' and somehow tell javascript that by A, I mean B even if A is undefined, WITHOUT ALTERING THE FUNCTION ITSELF?

答:
To the new viewers, if you want to do this without altering the function:

var A = (function() {
  var A = {a: 90, b: function() { return A.a }}; // same object as in the Q
  return A;
})()

console.log(A.b()) // 90

var B = A;
A = undefined;

console.log(B.b()) // Also 90

B.a = 89;
console.log(B.b()) // 89```


问:
How to space-between two divs vertically using flexbox?
How can I space-between two divs vertically using flexbox? Everything works when using it for the horizontal patterns, but not for the vertical ones.

#container {
  height: 50vh;
  width: 15vw;
  background-color: lightblue;
  justify-content: space-between;
}

.item {}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="container">
  <div class="item">
    <p>Align Top</p>
  </div>
  <div class="item">
    <p>Align Bottom</p>
  </div>
</div></code>```

答:
Set the display of #container to flex, and set flex-direction: column;:

#container {
  display: flex;
  flex-direction: column;
  height: 50vh;
  width: 15vw;
  background-color: lightblue;
  justify-content: space-between;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="container">
  <div class="item">
    <p>Align Top</p>
  </div>
  <div class="item">
    <p>Align Bottom</p>
  </div>
</div></code>```

Body:
How can I space-between two divs vertically using flexbox? Everything works when using it for the horizontal patterns, but not for the vertical ones.

#container {
  height: 50vh;
  width: 15vw;
  background-color: lightblue;
  justify-content: space-between;
}

.item {}

Align Top

Align Bottom

Body:
Set the display of #container to flex, and set flex-direction: column;:

#container {
  display: flex;
  flex-direction: column;
  height: 50vh;
  width: 15vw;
  background-color: lightblue;
  justify-content: space-between;
}

<div id="container">
  <div class="item">
    <p>Align Top</p>
  </div>
  <div class="item">
    <p>Align Bottom</p>
  </div>
</div>


问:
What does the -DQT_WEBKIT flag mean in g ++?
The same project is assembled on different versions of the OS with different flags.
What is this flag?

First OS:

-g++ -c -pipe -g -D_REENTRANT -Wall -W -Wno-unknown-pragmas -DQT_WEBKIT -D_TESTR ...

Other OS:

+g++ -c -pipe -g -D_REENTRANT -Wall -W -Wno-unknown-pragmas -D_TESTR

答:
The -D option is a preprocessor option and is documented in section 3.13 Preprocessor Options of the GCC Manual. (You can also always just run gcc --help or g++ --help to get help for the options.)

The -D<name>[=<value>] option #defines the macro <name> to have the value <value> (or 1 if the value <value> is not provided).

So, in your case, it defines the three macros _REENTRANT, QT_WEBKIT, and D_TESTR to the value 1, in other words, it is exactly equivalent to having

#define _REENTRANT 1
#define QT_WEBKIT 1
#define D_TESTR 1
```

prepended to the file being compiled.

Body:
The -D option is a preprocessor option and is documented in section 3.13 Preprocessor Options of the GCC Manual. (You can also always just run gcc --help or g++ --help to get help for the options.)

The -D<name>[=<value>] option #defines the macro <name> to have the value <value> (or 1 if the value <value> is not provided).

So, in your case, it defines the three macros _REENTRANT, QT_WEBKIT, and D_TESTR to the value 1, in other words, it is exactly equivalent to having

#define _REENTRANT 1
#define QT_WEBKIT 1
#define D_TESTR 1

prepended to the file being compiled.


问:
Angular 2 - How to have an `svg` in app.component and a `circle` as a child component?
So I want to develop a Pac-man game using Angular, I want to use an SVG for this, I want to create the board.component which will have an embedded pacman.component.

board.component will have an <svg></svg> and pacman.component will have a <circle></circle> but angular throws this error in my pacman.component:

[Angular] 'circle' is not a known element :

If 'circle' is an Angular component, then verify that it is part of this module.

To allow any element add 'NO_ERRORS_SCHEMA' to the '@NgModule.schemas' of this component.

After fixing those errors I end up with this SVG:

```<code>  <svg _ngcontent-c0="" width="100" height="100">
    <app-pacman _ngcontent-c0="" _nghost-c1="">
      <circle _ngcontent-c1="" fill="yellow" r="25" cx="10" cy="10"></circle>
    </app-pacman>
  </svg>
</code>```

Now the only problem now is that angular wraps the pacman.component with <app-pacman></app-pacman> and that makes the circle not work.

Just wondering what would be the Angular way of doing this? I don't want to have my whole svg code (svg, circles, paths, etc...) in a single component.

Thanks.

Edit:

board.component.html:

```<code><svg [attr.width]="width" [attr.height]="height">
  <app-pacman></app-pacman>
</svg>
</code>```

pacman.component.html:

```<code><circle [attr.cx]="cx" [attr.cy]="cy" r="25" fill="yellow"></circle>
</code>```

答:
I think the compiler error [Angular] 'circle' is not a known element is the point. Just add svg prefix to circle.

```<code><div [ngSwitch]="prop?.type">
    <app-svg-circle *ngSwitchCase="'circle'" [props]="prop"></app-svg-circle>
    <svg:path *ngSwitchCase="'path'" prop="prop"></svg:path>
</div>

@Component({
    selector: 'app-svg-base',
    template: `
            <svg:circle ${SvgBaseComponent.Bindings}></svg:circle>
    `
    })
    export class SvgBaseComponent {
      @Input()
      public props;
      public static readonly Bindings = '[attr.x]="props?.x" [attr.y]="props?.y" [attr.stroke]="props?.stroke"'

    }

@Component({
    selector: 'app-svg-circle',
    template: `
            <svg:circle ${SvgBaseComponent.Bindings}></svg:circle>
    `
    })
    export class SvgCircleComponent extends SvgBaseComponent { }
</code>```

Body:
So I want to develop a Pac-man game using Angular, I want to use an SVG for this, I want to create the board.component which will have an embedded pacman.component.

board.component will have an <svg></svg> and pacman.component will have a <circle></circle> but angular throws this error in my pacman.component:

[Angular] 'circle' is not a known element :

If 'circle' is an Angular component, then verify that it is part of this module.

To allow any element add 'NO_ERRORS_SCHEMA' to the '@NgModule.schemas' of this component.

After fixing those errors I end up with this SVG:

  <svg _ngcontent-c0="" width="100" height="100">
    <app-pacman _ngcontent-c0="" _nghost-c1="">
      <circle _ngcontent-c1="" fill="yellow" r="25" cx="10" cy="10"></circle>
    </app-pacman>
  </svg>

Now the only problem now is that angular wraps the pacman.component with <app-pacman></app-pacman> and that makes the circle not work.

Just wondering what would be the Angular way of doing this? I don't want to have my whole svg code (svg, circles, paths, etc...) in a single component.

Thanks.

Edit:

board.component.html:

<svg [attr.width]="width" [attr.height]="height">
  <app-pacman></app-pacman>
</svg>

pacman.component.html:

<circle [attr.cx]="cx" [attr.cy]="cy" r="25" fill="yellow"></circle>

Body:
I think the compiler error [Angular] 'circle' is not a known element is the point. Just add svg prefix to circle.

<div [ngSwitch]="prop?.type">
    <app-svg-circle *ngSwitchCase="'circle'" [props]="prop"></app-svg-circle>
    <svg:path *ngSwitchCase="'path'" prop="prop"></svg:path>
</div>

@Component({
    selector: 'app-svg-base',
    template: `
            <svg:circle ${SvgBaseComponent.Bindings}></svg:circle>
    `
    })
    export class SvgBaseComponent {
      @Input()
      public props;
      public static readonly Bindings = '[attr.x]="props?.x" [attr.y]="props?.y" [attr.stroke]="props?.stroke"'

    }

@Component({
    selector: 'app-svg-circle',
    template: `
            <svg:circle ${SvgBaseComponent.Bindings}></svg:circle>
    `
    })
    export class SvgCircleComponent extends SvgBaseComponent { }


问:
Prevent Browser Adding Light-Blue Background to Input Elements on Second Visit
When a form is filled out for a 2nd time and the browser recognises the details it adds a light-blue background to the form input elements on a site I'm building (which currently have the background set as transparent to show the dark blue background of the parent section). Image attached.

Is there a way to prevent this from happening?

It doesn't do it the first time of filling the form in, only if you input the details a second time after submission.

In the attached image I've left the fourth (bottom-right) field blank so you can see how it should look.

Thanks

答:
1. You can just disable autocomplete in form at all or in some of input fields you want:

```<code><form autocomplete="off">...</form>
</code>```

or

```<code><input type="text" autocomplete="off" />
</code>```

2. Try to overwrite autofill by own CSS rules

```<code>@-webkit-keyframes autofill {
  to {
    color: inherit;
    background: transparent;
  }
}

input:-webkit-autofill,
textarea:-webkit-autofill,
select:-webkit-autofill
{
  -webkit-animation-name: autofill;
  -webkit-animation-fill-mode: both;
}
</code>```

Body:
1. You can just disable autocomplete in form at all or in some of input fields you want:

<form autocomplete="off">...</form>

or

<input type="text" autocomplete="off" />

2. Try to overwrite autofill by own CSS rules

@-webkit-keyframes autofill {
  to {
    color: inherit;
    background: transparent;
  }
}

input:-webkit-autofill,
textarea:-webkit-autofill,
select:-webkit-autofill
{
  -webkit-animation-name: autofill;
  -webkit-animation-fill-mode: both;
}


问:
SQL database view all foreign keys
I am trying to view all foreign keys of my database and I have the following code to do that:

```<code>SELECT
  tc.TABLE_NAME,
  sc.COLUMN_NAME,
  CONSTRAINT_NAME,
  CONSTRAINT_TYPE
FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS as tc
inner join INFORMATION_SCHEMA.COLUMNS as sc
on sc.TABLE_NAME = tc.TABLE_NAME
order by tc.TABLE_NAME
</code>```

But it seems to give more results than it should be. It gives around 30.000 result and it should be no more than 2000. What I am doing wrong.
PS: I need this to return the table name, column name, column id and constraint type for further implementation in Laravel application.

答:
Try to add "where CONSTRAINT_TYPE = 'FOREIGN KEY'":</p>

```<code>SELECT
tc.TABLE_NAME,
sc.COLUMN_NAME,
CONSTRAINT_NAME,
CONSTRAINT_TYPE
FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS as tc
inner join INFORMATION_SCHEMA.COLUMNS as sc
on sc.TABLE_NAME = tc.TABLE_NAME
where CONSTRAINT_TYPE = 'FOREIGN KEY'
order by tc.TABLE_NAME;
</code>```

Title: SQL database view all foreign keys

Body:
I am trying to view all foreign keys of my database and I have the following code to do that:

SELECT
  tc.TABLE_NAME,
  sc.COLUMN_NAME,
  CONSTRAINT_NAME,
  CONSTRAINT_TYPE
FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS as tc
inner join INFORMATION_SCHEMA.COLUMNS as sc
on sc.TABLE_NAME = tc.TABLE_NAME
order by tc.TABLE_NAME

But it seems to give more results than it should be. It gives around 30.000 result and it should be no more than 2000. What I am doing wrong.
PS: I need this to return the table name, column name, column id and constraint type for further implementation in Laravel application.

Body:
Try to add "where CONSTRAINT_TYPE = 'FOREIGN KEY'":

SELECT
tc.TABLE_NAME,
sc.COLUMN_NAME,
CONSTRAINT_NAME,
CONSTRAINT_TYPE
FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS as tc
inner join INFORMATION_SCHEMA.COLUMNS as sc
on sc.TABLE_NAME = tc.TABLE_NAME
where CONSTRAINT_TYPE = 'FOREIGN KEY'
order by tc.TABLE_NAME;


问:
ERROR:'keytool' is not recognized as an internal or external command, operable program or batch file
When I use the command:

```<code>C:\>keytool -list -alias androiddebugkey
            -keystore .android\debug.keystore
            -storepass android -keypass android
</code>```

I get this error:

'keytool' is not recognized as an internal or external command, operable program or batch file.

I'm not able to get the certificate fingerprint(MD5) on my computer.

I have ensured that the keystore file is present in the appropriate location.

Any help?

答:
So if you have the following structure now:

```<code> C:\Program Files\Java\jre6\bin\
                                keytool.exe
                                debug.keystore
</code>```

then execute:

```<code>C:\Program Files\Java\jre6\bin>keytool -list -alias androiddebugkey -keystore debug.keystore -storepass android -keypass android
</code>```

Body:
When I use the command:

C:\>keytool -list -alias androiddebugkey
            -keystore .android\debug.keystore
            -storepass android -keypass android

I get this error:

'keytool' is not recognized as an internal or external command, operable program or batch file.

I'm not able to get the certificate fingerprint(MD5) on my computer.

I have ensured that the keystore file is present in the appropriate location.

Any help?

Body:
So if you have the following structure now:

 C:\Program Files\Java\jre6\bin\
                                keytool.exe
                                debug.keystore

then execute:

C:\Program Files\Java\jre6\bin>keytool -list -alias androiddebugkey -keystore debug.keystore -storepass android -keypass android