text:
Q: Passing data between pages wp7 I have a little question.
I have a data template like that :
    <phone:PhoneApplicationPage.Resources>
    <DataTemplate x:Key="DangersItemTemplate">
        <Grid Height="102" Width="447" Tap="Grid_Tap">
            <Image Name="image" Source="{Binding Image}" HorizontalAlignment="Left" Width="90" />
            <TextBlock Name="text" Text="{Binding Nom}" TextWrapping="Wrap" Margin="102,16,16,22"/>
        </Grid>
    </DataTemplate>
</phone:PhoneApplicationPage.Resources>

I want to use the Textlock control in the CSharp code to pass the Text property to the second xaml page, but I can't find the name of the control, it's inaccessible.
Any idea ?

A: I just use VB.Net but I am sure you can convert.
Just use any shared variable in the application.
Here you can see it in an SourceCode example:
http://www.activevb.de/rubriken/kolumne/kol_30/res/nachtscanner.zip
Just use Public Shared MyText As String
in Application Class. This vairable you can access anywhere.
You can also use INotifyPropertyChanged for that shared property to bind.
Alternatively you can use Navigation Query. Read more here:
How can I pass query string variables with NavigationService.Navigate?

A: Your binding the Text of the TextBlock so you must have the value in your datacontext. I'd add this value to the Querystirng and navigate to the page.
var text = ((Whatever) DataContext).Nom;
string page2Uri = string.Foramt("/PAge2.xaml?Nom={0}", text);
NavigationService.Navigate(new Uri(page2Uri, UriKind.Relative));

And then to get the data out of the querystring you can use the OnNavigatedTo method in your page, and then inspect this.NavigationContext.QueryString["nom"]
Or have a look into something like the MVVM pattern.


text:
Q: Which Property type do I use to put a User's user_id() in the Datastore? This is why I need to put user_id()'s in the Datastore:

A User value in the datastore does not
  get updated if the user changes her
  email address. This may be remedied in
  a future release. Until then, you can
  use the User value's user_id() as the
  user's stable unique identifier.
http://code.google.com/appengine/docs/python/datastore/typesandpropertyclasses.html#users_User
Within the datastore, the value is
  equal to the email address plus the
  user's unique ID. If the user changes
  her email address, the new User value
  will not equal the original User value
  in datastore queries or when compared
  by the app. If your app needs a stable
  identifier that does not change, you
  can store the unique ID separately
  from the User value.
http://code.google.com/appengine/docs/python/users/userobjects.html

How do I do it?
And how did you know (or where did you look it up?)

A: The usual answer is "no property": If you need a stable identifier, it's probably because you're looking users up by it, in which case you should use it as the key name for the entity, like so:
class UserInfo(db.Model):
  is_admin = db.BooleanProperty(required=True, default=False)

user_info = UserInfo.get_or_insert(users.get_current_user().user_id())

If you really need to store an identifier for the user elsewhere, you can use a db.StringProperty to store the User ID.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Does Node.js fs.readFile() work as PHP's file_get_contents()? I have the following scripts that read and print an image as string:
PHP:
<?php
echo file_get_contents("/path/to/small.png");

Node.js:
var fs = require('fs')
var file = fs.readFileSync('/path/to/small.png', 'utf8');
console.log(file)

But there's a little bit difference between the strings output by 2 scripts. I tried the same thing with the following Go code and the outputs is identical to PHP's:
package main

import (
    "fmt"
    "io/ioutil"
)

func main() {
    buf, err := ioutil.ReadFile("/path/to/small.png")
    if err != nil {
        panic(err)
    }

    content := string(buf)
    fmt.Println(content)
}

So, anybody got an idea why does fs.readFile() behave differently?

A: var fs = require('fs')
var file = fs.readFileSync('/path/to/small.png', 'binary');
console.log(file)

references:
https://nodejs.org/dist/latest-v7.x/docs/api/fs.html#fs_fs_readfilesync_file_options
https://github.com/nodejs/node/blob/master/lib/buffer.js#L432

A: Garbage in, garbage out. If you tell Node that your binary picture file is a plain text file encoded as UTF-8, it's no wonder you get unexpected results.
On the other side, your PHP code just prints the exact bytes read.


text:
Q: How to create a custom FX component that renders it's children dinamically? I have a custom component representing a form field. It has a label, a text field and an error message that may be shown after input validation.
<fx:root maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="109.0" prefWidth="512.0" spacing="10.0" styleClass="vbox" type="VBox" xmlns="http://javafx.com/javafx/10.0.2-internal" xmlns:fx="http://javafx.com/fxml/1">
   <children>

      <TextField fx:id="textField" promptText="Lorem ipsum dolor sit amet"></TextField>

   </children>
</fx:root>

public class FormField extends VBox {

    @FXML private TextField textField;
    @FXML private Label fieldLabel;
    @FXML private Label errorLabel;

    private String fieldLabelText;
    private String promptText;

    public FormField(@NamedArg("fieldLabelText") String fieldLabelText,
                     @NamedArg("promptText") String promptText,
                     @NamedArg("isPasswordField") boolean isPasswordField) {

        FXMLLoader loader = new FXMLLoader(getClass().getResource("../../resources/fxml/form-field.fxml"));
        loader.setRoot(this);
        loader.setController(this);

        this.fieldLabelText = fieldLabelText;
        this.promptText = promptText;

        try {
            loader.load();
        } catch (IOException exception) {
            throw new RuntimeException(exception);
        }
    }

    @FXML
    public void initialize() {
        this.fieldLabel.setText(fieldLabelText);
        this.textField.setPromptText(promptText);
    }

Now what I want to know is how would I go about making an extension of this component that has a PasswordField instead of a TextField? Or passing an argument such as boolean isPasswordField that let's FormField decide if it should render a TextField or a PasswordField? If TextField had an obscureText(true) method in it's API it would be good enough since this is all I'm looking for, but I couldn't find any.
All I could find about JavaFX inheritance was in the sense of "extending" the object by adding new components to it, not by changing it's existing elements.

A: One option is to place both a TextField and a PasswordField in the UI, stacked on top of each other in a StackPane, with only one of them visible:
<fx:root maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="109.0" prefWidth="512.0" spacing="10.0" styleClass="vbox" type="VBox" xmlns="http://javafx.com/javafx/10.0.2-internal" xmlns:fx="http://javafx.com/fxml/1">
   <children>

      <StackPane>
        <TextField fx:id="textField" promptText="Lorem ipsum dolor sit amet"></TextField>
        <PasswordField fx:id="passwordField" visible="false"/>
      </StackPane>

   </children>
</fx:root>

Then in the controller decide which is visible based on the parameter that was passed:
public class FormField extends VBox {

    @FXML private TextField textField;
    @FXML private PasswordField passwordField;
    @FXML private Label fieldLabel;
    @FXML private Label errorLabel;

    private String fieldLabelText;
    private String promptText;
    private boolean isPasswordField;

    public FormField(@NamedArg("fieldLabelText") String fieldLabelText,
                     @NamedArg("promptText") String promptText,
                     @NamedArg("isPasswordField") boolean isPasswordField) {

        // path is copied from OP, but is incorrect:
        FXMLLoader loader = new FXMLLoader(getClass().getResource("../../resources/fxml/form-field.fxml"));
        loader.setRoot(this);
        loader.setController(this);

        this.fieldLabelText = fieldLabelText;
        this.promptText = promptText;
        this.isPasswordField = passwordField;

        try {
            loader.load();
        } catch (IOException exception) {
            throw new RuntimeException(exception);
        }
    }

    @FXML
    public void initialize() {
        this.fieldLabel.setText(fieldLabelText);
        this.textField.setPromptText(promptText);
        this.passwordField.promptTextProperty().bind(
            this.textField.promptTextProperty());
        this.passwordField.setVisible(isPasswordField);
        this.textField.setVisible(!isPasswordField);
    }

}

Other variations are possible, e.g. your FXML could just define the StackPane with no content; then in the controller code add either a TextField or PasswordField as needed.


text:
Q: Pre-Moving user files prior to folder redirection to new folder I have folder redirection in place at the office I work for. The user files currently reside in a folder on my file server. I am in the process of reworking the GPO and AD structure to facilitate better organization of files and users.
My question/issue is, is there any way I can move my existing users files into their new home without having to wait the hour plus for windows to do it automatically. In a test environment, a user with about 2GB worth of redirected data took approx. 30 minutes to move at log in. I have users that have 10GB plus of data that I would like to move to it's new home prior to the user logging in and having to wait several hours. I've tried copying the files over manually, but windows still acts like it's transferring files at log in (during the 'Welcome' screen.)
Is there any way to do this that is tried and tested? Any help would be appreciated. Thanks

A: I have figured out a sort of work around for the time being. I am copying the redirected files over to the local drive of the computer while the user is still logged in. I then have them log off and back on to refresh the GPO and have them copy their files back to their Documents folder that is redirected to the new location. A bunch of copying, but it minimizes the amount of time on the Welcome screen.


text:
Q: How to get java 1.6 applet working on mac os x anyone got java 1.6 applet working on mac os x ?
check it on gemal.dk/browserspy/java.html
I got Java using object and applet tag  1.5.0_16 (1.5.0_16-133) from Apple Inc.
and you ?
on windows and linux 1.6 working gracefully :S

A: On Leopard, open /Applications/Utilities/Java/Java Preferences.app, and select Java 6 as the default for your applets. This won't work, of course, if you don't have an Intel Mac running Leopard (at least, I think it requires Leopard... perhaps there's an installer for Tiger). In either event, not reliable if you need to deploy 1.6-based applets to users, but works tickety-boo for your own surfing.

A: There should be an installed Java JRE picker... had a similar road block, give it a peak.

A: It was a problem with OSX itself that didn't support 1.6 on applets now everything is updated and works on 10.6.6 at least
I wrote it here so somebody don't confuse this problem with another.


text:
Q: Is this powershell script a good way to find the owner then change the owner I wrote a Powershell v3 script to list all the files owned by a user on our file server.  It ran for 3 hours before I stopped it. It has to go through 619,238 Files and 57,452 Folders (517 GB). What order of magnitude should this take? Is there a way to improve the speed?
I tried to do this using pipes, but failed to get anything to work.
It's running on a Vmware virtual machine running Windows 2009 R2 SP1 with 4GB of memory. It uses about 60% of the CPU when I run it.
Here the code I wrote. I am very new to Powershell, but I have a lot of experience with Perl. My co-workers said to write a bat file.
<#
.SYNOPSIS
   C:\ams\psscripts\list-files.ps1
.DESCRIPTION
   List all the files that a given user owns
.PARAMETER none
   username: user
   logfile: path to log file. This is optional. If omitted the the log file is created "u:\scratch\<$username>-files.txt
.EXAMPLE
    C:\ams\psscripts\list-files.ps1 plo
    Example: C:\ams\psscripts\list-files.ps1 plo u:\scratch\log.txt

#>

param (
    [string]$username,
    [string]$logfile
    )

# Load modules
Set-ExecutionPolicy Unrestricted
Import-Module ActiveDirectory
Add-PSSnapin Quest.ActiveRoles.ADManagement

function printHelp {
    Write-Host "This script will find all the files owned by a user. It scans \\dfs\groups"
    Write-Host "C:\ams\psscripts\list-files.ps1 user logfile (optional)"
    Write-Host "Example: C:\ams\psscripts\list-files.ps1 plo"
    Write-Host "Example: C:\ams\psscripts\list-files.ps1 plo u:\scratch\log.txt"
}

if ($logfile -eq "") {
    $logfile = "u:\scratch\" + $username + "-files.txt"
    Write-Host "Setting log file to $logfile"
}

# you must use a UNC path
[String]$path = "\\dfs\u$\groups"
[String]$AD_username = "AMS\" + $username

# check that we have a valid AD user
if (!(Get-QADUser $AD_username)){
    Write-Host "ERROR: Not a valid AD User: $AD_username"
    Exit 0
}

Write-Output "Listing all files owned by $username from $path" | Out-File -FilePath $logfile
Write-Host "Listing all files owned by $username from $path"
$d = Get-Date
Write-Output $d | Out-File -FilePath $logfile -Append

$files = Get-ChildItem $path -Recurse
Foreach ($file in $files)
{
    $f = Get-Acl $file.FullName

    $d = [string]::Compare($file.FullName, $username, $True)
    if (($f.Owner -eq $username) -or ($f.Owner -eq $AD_username))
    {
        Write-Host "$file.FullName"
        Write-Output $file.FullName | Out-File -FilePath $logfile -Append
    }
}

Write-Host "Completed"
exit 0

The next step I have to do is modify the script above to find the files owned by a given user and change them to their manager.
This is the script I found to change the owner. It will be in a loop which walks the filesystem. Is this a good way to do this.
$username="dnp"
$domain="ams"
$ID = new-object System.Security.Principal.NTAccount($domain, $username)

# file to change owner. must be UNC path
$path = "\\dfs\c$\ams\psscripts\test.txt"
write-host $path
$acl = get-acl $path
$acl.SetOwner($ID)
set-acl -path $path -aclObject $acl

Thanks,
Dan

A: Try using this to log the files owned by user as there's no writing out to disk until the whole process is completed:
[string]$fileowned +=  $file.fullname|?{$f.owner -eq $username -or $f.owner -eq $AD_username}

Once out of loop, then write resulting $logfile out to disk:
$fileowned|out-file $logfile

By the way, you're using $d twice; once for get-date and next for the compare string.

A: I don't know what order of magnitude that should take but to improve the speed you could start by removing the redundant compare in your foreach loop:
$d = [string]::Compare($file.FullName, $username, $True)

String comparison is costly and you're not using $d.  You're also comparing against $username or "AMS\" + $username which again is costly.  I can't see why you need to compare against both.  I've modified your script to add timing to it.  I would recommend trying it on a subset of the files to get some empirical data to work out how long the full set would take.  Bear in mind that the total size of the files is irrelevant in this case as you aren't processing them, just their properties.
<#
.SYNOPSIS
   C:\ams\psscripts\list-files.ps1
.DESCRIPTION
   List all the files that a given user owns
.PARAMETER none
   username: user
   logfile: path to log file. This is optional. If omitted the the log file is created "u:\scratch\<$username>-files.txt
.EXAMPLE
    C:\ams\psscripts\list-files.ps1 plo
    Example: C:\ams\psscripts\list-files.ps1 plo u:\scratch\log.txt

#>

param (
    [string]$username,
    [string]$logfile
    )

# Load modules
Set-ExecutionPolicy Unrestricted
#Import-Module ActiveDirectory
#Add-PSSnapin Quest.ActiveRoles.ADManagement

function printHelp {
    Write-Host "This script will find all the files owned by a user. It scans \\dfs\groups"
    Write-Host "C:\ams\psscripts\list-files.ps1 user logfile (optional)"
    Write-Host "Example: C:\ams\psscripts\list-files.ps1 plo"
    Write-Host "Example: C:\ams\psscripts\list-files.ps1 plo u:\scratch\log.txt"
}

#StopWatch
$stopWatch = New-Object System.Diagnostics.Stopwatch
$stopWatch.Start()

if ($logfile -eq "") {
    $logfile = "e:\scratch\" + $username + "-files.txt"
    Write-Host "Setting log file to $logfile"
}

# you must use a UNC path
[String]$path = "\\test-server\testfolder\subfolder"
[String]$AD_username = "AMS\" + $username

# check that we have a valid AD user
if (!(Get-QADUser $AD_username)){
    Write-Host "ERROR: Not a valid AD User: $AD_username"
    Exit 0
}

Write-Output "Listing all files owned by $username from $path" | Out-File -FilePath $logfile
Write-Host "Listing all files owned by $username from $path"
$d = Get-Date
Write-Output $d | Out-File -FilePath $logfile -Append

$stopWatch.Stop()
Write-Output ("Setup time: {0}." -f $stopWatch.Elapsed) | Out-File -FilePath $logfile -Append
$stopWatch.Reset()

$stopWatch.Start()
$files = Get-ChildItem $path -Recurse
$stopWatch.Stop()
Write-Output ("Got {0} files to process, took {1}" -f $files.Count, $stopWatch.Elapsed) | Out-File -FilePath $logfile -Append
$stopWatch.Reset()

$stopWatch.Start()
Foreach ($file in $files)
{
    $f = Get-Acl $file.FullName

    #$d = [string]::Compare($file.FullName, $username, $True)
    #if (($f.Owner -eq $username) -or ($f.Owner -eq $AD_username))
    if ($f.Owner -eq $AD_username)
    {
        Write-Host ("{0}" -f $file.FullName)
        Write-Output $file.FullName | Out-File -FilePath $logfile -Append
    }
}
$stopWatch.Stop()
Write-Output ("Processed {0} files, took {1}" -f $files.Count, $stopWatch.Elapsed) | Out-File -FilePath $logfile -Append

Write-Host "Completed"
exit 0

Running this yielded the following results in our infrastructure:
Got 37803 files to process, took 00:00:57.5834897
Processed 37803 files, took 00:10:42.2988004
Your original code took 15 minutes to process the same number of files:
Processed 37803 files, took 00:15:04.1024350
Added @GeorgeR.Jenkins in memory string construction but it didn't make a significant reduction to the processing time:
Processed 37803 files, took 00:10:26.7815446
Interestingly attempting to pipe the get-childitem to a where clause didn't improve the performance.  Using
$files = Get-ChildItem $path -Recurse | where {(Get-Acl $_.FullName).Owner -eq $AD_username} <br/>

which will only return files with the correct owner so no processing was needed later yielded:
Got 46 files to process, took 00:13:51.4940596
That all said, if you where running on similar infrastructure to me I would expect, at the fastest rate I've seen, which is 59 files per second, that your 619,238 files would take around 175 minutes.  The rate I got with your original code was 42 files per second, which would have taken 246 minutes.  Again I would advise running on your system with a small subset of the files to calculate how long it will take before running the whole set.


text:
Q: XCode - Dynamically created labels, when i change the text it changes it for the last one only So i have a bunch of dynamically loaded labels..
Each of them has the same name because there is no telling how many there will be..
I have another method (not the one that created the labels) changing the text for one of the labels, but when i run it only the last label that was created will change..
I need it to change the one that has a certain tag or something..
Help is much appreciated, this website is yet to let me down.

A: self.myLabel  cannot be connected to multiple labels, so it will contain the reference of last created label, you will have to create new label every time, and you can't track them by class properties, you have to access label by their tag.
you can set tag for each label, below is sample code,
 for(int i=0; i< numberOfLabels; i++)
{
    UILabel *label = [[UILabel alloc] init];
    label.tag = i; // do not use tag 0 here.. u can use i+1, or i+100.. something like this.
    [self.view addSubview:label];
}

to access labels,
UILabel *label = (UILabel*)[self.view viewWithTag: labelTag];

A: Okay since you dont have any code to show i guess i have to speculate.
What i understood is that you are creating Dynamic UILabels in ur code and you want to access them. Since you have same name for all the UILabels you might me loosing the previous UILabel when every time you create a new UILabel. So in order to keep track of how many UILabel you created you must add them in an Array. Declare an NSMutableArray in your viewController.h file and make sure in the viewDidLoad u allocate it like
arrForLabels = [[NSMutableArray alloc]init];

Since it is an NSMutableArray you can add object to it.
So when u create a UILabel make sure you add the same UILabel in the Array as well
for Instance
[arrForLabels addObject:yourLabel];

you can try to NSLog your Array to see its content.
Now all youu got to do is to Create a weak link like that
UILabel *tempLabel = [arrForLabels objectAtIndex:1];

now tempLabel will be the UILabel to change text
tempLabel.text = @"My New Text";

It will work fine.
Feel free to ask for any issues in it.


text:
Q: Case para vários campos Consigo fazer uma query utilizando 1 case para vários campos? Os campos são do tipo int.
Caso não, consigo fazer em php?
Query
select *,
(case (pergunta1,pergunta2)
when 1 then 'Ótimo'
when 2 then 'Bom'
when 3 then 'Regular'
when 4 then 'Ruim'
END) as pergunta1,pergunta2 from tabela

A: Sim, porém pra utilizar esse tipo de case você não pode ter o valor fixo logo após o case e os testes devem ser realizados no when da seguinte forma:
select *,
      (case
         when pergunta1 = 1 and pergunta2 = 1 then 'Ótimo'
         when pergunta1 = 2 and pergunta2 = 2 then 'Bom'
         when pergunta1 = 3 and pergunta2 = 3 then 'Regular'
         when pergunta1 = 4 and pergunta2 = 4 then 'Ruim'
      END) as pergunta1,pergunta2 from tabela


text:
Q: How to set up a parallel port printer in 12.04? After the upgrade from 10.04 to 12.04 the parallel printer stopped working. It seems that that the parallel port is not detected. I didn't change anything in the bios and before it worked without problems.
I followed the instructions of this page:
https://wiki.ubuntu.com/DebuggingPrintingProblems#Parallel_port_printer
$ lsmod | grep lp
lp                     17799  0
parport                46562  3 ppdev,lp,parport_pc
$ lsmod | grep ppdev
ppdev                  17113  0
parport                46562  3 ppdev,lp,parport_pc
$ lsmod | grep parport_pc
parport_pc             32866  0
parport                46562  3 ppdev,lp,parport_pc
$ dmesg | grep par
[    0.000000] Booting paravirtualized kernel on bare hardware
[    0.000000] vt handoff: transparent VT on vt#7
[    0.515991] hpet0: 8 comparators, 64-bit 14.318180 MHz counter
[   18.007169] type=1400 audit(1371154439.505:2): apparmor="STATUS"    operation="profile_load" name="/sbin/dhclient" pid=654 comm="apparmor_parser"
[   18.007426] type=1400 audit(1371154439.505:3): apparmor="STATUS" operation="profile_load" name="/usr/lib/NetworkManager/nm-dhcp-client.action" pid=654 comm="apparmor_parser"
[   18.007575] type=1400 audit(1371154439.505:4): apparmor="STATUS" operation="profile_load" name="/usr/lib/connman/scripts/dhclient-script" pid=654 comm="apparmor_parser"
[   18.007789] type=1400 audit(1371154439.505:5): apparmor="STATUS" operation="profile_replace" name="/sbin/dhclient" pid=716 comm="apparmor_parser"
[   18.008101] type=1400 audit(1371154439.505:6): apparmor="STATUS" operation="profile_replace" name="/usr/lib/NetworkManager/nm-dhcp-client.action" pid=716 comm="apparmor_parser"
[   18.008280] type=1400 audit(1371154439.505:7): apparmor="STATUS" operation="profile_replace" name="/usr/lib/connman/scripts/dhclient-script" pid=716 comm="apparmor_parser"
[   18.019011] ppdev: user-space parallel port driver
[   19.744248] type=1400 audit(1371154441.241:8): apparmor="STATUS" operation="profile_load" name="/usr/lib/lightdm/lightdm/lightdm-guest-session-wrapper" pid=964 comm="apparmor_parser"
[   19.744326] type=1400 audit(1371154441.241:9): apparmor="STATUS" operation="profile_replace" name="/sbin/dhclient" pid=965 comm="apparmor_parser"
[   19.744676] type=1400 audit(1371154441.241:10): apparmor="STATUS" operation="profile_replace" name="/usr/lib/NetworkManager/nm-dhcp-client.action" pid=965 comm="apparmor_parser"
[   19.744874] type=1400 audit(1371154441.241:11): apparmor="STATUS" operation="profile_replace" name="/usr/lib/connman/scripts/dhclient-script" pid=965 comm="apparmor_parser"
$ ls -l /dev/lp* /dev/parport*
ls: Zugriff auf /dev/lp* nicht möglich: Datei oder Verzeichnis nicht gefunden
ls: Zugriff auf /dev/parport* nicht möglich: Datei oder Verzeichnis nicht gefunden
$ ls -l /proc/sys/dev/parport/parport*/autoprobe*
ls: Zugriff auf /proc/sys/dev/parport/parport*/autoprobe* nicht möglich: Datei oder Verzeichnis nicht gefunden
$ sudo cat /proc/sys/dev/parport/parport*/autoprobe*
cat: /proc/sys/dev/parport/parport*/autoprobe*: Datei oder Verzeichnis nicht gefunden
$ lpinfo -v
network lpd
network ipps
network http
network https
network socket
network ipp14
network ipp
network beh
direct scsi
direct hp
network smb
direct hpfax
$ /usr/lib/cups/backend/parallel
$ sudo /usr/lib/cups/backend/parallel

Any ideas?


text:
Q: Python - automaticly zip specific folders/files I have been getting into Python lately and have come across a problem wich i think i could solve using it.
I have a USB stick with a lot of folders in there, the folders each contain the following:
/HTML5/
/Images/
foldername.html
foldername.ofp
preview.html
profile.xml

Now, i have to create a zip file of each folder, but only containing the Images folder and the profile.xml file. There is 40ish folders in there and there will be more in the future.
Here is the final code:
# Script to zip Foldername/Images/ and Foldername/profile.xml to Foldername.zip

import os
import zipfile

dirname = "D:\\testdir"

for schoen in os.listdir(dirname):
    print schoen
    myZipFile = zipfile.ZipFile(schoen+".zip", "w" )
    for f in os.listdir(os.path.join(dirname, schoen)):
        print f
        if f == "Profile.xml":
            print "Found profile.xml"
            myZipFile.write(schoen + "\\" + f, f)
        elif f == "Images":
            print "Found Images"
            myZipFile.write(schoen + "\\" + f, f)
    myZipFile.close()

Many thanks,
Grootie

A: Instead of finding random code and trying to guess what it might mean and what you should change, why not look it up in the documentation?
The parameters to ZipFile.write are:
ZipFile.write(filename, arcname=None, compress_type=None)

So your code copies the file named profile.xml into the archive under the name images\\test.py. Is that really what you want? I doubt it. But I'm not sure what you do want. You need to figure that out, in terms you could explain to an idiot (because computers are idiots). Then the docs—or SO, if you get confused by the docs—can help you translate that explanation into the appropriate code.


text:
Q: Julia macro splatting Why does this work:
function test_func(a, b)
  a + b
end

test_func((1, 2)...)

But this does not?
macro test_func(a, b)
  a + b
end

@test_func((1, 2)...)

Is it a bug in Julia?

A: Macros operate on surface syntax, so @test_func isn't seeing the result of the splat.  Instead, it sees the splat operation itself!  As always, a great way to inspect this is to quote it and see exactly what syntax the macro is operating on:
julia> :(@test_func((1,2)...))
:(@test_func (1,2)...)

julia> Meta.show_sexpr(ans)
(:macrocall, symbol("@test_func"), (:..., (:tuple, 1, 2)))

So the macro is only receiving one argument (not two), and it's an Expr(:..., Expr(:tuple, 1, 2)).  Notice that the tuple (1,2) is getting passed to your macro, but it's just hidden away inside the splat operation.  So you could dig into the Expr and kind-of-sort-of implement splatting yourself:
julia> macro test_func(as...)
           if length(as) == 1 && isa(as[1], Expr) && as[1].head == :... &&
                  isa(as[1].args[1], Expr) && as[1].args[1].head == :tuple
               a, b = as[1].args[1].args
           elseif length(as) == 2
               a, b = as
           else
               error("unsupported syntax $as")
           end
           return esc(:($a + $b))
       end

julia> @test_func((1,2)...)
3

But this only kind-of-sort-of supports splatting.  Look what happens if you try to operate on a variable instead:
julia> @test_func(xs...)
ERROR: unsupported syntax (:(xs...),)

There's now no way for the macro to know what it should be adding together!


text:
Q: Angular Kendo UI Tabstrip active state for dynamic tabs I am trying to implement dynamic tabs using Kendo UI Tabstrip in Angular JS. How to indicate the active state? For example I want the second tab to be active by default.
Markup with directives

//Tabs controller
ngUI.controller('nguiTabsController', function($scope) {
     $scope.panes = {

        data : [ {title:"First", content:"Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec vitae dolor sed lacus interdum rutrum. Mauris mauris dui, rhoncus ut magna vitae, faucibus elementum lectus. "},
                 {title:"Second", content:"Sed auctor, turpis at scelerisque dapibus, dolor quam laoreet nibh, in pulvinar augue est a est. Nulla eu nulla nunc. Donec eu augue placerat, tincidunt diam vel, fringilla velit. Ut convallis faucibus neque. Nullam pellentesque, nisi quis facilisis tincidunt."},
                 {title:"Third", content:"Maecenas posuere tellus vel elit cursus porttitor. Proin auctor lorem risus, sit amet blandit ligula ultricies sit amet. Pellentesque eget velit ut libero faucibus lobortis."},
                 {title:"Fourth", content:"Suspendisse sodales consequat aliquet. Mauris ultricies nisl a metus convallis, at iaculis elit scelerisque. Nullam dignissim convallis lectus eu malesuada. Etiam libero mi, suscipit at auctor id, porta eu justo. Nullam a ipsum dictum, gravida erat vitae, sollicitudin justo."},
                 {title:"Fifth", content:"Phasellus suscipit ipsum molestie augue interdum sodales. Sed sit amet eros in odio viverra aliquam vitae nec odio. Nulla condimentum eleifend tortor, non malesuada purus placerat non. Mauris porttitor odio tortor."}]

};

});

A: Change the div to define the widget reference;
<div data-kendo-tab-strip="tabStrip"...

In the controller, create the tabStrip scope variable and place a watch on it.  When it is set, select the desired tab by number.
ngUI.controller('nguiTabsController', function($scope) {
    $scope.tabStrip = null;
    $scope.$watch('tabStrip', function() {
      $scope.tabStrip.select(0);
    });

    $scope.panes...
}


text:
Q: Python: cross-function threading Does anyone know a way to acquire a lock so that not only the called function but also other functions are locked.
Let's say I have a bunch of functions ( a(),b(),c() ) an when I call function a() I want also functions b() & c() to be locked.
import threading
from time import sleep

def a():
    for i in range(5):
        print(i)
        sleep(1)

def b():
    for i in range(5):
        print(i)
        sleep(1)

def c():
    for i in range(5):
        print(i)
        sleep(1)

thread_a=threading.Thread(target=a)
thread_a.start()
thread_b=threading.Thread(target=b)
thread_b.start()
thread_c=threading.Thread(target=c)
thread_c.start()

How would I have to use the lock if i wanted the above code to give the output:
0
1
2
3
4
0
1
2
3
4
0
1
2
3
4

?
Any help appreciated,
Greetz

A: You must in a way or another use the same Lock instance shared between your functions.
lock = threading.Lock()

def a():
    with lock:
        for i in range(5):
            print(i)
            sleep(1)

Do this for each function and it will output what you want.


text:
Q: Does a vibrating string produce changes in tension in the string? A taut string anchored at both ends increases in tension as the string is displaced to a side. When released the string will vibrate at whatever frequency to which the system is tuned.
If this were a simple standing wave it seems that tension would drop as the string moved to the neutral position and increase again as it deflected on the opposing side. Harmonics in this case would not change the behavior.
Is this the way an actual string behaves, or is there some other oscillation pattern that allows tension to remain relatively constant even as the string vibrates? Does a vibrating string always produce changes in tension?

A: This question covers a lot of area, so let's work through it piece by piece.
First, the normal approximation for a vibrating string is (a) a transverse (perpendicular to string) displacement that (b) is a small where (c) the string acts like a spring:  (small) changes in length result in (small) changes to the tension.
What's "small"?  Much less than what's already there.
In that case, there is a periodic change in tension as the string vibrates.  It goes like the amplitude squared: two positive peaks and two zeros per cycle of the string. Again, this is small compared to the tension already in the string, and is usually ignored on that basis.
If the amplitude is large, so that the tension change is large, then the motion gets more complicated: Still periodic, but not the nice sinusoidal form with constant frequency. The increased tension at the peaks tends to "flatten" the plus and minus peaks of the sinusoidal motion by pulling back early; it also raises the frequency as the amplitude increases. With even more tension, it gets even more complicated...
But there are string oscillations that behave somewhat differently.  For example, a rotary vibration is possible:  Think of the motion of a double-dutch jump rope that's circling around with two fixed end points.  That's vibrating, but it also has a constant length hence (slightly) increased, but constant, tension.

A: String vibration, as well as vibration of other mechanical oscillators (springs, pendulums, etc.) involves periodic back and forth transitions between its kinetic and potential energy.
The potential energy of a string is associated with its tension, the kinetic energy - with its velocity.
So, if the tension of a string stayed the same, its potential energy would not be changing, there would not be any transitions between potential and kinetic energy and, therefore, there would not be any vibrations.


text:
Q: Why does my cumulative column not work as expected? Here is my query , I have a column called cum_balance which is supposed to calculate the cumulative  balance but after row number 10 there is an anamoly and it doesn't work as expected , all I notice is that from row number 10 onwards the hour column has same value. What's the right syntax for this?
[select
  hour,
  symbol,
  amount_usd,
  category,
  sum(amount_usd) over (
    order by
      hour asc RANGE BETWEEN UNBOUNDED PRECEDING
      AND CURRENT ROW
  ) as cum_balance
from
  combined_transfers_usd_netflow
order by
  hour][1]

I have tried removing RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW , adding a partition by hour and group by hour. None of them gave the expected result or errors

Row Number
Hour
SYMBOL
AMOUNT_USD
CATEGORY
CUM_BALANCE

1
2021-12-02 23:00:00
WETH
227.2795
in
227.2795

2
2021-12-03 00:00:00
WETH
-226.4801153
out
0.7993847087

3
2022-01-05 21:00:00
WETH
5123.716203
in
5124.515587

4
2022-01-18 14:00:00
WETH
-4466.2366
out
658.2789873

5
2022-01-19 00:00:00
WETH
2442.618599
in
3100.897586

6
2022-01-21 14:00:00
USDC
99928.68644
in
103029.584

7
2022-03-01 16:00:00
UNI
8545.36098
in
111574.945

8
2022-03-04 22:00:00
USDC
-2999.343
out
108575.602

9
2022-03-09 22:00:00
USDC
-5042.947675
out
103532.6543

10
2022-03-16 21:00:00
USDC
-4110.6579
out
98594.35101

11
2022-03-16 21:00:00
UNI
-3.209306045
out
98594.35101

12
2022-03-16 21:00:00
UNI
-16.04653022
out
98594.35101

13
2022-03-16 21:00:00
UNI
-16.04653022
out
98594.35101

14
2022-03-16 21:00:00
UNI
-16.04653022
out
98594.35101

15
2022-03-16 21:00:00
UNI
-6.418612089
out
98594.35101

A: The "problem" with your data in all the ORDER BY values after row 10 are the same.
So if we shrink the data down a little, and use for groups to repeat the experiment:
with data(grp, date, val) as (
    select * from values
    (1,'2021-01-01'::date, 10),
    (1,'2021-01-02'::date, 11),
    (1,'2021-01-03'::date, 12),

    (2,'2021-01-01'::date, 20),
    (2,'2021-01-02'::date, 21),
    (2,'2021-01-02'::date, 22),
    (2,'2021-01-04'::date, 23)
)
select d.*
    ,sum(val) over ( partition by grp order by date RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW ) as cum_val_1
    ,sum(val) over ( partition by grp order by date ) as cum_val_2
from data as d
order by 1,2;

we get:

GRP
DATE
VAL
CUM_VAL_1
CUM_VAL_2

1
2021-01-01
10
10
10

1
2021-01-02
11
21
21

1
2021-01-03
12
33
33

2
2021-01-01
20
20
20

2
2021-01-02
21
63
63

2
2021-01-02
22
63
63

2
2021-01-04
23
86
86

we see with group 1 that values accumulate as we expect. So for group 2 we put duplicate values as see those rows get the same value, but rows after "work as expected again".
This tells us how this function work across unstable data (values that sort the same) is that they are all stepped in one leap.
Thus if you want each row to be different they will need better ORDER distinctness. This could be forced by add random values of literal random nature, or feeling non random ROW_NUMBER, but really they would be random, albeit not explicit, AND if you use random, you might get duplicates, thus really should use ROW_NUMBER or SEQx to have unique values.
Also the second formula shows they are equal, and it's the ORDER BY problem not the framing of "which rows" are used.
with data(grp, date, val) as (
    select * from values
    (1,'2021-01-01'::date, 10),
    (1,'2021-01-02'::date, 11),
    (1,'2021-01-03'::date, 12),

    (2,'2021-01-01'::date, 20),
    (2,'2021-01-02'::date, 21),
    (2,'2021-01-02'::date, 22),
    (2,'2021-01-04'::date, 23)
)
select d.*
    ,seq8() as s
    ,sum(val) over ( partition by grp order by date ) as cum_val_1
    ,sum(val) over ( partition by grp order by date, s ) as cum_val_2
    ,sum(val) over ( partition by grp order by date, seq8() ) as cum_val_3
from data as d
order by 1,2;

gives:

GRP
DATE
VAL    S
CUM_VAL_1
CUM_VAL_2
CUM_VAL_2_2

1
2021-01-01
10
0
10
10

1
2021-01-02
11
1
21
21

1
2021-01-03
12
2
33
33

2
2021-01-01
20
3
20
20

2
2021-01-02
21
4
63
41

2
2021-01-02
22
5
63
63

2
2021-01-04
23
6
86
86


text:
Q: How to style a single QToolButton using qss/css I have a toolbar with multiple toolbuttons on it, I have tried to apply a style to an individual button with:
QToolButton#button_name
{
    border: 3px solid #FF00FF;
}

I thought this would have applied a pink border to just the one button which has the name "button_name" but it does nothing.
i can apply a style to all buttons on the toolbar if i take the "#button_name" off. So im wondering if there is anyway to individual set styles for a specific QToolButton
Cheers

A: You should change objectName of needed widget, not QAction. You can get this widget with widgetForAction() method. For example:
QToolBar tool;

QAction * foo = new QAction("foo",&tool);
QAction * bar = new QAction("bar",&tool);
QAction * baz = new QAction("baz",&tool);

tool.addAction(foo);
tool.addAction(bar);
tool.addAction(baz);

tool.widgetForAction(bar)->setObjectName("unique");
tool.show();

qApp->setStyleSheet("QToolButton#unique{border: 3px solid #FF00FF;}");

Result:


text:
Q: How to change the format of acronyms? I use the acronym package.
Please help me to change a gap between the acronym and full name of acronym and to put a dash between them like this:

PG       - some text

HRoT     - some text some text some text some text some
           text some   text some text some text some text some text

Also I would like to make the acronyms shown in Roman text-style (by default it's in Bold)
  \documentclass[12pt]{report}
  \usepackage{fontspec}
  \usepackage{xunicode}
  \usepackage[no-sscript]{xltxtra}
  \usepackage[babel=false]{csquotes}
  \usepackage{polyglossia}
  \setdefaultlanguage{french}
  \setotherlanguages{german,english,greek,polish,russian}
  \setmainfont[Mapping=tex-text]{Linux Libertine}
  \usepackage{acronym}

  \makeatletter
  \def\uplabel#1{{\normalfont{\textsf{#1}}\hfill}-}
  \renewenvironment{AC@deflist}[1]%
    {\ifAC@nolist%
     \else%
        \raggedright\begin{list}{}%
            {\settowidth{\labelwidth}{\normalfont{\textsf{#1}}\hspace*{3em}}% change 2em to the desired value
            \setlength{\leftmargin}{\labelwidth}%
            \addtolength{\leftmargin}{\labelsep}%
            \renewcommand{\makelabel}{\uplabel}}%
      \fi}%
    {\ifAC@nolist%
     \else%
        \end{list}%
     \fi}%
  \makeatother

  \begin{document}
  \begin{acronym}
  \acro{Esj}{some text some text some text some text some text some text some text some text some textsome text some text some text}

  \acro{At}{some text some text some text some text some text some text some text some text some text some text some textsome textsome text some text some text}
  \end{acronym}
  \end{document}

EDIT: Extra dash

A: The file acronym.sty uses \bflabel to typeset the label in boldface and using small capitals; I defined a new macro \uplabel which uses \normalfont instead of boldfaced series and includes a hyphen to separate the acronym and its definition; this command will be used in the environment AC@deflist which formats the list of acronyms and will have to be redefined to increase the separation between the acronyms and their definitions. The acronym environment will also have to be redefined.
Add the following lines to the preamble (after the acronym package has been loaded) and change the used values according to your needs:
\documentclass[12pt]{report}
  \usepackage{fontspec}
  \usepackage{xunicode}
  \usepackage[no-sscript]{xltxtra}
  \usepackage[babel=false]{csquotes}
  \usepackage{polyglossia}
  \setdefaultlanguage{french}
  \setotherlanguages{german,english,greek,polish,russian}
  \setmainfont[Mapping=tex-text]{Linux Libertine}
  \usepackage{acronym}
\usepackage{enumitem}

\renewcommand\acsfont{\normalfont}

\makeatletter
\def\uplabel#1{{\normalfont{\textsf{#1}}\hfill}-}
\renewenvironment{acronym}[1][1]{%
   \providecommand*{\acro}{\AC@acro}%
   \providecommand*{\acroplural}{\AC@acroplural}%
   \long\def\acroextra##1{##1}%
   \def\@tempa{1}\def\@tempb{#1}%
   \ifx\@tempa\@tempb%
      \global\expandafter\let\csname ac@des@mark\endcsname\AC@used%
      \ifAC@nolist%
      \else%
         \begin{list}{}%
                {\settowidth{\labelwidth}{\normalfont{\textsf{#1}}\hspace*{3em}}% change according to your needs
                \setlength{\leftmargin}{\labelwidth}%
                \addtolength{\leftmargin}{\labelsep}%
                \renewcommand{\makelabel}{\uplabel}}
      \fi%
   \else%
      \begin{AC@deflist}{#1}%
   \fi%
  }%
  {%
   \ifx\AC@populated\AC@used\else%
      \ifAC@nolist%
      \else%
          \item[]\relax%
      \fi%
   \fi%
   \expandafter\ifx\csname ac@des@mark\endcsname\AC@used%
      \ifAC@nolist%
      \else%
        \end{list}%
      \fi%
   \else%
      \end{AC@deflist}%
   \fi}%
\renewenvironment{AC@deflist}[1]%
        {\ifAC@nolist%
         \else%
            \raggedright\begin{list}{}%
                {\settowidth{\labelwidth}{\normalfont{\textsf{#1}}\hspace*{3em}}% change according to your needs
                \setlength{\leftmargin}{\labelwidth}%
                \addtolength{\leftmargin}{\labelsep}%
                \renewcommand{\makelabel}{\uplabel}}%
          \fi}%
        {\ifAC@nolist%
         \else%
            \end{list}%
         \fi}%
 \makeatother

  \begin{document}
  \begin{acronym}
  \acro{Esj}{some text some text some text some text some text some text some text some text some textsome text some text some text}

  \acro{At}{some text some text some text some text some text some text some text some text some text some text some textsome textsome text some text some text}
  \end{acronym}
  \end{document}

EDIT: acronym environment redefined.


text:
Q: Applying styles to categorized layer using QGIS I have categorised a layer so I can attach reference numbers and names to the various points but I would like all the points to have the same colour and only be differentiated by their number.
Unfortunately QGIS automatically sets it to colour each item as part of a range of colours and I can't seem to find a way of making them all the same colour.

A: The categorising in QGis is so you can have different styling based on certain criteria in the data ('categories' for certain ranges of a parameter in one of the data fields).
If you want them all to look the same, don't go for categorised, but 'single symbol' (bottom left of the 'style' tab in properties, and set the style once. It'll apply to all objects that way.


text:
Q: Cannt run pdflatex in texstudio If i run in terminal sudo pdflatex file.tex it works and compiles but not if i dont add sudo nor use texstudio?
I tryed to add pdflatex to my $PATH:
PATH=$PATH:/usr/bin/pdflatex
export PATH

but it didnt help.
$ sudo which pdflatex
/usr/bin/pdflatex


text:
Q: Can you change preset html form input value? So if I have a form with a text input, or a select input, I want that box to have a certain value when the page loads.  I know you can add,
value="pre defined value"

but when the user erases that and puts in something else, when the form is submitted, is the value that is sent the predefined one or the one that the user changed it to?

A: The answer to your question is:
The value that is sent is the input that the user typed into the textbox and the value from the select input will be the one you set unless the user uses his browser to change the value(with any developer tools).
On a side note:
If an attacker changes the values then that value will be sent, this is why you must validate all input on server side, and also validate input from hidden, select, checkboxes, etc... elements. Client-side validation is only helpfull to tell the user if he has filled an input with the wrong thing but won't help you against any attacks since they can change the values that are sent with developer tools or a proxy.


text:
Q: What does a custom APN profile actually do, and why do I have to re-enter the proxy in my browser when I tether? I'm currently in Canada and I'm using the 7-Eleven Speakout "unlimited browsing" mobile internet plan. Unlimited browsing means that only HTTP and HTTPS are unblocked, while any services that use other ports probably won't work. In order to use the Speakout internet service, you have to specify custom APN settings, as follows: (according to the official website)
Homepage http://wap:8582/start.wml
Connection security: Off
Active Bearer: GPRS
Connection type: GPRS Attach on Demand
Authentication Type: Normal Access Point Name: goam.com
User Name: wapuser1
Password: wap
Login Type: Automatic
Primary Proxy Server Setting 10.128.1.69
Primary Proxy Server Port: 80

Once I entered these settings into my phone, all my apps worked fine. However, when I first tried to tether my phone to my PC, I couldn't get any websites to load. A helpful tip suggested that I try using 10.128.1.69:80 as a proxy server, and once I dialed those settings into Firefox, everything started working as expected. However, I still have absolutely no idea how the whole system is working under the hood, and this bothers me.
My questions:

*

*What do the APN settings on the phone actually do? In regards to the access point name and the primary proxy server, What exactly happens when I tell Safari to load a webpage?

*Why do I have to enter the proxy server a second time in Firefox? Shouldn't my computer traffic be transparently sent through my phone's mobile internet, exactly the same as Mobile Safari?

*I never have to enter any proxy settings into Firefox when I'm using normal tethering with my AT&T mobile internet plan. What makes Speakout so different?

Thank you!

A:
What do the APN settings on the phone actually do?

The APN settings contain information required to set up an internet data connection
while you are on a mobile network (that is, not connected to wifi).

In regards to the access point name and the primary proxy server, What exactly happens when I tell Safari to load a webpage?

Most of the magic of APN settings happens at a much lower level and is handled on an OS-wide basis, so Safari itself doesn't particularly need to concern itself with these settings.
The HTTP proxy and port are an exception to this - even though the HTTP proxy settings are included within the APN settings they are used by HTTP clients (such as Safari) as a proxy to use for all HTTP requests.  When loading a web page in your browser it will consult its HTTP proxy setting to determine whether it should directly connect to a server or go via a proxy.
The intention behind offering this is to allow web access to restricted mobile networks that do not allow direct HTTP communication except through the provider's HTTP proxy.  Such setups are comparatively rare these days.

Why do I have to enter the proxy server a second time in Firefox? Shouldn't my computer traffic be transparently sent through my phone's mobile internet, exactly the same as Mobile Safari?

Proxy settings are used by the HTTP client (eg, a web browser).  Most operating systems including your phone will communicate a set of default proxy settings to other compliant HTTP clients that run on the same operating system but when tethering you're crossing over to another separate system and the proxy settings would need to be set up there separately.

I never have to enter any proxy settings into Firefox when I'm using normal tethering with my AT&T mobile internet plan. What makes Speakout so different?

Different providers have different requirements.  Many providers these days run everything through a transparent proxy at their end so you don't need to set up proxy settings in your client software.  It sounds like this provider doesn't do that.
Providers don't need to use proxies at all, but proxies can help them with various things like modifying websites for your device, calculating/indicating whether you're accessing sites within a "free"/"unmetered" zone, blocking access to certain sites, etc.


text:
Q: Oracle SQL - Table created cannot be seen I have never ever worked with Oracle before so please stay with me :)
I just want to do something simple : create a database and then create a table.
I am using oracle 18c version.
Ok so I have run the database configuration tool and my DB DB18c was successfully created. I then opened SQL Developer and created a new connection to this DB called localDB.
I created a new user RTT for this connection with admin privileges for everything.
Now I want to create a table calling a command; I created a file CreateAll.bat which contains the cmd:
sqlplus %USER%/%PWD%@%DB_NAME% @./tables/ulds.Table.sql
spool %LOG_FILE%

When I run it, I pass as arguments of my command the username/pwd I created and for the DB_NAME I enter DB18c.
SQL*Plus: Release 18.0.0.0.0 - Production on Thu Feb 21 09:15:30 2019
Version 18.3.0.0.0

Copyright (c) 1982, 2018, Oracle.  All rights reserved.

Connected to:
Oracle Database 18c Enterprise Edition Release 18.0.0.0.0 - Production
Version 18.3.0.0.0

PL/SQL procedure successfully completed.

I go back to SQL developer and refresh the tables under my user RTT however there is no table at all.
So my command is successfully completed but I dont know where my table was created? There is no filter apply to my Tables.
I dont know if I need to specify my connection name (localDB) somewhere in my command?
Below are the details extracted from the tnsnames.ora
LISTENER_DB18C =
  (ADDRESS = (PROTOCOL = TCP)(HOST = MCMELM01.eur.ad.sag)(PORT = 1525))

DB18C =
  (DESCRIPTION =
    (ADDRESS = (PROTOCOL = TCP)(HOST = MCMELM01.eur.ad.sag)(PORT = 1525))
    (CONNECT_DATA =
      (SERVER = DEDICATED)
      (SERVICE_NAME = db18c)
    )
  )


text:
Q: Pythonic way of observing a variable in multithreading? Imagine having the two threads observeT and upT. observeT observes the value of an instance attribute (instance.a) and should 'alert' (print a note in this example) if its value is 7. Then there's the thread upT, which increases the value of the instance attribute by 1 at a time (instance.a += 1).
However, due to the randomly chosen thread to continue with Python's Lock we can't make sure that the observer thread (observeT) catches the moment when the value of instance.a was increased to 7.
How do I make sure that the observer is called every time after upT releases to lock? Note that it is important to keep the threads upT and observeT split.
Please see the following code for more details:
from threading import Lock, Thread

class MyClass():
    a: int

    def __new__(cls):
        instance = super().__new__(cls)
        instance.a = 0
        return instance

instance = MyClass()
lock = Lock()

def up():
    for i in range(100000):
        with lock:
            instance.a += 1

def observe():
    while True:
        with lock:
            a = instance.a
            if a == 7:
                print("This is 7!")
            if instance.a == 100000:
                break

observeT = Thread(target=observe)
upT = Thread(target=up)

observeT.start()
upT.start()

upT.join()
observeT.join()

Thank you for your help!

A: Is this what you're looking for?
from threading import Thread, Lock, Condition

class MyClass:
    def __init__(self, a_lock):
        self.cond = Condition(a_lock)
        self.canproceed = False
        self.a = 0

    def __setattr__(self, key, value):
        super().__setattr__(key, value)
        if key == 'a':
            if value == 7 or value == 100000:
                self.cond.notify()
                if value == 7:
                    while not self.canproceed:
                        self.cond.wait()

lock = Lock()
instance = MyClass(lock)

def up():
    for i in range(100000):
        with lock:
            instance.a += 1

def observe():
    with instance.cond:
        while instance.a != 7:
            instance.cond.wait()
        print("This is 7!")
        instance.canproceed = True
        instance.cond.notify()
        while instance.a != 100000:
            instance.cond.wait()

observeT = Thread(target=observe)
upT = Thread(target=up)

observeT.start()
upT.start()

upT.join()
observeT.join()

Output:
This is 7!


text:
Q: How to navigate vehicle icon for current location using google map SDK in swift? I'm calling direction API to draw the route and trying to move the current location marker icon as user moves the location, But I m facing following problems while implementation.

*

*while moving the icon, It appears like icon got tilt.

*It doesn't display the actual user position on the route, Icon appears like it is traveling on the side of route.

*My location icon (blue icon) on google map continuously changes its position.

func locationManager(_ manager: CLLocationManager, didUpdateHeading newHeading: CLHeading) {
    let direction = newHeading.trueHeading
        lastDriverAngleFromNorth = direction
        self.sourceMarker?.rotation = (lastDriverAngleFromNorth - mapBearing) - bearingValue

        DispatchQueue.main.async {
            CATransaction.begin()
            CATransaction.setValue(2, forKey: kCATransactionAnimationDuration)
                self.gmsmapView?.animate(toBearing: newHeading.magneticHeading)
                    CATransaction.commit()
    }
}

func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    if let lastLocation = locations.last {

        self.currentLocation = lastLocation
            let zoom = self.gmsmapView?.camera.zoom ?? 20.0
            zoomLevel = zoom
            let destination = CLLocation.init(latitude: viewModel.marker.location[0], longitude: viewModel.marker.location[1])
            let bearing = getBearingBetweenTwoPoints(point1: lastLocation.coordinate, point2: destination.coordinate)
            self.cameraMoveToLocation(toLocation: lastLocation, zoom:zoom, bearing: bearing)
    }
}

func mapView(_ mapView: GMSMapView, didChange position: GMSCameraPosition) {
    mapBearing  = position.bearing
    if let coordinate = self.currentLocation?.coordinate{
            self.rerouteCalculation(currentLocation:coordinate)
    }

    self.sourceMarker?.rotation = (lastDriverAngleFromNorth - mapBearing) - bearingValue
}

func cameraMoveToLocation(toLocation: CLLocation, zoom : Float, bearing : Double) {
    self.gmsmapView?.animate(toLocation: toLocation.coordinate)
    self.sourceMarker?.position = toLocation.coordinate
}

Can anyone please help me, I'm stuck here.

A: Make sure that you choose the correct location accuracy for your needs.
CCLocationAccuracy offers the following options:

*

*kCLLocationAccuracyBestForNavigation:  <= You should use this when the device is plugged to a power source
The highest possible accuracy that uses additional sensor data to
facilitate navigation apps.

*kCLLocationAccuracyBest: <= You should use this when the device runs on battery
The best level of accuracy available.

*kCLLocationAccuracyNearestTenMeters: Accurate
to within ten meters of the desired target.

*kCLLocationAccuracyHundredMeters: Accurate to
within one hundred meters.

*kCLLocationAccuracyKilometer: Accurate to the
nearest kilometer.

*kCLLocationAccuracyThreeKilometers: Accurate
to the nearest three kilometers.


text:
Q: How to set node environment variables during cloud provisioning -terraform? I am using react as frontend and node js as backend an I performing cloud provisioning, a new ec2 instance using terraform. I haven't started to write the terraform script yet.
But I am writing bash script in the user data value to execute on the new instance created. I am writing this userdata attribute of terraform ,just that I can know whether my flow is right or wrong.
And in here , I feel the flow is good correct me if I am wrong .
Note 1: This provision happens with a single click on frontend by admin and a new instance is created with the front end and backend along with the new environment variables , ( because here Paypal client ID and google auth key is remaining unique for each instance so how do I set those environment variables dynamically )
Note 2: Since I am having my backend as node js, I have the form data {google auth client ID , Paypal Cliend ID} there which I receive by the requested user submitted on the frontend, After admin accepts the request all this provisioning should happen automatically .
And upon that button click by admin, I am calling the terraform script in the backend node js to spin up a new instance , there in the userdata attribute of terraform I am using the following bash script . How do I set the form data values {google auth client ID , Paypal Cliend ID} in my bash script .
So what is the method which can set these node js environment variables at time of cloud provisioning?
this terraform/main.tf will be called by node js so how can node js set the environment variables of frontend and backend of the new instance created
terraform /main.tf
resource "aws_instance" "default" {
  ami                    = var.ami-id
  iam_instance_profile   = var.iam-instance-profile
  instance_type          = var.instance-type
  key_name               = var.key-pair
  private_ip             = var.private-ip
  subnet_id              = var.subnet-id
  vpc_security_group_ids = var.vpc-security-group-ids

  user_data = <<EOF
sudo su -
yum install updates -y
yum install mysql -y
yum install nginx -y
sudo service nginx start
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.34.0/install.sh | bash
. ~/.nvm/nvm.sh
nvm install node
mkdir cd /var/apps
cd /var/apps
yum install git -y
git clone https://username:password@github.com/username/frontend.git
git clone https://username:password@github.com/username/backend.git
cd frontend && npm install
//I want to set some node env variables for my front end here
//like NODE.env.PAYPAL_CLIENT_ID='0000aaaaa' NODE.env.GOOGLE_CLIENT_ID='12321ewre'
npm run build
cd ..
cd backend && npm install
//I want to set some node env variables for my backend here
//like NODE.env.PAYPAL_CLIENT_ID='0000aaaaa' NODE.env.GOOGLE_CLIENT_ID='12321ewre'
npm start
rm -r /etc/nginx/nginx.conf
cp backend/nginx/config/nginx.conf /etc/nginx/nginx.conf
sudo service nginx restart
EOF

  tags = {
    Name = var.name
  }
}

NOTE : I do have a .env.production and .env.development files, but I don't know how to overwrite them with values from node js to here


text:
Q: do not hide bootstrap tooltip while user focus on tooltip content I have implemented bootstrap tooltip using hover in my application. When user move to the tooltip content  tooltip is hiding. Can anybody suggest  should not hide tooltip while user focusing on tooltip content
Hover over me

If user focus or move tooltip content it is hiding . How to avoid this
Thanks

A: If I understand your issue correctly, the desired behaviour of the tooltip is inverted. So that when you are not hovering on the tooltip it is actually showing? Is that what you are seeing?
I have created a JSFiddle example here... https://jsfiddle.net/fatchild/4zng2hmL/6/
  Hover over me

It may be best to share your code, so we can understand the issue better and help you more effectively.
Edit:
Incase you haven't referenced the documentation for bootstrap tooltips, here is a link... https://getbootstrap.com/docs/4.0/components/tooltips/


text:
Q: Base/Derived template class types I have a template class that is built around a std::vector.  It looks like...
template <class T>
class Vector {
public:
    std::vector<T> vec;

    // Constructors...
    // Operator overloads...
    // Methods...
    // etc.
};

I want to create a derived template class, ComplexVector that will require the data type to be std::complex<T>, and of course I want to reuse the methods, operator overloads, etc., that I created in class Vector.
The problem is that it seems like there are two ways of doing this.
1) Force the declaration of std::complex<T> as the template type.
ComplexVector< std::complex<float> > myVec;

2) Declare ComplexVector with just the the scalar type, but then pass the std::complex type to the Vector constructor.
ComplexVector<float> myVec;
// Constructor
ComplexVector<T>::ComplexVector() : Vector< std::complex<T> >

Option 1 is far simpler in terms of developing the software but it is ugly for the user, while option 2 is a lot nicer for the user.  I would like to do option #2, but I'm worried about how it will work out.
If I pass std::vector<T> to the base class' constructor, will that only change what the constructor does, or will the entire template go from type T to std::complex< T >?
If it doesn't all convert to std::complex<T>, does that mean that I would have to overload all of the methods that are in Vector?

A: Templated typedef
If you don't really want to have specialization, you can simply use a templated typedef like so:
template <typename T>
using ComplexVector = Vector<std::complex<T>>;

Users could then use ComplexVector<float> and it would properly represent a Vector<std::complex<T>>.
This is a very simple solution which doesn't quite fit your needs. Take a look at the following solutions for your specific problem.
Templated inheritence
If your goal is to only change specific methods when T is std::complex<U>, you have to inherit from Vector like so:
template <typename T>
class Vector
{
    public:
    bool is_complex() { return false; }
};

template <typename U>
class ComplexVector : Vector<std::complex<U>>
{
  public:
    bool is_complex() { return true; }
};

This also allows you to add methods only available to complex-based Vectors.
Adding a method for ComplexVector only
If you want to be able to "enhance" ComplexVector, you can do it like so:
#include <iostream>
#include <complex>

template <typename T>
class Vector
{
  public:
    bool is_complex() { return false; }
};

template <typename U>
class ComplexVector : Vector<std::complex<U>>
{
  public:
    bool is_complex() { return true; }
    bool only_for_complex() { return true; } // Only in ComplexVector
};

int main() {
  Vector<float> float_vec;
  ComplexVector<float> complex_vec;

  std::cout << "Is float_vec complex? " << float_vec.is_complex() << "\n";
  std::cout << "Is complex_vec complex? " << complex_vec.is_complex() << "\n";

  // The following line doesn't compile
  // std::cout << "Is only_for_complex method in float_vec? " << float_vec.only_for_complex() << "\n";
  std::cout << "Is only_for_complex method in complex_vec? " << complex_vec.only_for_complex() << "\n";

  return 0;
}

Working demo here
Using a small type trait to check the type
Using some templating, we can create a small helper to determine whether a given type is a ComplexVector or not. This could come in handy if you want to call the specific methods safely in a template heavy environment:
// For any type T, value is false.
template <typename T>
struct is_complex_vector
{
    static const bool value = false;
};

// We specialize the struct so that, for any type U,
// passing ComplexVector<U> makes value true
template <>
template <typename U>
struct is_complex_vector<ComplexVector<U>>
{
    static const bool value = true;
};

is_complex_vector<typeof(float_vec)>::value; // is false
is_complex_vector<typeof(complex_vec)>::value; // is true

Here is another small demo to demonstrate this behavior in practice
value will be determined at compile. This could allow you to use some SFINAE tricks in order to better control the flow of your program. (Or you can use the constexpr if if you are using C++17.)

A: I think you're confused by using the name T twice. Look at this this way:
template<typename T>
class Vector
{ ... }

template<typename U>
class ComplexVector : public Vector<std::complex<U>>
{ ... }

ComplexVector<float>; // U = float, T = std::complex<float>

A: In comments on the original q., @JimClay clarifies the use case: he wants to extend the complex vector with methods like fft (Fast Fourier Transform).
It is certainly possible to derive from vector<T> to create a new class, say, ComplexVector<T> and add a method like fft, but I don't recommend it. Detailed reasons below. A better alternative is to add a standalone function like
template<typename T>
vector<complex<T>> fft(const vector<complex<T>>&);

(that's with using namespace std for readability).
Here are the reasons not to use a derived template class:

*

*Suppose you want to use a library function that returns a vector<complex<T>> v. If you've rolled your own ComplexVector<T>, you'll need to take v and convert it to a ComplexVector<T> before calling fft. This can be done efficiently, but it requires users to be careful with move construction.

*It gets worse. Suppose you and I are in the same situation, and both roll our own classes, MyComplexVector<T> and YourComplexVector<T>. Then users who want to use our libraries together will need to take the MyComplexVector<T>, convert it to a vector<T>, and then convert to a YourComplexVector<T> before calling my library. [Though the first conversion will happen implicitly in most cases.]

*Users will need to do work to familiarise themselves with the semantics of ComplexVector<T>, whereas every C++ programmer knows how vector<T> behaves.

I'm old enough to have used C++ before the STL, and using libraries together was not fun! Indeed, library interoperability was one of the main reasons for the introduction of the standard string, vector, etc..
Note that if you want to implement an efficient in-place fft, you'll want a rvalue-reference version:
template<typename T>
vector<complex<T>> fft(vector<complex<T>>&&);

A: ComplexVector<std::complex<T> > is redundant (you already said it was a complex vector right ?).
Using the general convention you will arrive at:
class ComplexVector< T > : public Vector< std::complex<T> > {
public:
  typedef std::complex<T> type;//for convenience, etc.
  //...
}

Adding specialization of Vector(as some suggested), while also inheriting is not directly possible and a (perhaps difficult) refactor is needed involving Vector<T>- but basicly it involves moving most/all parts to a new common base class. It might be a good idea if you are already doing work on Vector<T> for example.


text:
Q: React Router useParams hook returning empty object I'm having an issue with React Router not getting params using the useParams hook. When going to the route /view/12345 (browser path includes basename /pending-nominations/view/12345) the console.log() logs an empty object here {} where it should be displaying the id eg. {id: 12345}
const SingleRecognition = (props) => {
    let params = useParams();
    console.log("SingleRecognition -> params", params)

    return (
        <div>
            id:
        </div>
    );
}

function App() {
    return (
        <Provider store={store}>
            <ThemeProvider theme={theme}>
            <Router basename="/pending-nominations">
                <PageNav/>
                <Switch>
                    <Route path="/history">
                        <History/>
                    </Route>
                    <Router path="/view/:id">
                        <SingleRecognition/>
                    </Router>
                    <Route path="/">
                        <PendingRecognitions/>
                    </Route>
                </Switch>
            </Router>
            </ThemeProvider>
        </Provider>
    );
}

Looking at the example https://reacttraining.com/react-router/web/api/Hooks/useparams this should work.

A: I think you have problem because you used Router instead of Route.


text:
Q: Do "three consecutive days" mean the same as "three straight days"? Are the two phrases equivalent?
Example sentences:

Mary had stayed in this hotel for five consecutive days.
Mary had stayed in this hotel for five straight days.

A: No, there is no difference between "consecutive" and "straight" in this context.
According to the Oxford Dictionary, consecutive means "Following each other continuously.", and straight means "In continuous succession." They are listed as synonyms of one another.
Edit: I would use "consecutive" for clarity, see @Davo's comment

A: I agree with Davo's comment to SirChregeli.
straight refers to a stretch of time as uninterrupted or unrelieved (e.g. by a respite) or unvaried (e.g. in routine), whereas  consecutive means one after the other.

She had to attend three consecutive two-hour meetings. She was going to be tied up for six straight hours.

A: I think we have got seriously off track as a result of Davo's comment.
The original answer quoted the OED. That is reliable authority. "Five consecutive days" and "five straight days" have the same denotative meaning.
"She stayed at that hotel for five consecutive days" and "she stayed at that hotel for five straight days" denote the same thing, and neither implies that she never left the hotel's premises throughout those five days.
"She stayed inside that hotel for five consecutive days" and "she stayed inside that hotel for five straight days" denote the same thing, and both explicitly state that she immured herself in a particular place for the same duration.
So in terms of teaching someone English, the denotative meanings of "five consecutive days" and "five straight days" are the same. The potential ambiguity arises from the term "stay in the hotel," which may mean "stay inside the hotel" or "stay at the hotel." So in terms of the nuances of the English language, the phrase "stay in a hotel" may mean one of two things because both "stay" and "in" have fairly broad meanings.
Why then did Davo perceive the ambiguity in one case and not the other? The answer is that, although "consecutive" and "straight" denote the same continuity, they have slightly different connotations, with "consecutive" being invariably neutral and "straight" sometimes implying disapproval or surprise. There is nothing surprising about being a guest at the same hotel for days on end, but it may be surprising to never leave the premises for days on end. To avoid any possibility about whether "stay in the hotel" means "stay at the hotel" or "stay inside the hotel," the key word to fix is the preposition following "stay."


text:
Q: Lotus notes give an error message during calling Crystal Report viewer control 9 OS : window 7 Enterprise Service pack 1 (32 bit)
Lotus notes version : 9.0 (social edition)
Whenever i want to create an object- crystal report viewer control 9 it give me an error message: below is error message that generate by lotus notes

-Already register odbc driver for lotus notes 9.0
May i know how to fix this error?
Here is the fatal stack.
############################################################
### FATAL THREAD 1/12 [ NLNOTES:  10e0:  10e4]
### FP=0x001b8208, PC=0x0887e890, SP=0x001b81c4
### stkbase=001c0000, total stksize=241664, used stksize=32316
### EAX=0x080ebf23, EBX=0x00000000, ECX=0x001b8188, EDX=0x77af70f4
### ESI=0x0887e890, EDI=0x001e071e, CS=0x0000001b, SS=0x00000023
### DS=0x00000023, ES=0x00000023, FS=0x0000003b, GS=0x00000000 Flags=0x00010206
Exception code: c0000005 (ACCESS_VIOLATION)
############################################################
 [ 1] 0x77525f9f USER32.SetPropW+474 (0,80ebf23,1e071e,81)
 [ 2] 0x77524f0e USER32.GetScrollBarInfo+253 (140a4b0,81,0,1b834c)
 [ 3] 0x7751e98a USER32.SendMessageTimeoutW+1329 (1b8324,60,1b87e0,77af6fe0)
 [ 4] 0x77af702e ntdll.KiUserCallbackDispatcher+46 (0,c2d0,0,56000000)
 [ 5] 0x7751ec54 USER32.SendMessageTimeoutW+2043 (0,c2d0,0,56000000)
 [ 6] 0x7751ecaf USER32.CreateWindowExW+51 (0,c2d0,0,56000000)
 [ 7] 0x080ebfd0 crviewer9 (190534,1b87b8,0,56000000)
 [ 8] 0x080fd319 crviewer9.DllUnregisterServer+6942 (fffffffc,1b8838,80fdcc8,1b8838)
 [ 9] 0x080fedb5 crviewer9.DllUnregisterServer+13754 (887e8c0,fffffffc,0,83658d8)
@[10] 0x5a8d6076 nnotesws.CEditorOLEContainedObj::DoVerb+454 (23053c,fffffffc,0,508)
@[11] 0x59f7a777 nnotesws.DocOLEActivateInPlaceWhenVisible@4+439 (8b3c7a8)
@[12] 0x59f3f94e nnotesws.DocOLEAsyncEvent@12+846 (8335018,508,0)
@[13] 0x59edf24b nnotesws.@DocWindowsMessage@24+19531 (508,0,1b8c7c,1b9120,0,0)
@[14] 0x59ee4699 nnotesws.EditInstanceMessage@24+1161 (8335018,23053c,4f8,508,0,0)
@[15] 0x59ee38a3 nnotesws.CEditSubprogram::SubMessageProc+323 (8352418,4f8,508,0,0,0)
@[16] 0x59eb515d nnotesws.MainWndProc@16+8685 (23053c,4f8,508,0)
 [17] 0x7752c4e7 USER32.gapfnScSendMessage+463 (59eb2f70,23053c,4f8,508)
 [18] 0x7752c5e7 USER32.gapfnScSendMessage+719 (0,59eb2f70,23053c,4f8)
 [19] 0x7752cc19 USER32.gapfnScSendMessage+2305 (59eb2f70,0,1b9274,59f50b3a)
 [20] 0x7752cc70 USER32.DispatchMessageW+15 (1b9250,775253ba,601ba,59eb0000)
@[21] 0x59f50b3a nnotesws.NEMMainLoop@4+1194 (10f13b0)
@[22] 0x010f1f80 NLNOTES.WinMain@16+3024 (10f0000,0,1,0)
@[23] 0x010f2f95 NLNOTES.__tmainCRTStartup+336 (7ffdb000,1bfac8,77b137eb,7ffdb000)
 [24] 0x75e9ed5c KERNEL32.BaseThreadInitThunk+18 (7ffdb000,77a09f0b,0,0)
 [25] 0x77b137eb ntdll.RtlInitializeExceptionChain+239 (10f30d8,7ffdb000,0,0)
 [26] 0x77b137be ntdll.RtlInitializeExceptionChain+194 (10f30d8,7ffdb000,0,0)

A: Check your PATH environment variable in Windows. And old rule of thumb is to have the Lotus Notes program directory located amongst the first 128 characters of the PATH variable. On my machine I specify my Notes program directory as the first "normal" path after all the Windows-variables like %SystemRoot%\system32 etc.
Finally check that the same goes for the directory in Crystal Reports holding any DLLs like crviewer9.dll.
If that doesn't work, I would use Dependency Walker and run that on crviewer9.dll to see if any obvious DLLs are missing.
EDIT: Just scanning the net for some of the files you mention, seems to suggest that there is problem with the Visual Studio 2010 redistributable package. Look down at the comments here.


text:
Q: Pusher/Laravel Echo stops working on Ionic 3.9.2 intermittently Normally it works.
When I create an appointment on the Laravel webapp, the Ionic mobile app's listview updates in real-time with the new appointment (thru Laravel Echo and Pusher).
...
@Injectable()
export class UpdateService {
  private echoStarted: boolean;
  private channel: string = null;
  private dataChanged = new Subject<void>();
  public dataChanged$ = this.dataChanged.asObservable();

  constructor(private auth: AuthService) {
    window.Pusher = require("pusher-js");
    if (this.auth.isLoggedIn()) {
      this.startEcho();
    }
    this.auth.authenticated$.subscribe(status => {
      if (status) {
          if (!this.echoStarted) {
            this.startEcho();
          }
        } else {
          this.stopEcho();
        }
    });
  }
...

But at some point the real-time listener just stops completely and continues to not work until I hard-refresh the mobile page or reset the mobile app. In other words, when I create a new appointment, the mobile app listview just sits there with no automatic update.
This problem seems to be reproduced when switching to another mobile app then coming back, or when putting the mobile app in background mode (pressing phone power button then coming back in). Happens on both Android and iOS.
This problem does not occur with the real-time updates on the webapp's front-end Pusher implementation.
So I'm suspecting this is a mobile app code issue, and hopefully not a fundamental stability problem with Ionic and Pusher.
Maybe something to do with the OnResume trigger where the real-time listener/process is getting doubled up and failing? Or maybe the listener/process fails as it was receiving some new data but going into background mode? The intermittent failure is what makes this issue thorny to think about.
Wondering if you've experienced a similar issue. Any illumination is greatly appreciated.


text:
Q: Why do the values in the array suddenly disappear? Swift I am new to Swift and I am wondering why the array is empty at the end of the function at the print("array printed2: \(newArr)") line, when at the first print statement print("array printed1: \(newArr)") it is filled with data.
Does anyone have any corrections or suggestions on how to make the data in the array stay?
Thanks in advance, the code for the function is below.
func testRdArr(){

         var newArr=[Establishment]()
          print("Downloading club data...")
           let db = Firestore.firestore()

               db.collection("clubs").getDocuments() { (querySnapshot, err) in
                   if let err = err {
                       print("Error getting documents: \(err)")
                   } else {
                       for document in querySnapshot!.documents {
                          let data = document.data()

                         let name = data["Name"] as? String ?? "Name Unknown"
                         let description = data["description"] as? String ?? "Description Uknown"
                         let imageURL1 = data["imgUrl"] as? String ?? "Image Unknown"
                         let coordX = data["coordX"] as? String ?? "Unknown"
                         let coordY = data["coordY"] as? String ?? "Unknown"
                         let openingTimes=data["openingTimes"] as? [String] ?? ["Unknown"]
                         let weeklyEvents=data["weekly events"] as? [String] ?? ["Unknown"]
                         let postcode=data["postcode"] as? String ?? "Unknown"
                         let id = document.documentID

                        let x = Establishment(name: name, imageURL1: imageURL1, coordX: coordX, coordY: coordY, postcode: postcode, openingTimes: openingTimes, weeklyEvents: weeklyEvents, description: description, type: "club", id: id)

                           newArr.append(x)

                       }
                   }
                //line below prints the populated array
                print("array printed1: \(newArr)")
                print("end of printing array")
               }
           //at this point array becomes empty, why does this happen and how would you suggest
           //fixing it?
           print("array printed2: \(newArr)")

      }

A: The download happens in the background and completes after your print at the bottom of the function. It did not become empty. That line happened before the download was done.
See: Waiting for Asynchronous function call to complete


text:
Q: Why do I need call onChange and onTouch in writeValue when implementing ControlValueAccessor in Angular? I have implemented the following component. It works and behaves as expected. Nevertheless, as the implementation of ControlValueAccessor was new to me, I had to follow a blog without understanding the deeper details of a few sections. So this is a type of "it works but why?!" situation.
@Component({ selector: ..., templateUrl: ..., styleUrls: ...,
  providers: [{ provide: NG_VALUE_ACCESSOR,
                useExisting: forwardRef(() => InputTextComponent),
                multi: true }]
})
export class InputComponent implements ControlValueAccessor {

  constructor() { }
  @Input() info: string;
  onChange: any = () => { }
  onTouch: any = () => { }

  writeValue(input: any): void {
    this.info.value = input;
    // this.onChange(input);
    // this.onTouch();
  }

  registerOnChange(_: any): void { this.onChange = _; }
  registerOnTouched(_: any): void { this.onTouch = _; }

  setDisabledState?(state: boolean): void { }

  onEdit(value: string): void { this.onChange(value); }
}

When I've got it working, I commented out the second and third line of writeValue(...) method and, as far I can tell, nothing broke. Those calls are consistently suggested by other blogs as well, so I'm convinced that it's improper to omit them. However, I don't believe in magic and prefer to have a concrete reason for doing things.
Why is it important to execute the call to onChange(...) and onTouch(...) in writeValue(...)? What will go wrong and under what circumstances can it be expected?
As a side quest, I also tried to comment out the other methods and discovered that I couldn't tell anything going bananas when I removed setDisabledState(...). When can that one be expected to cause problems? Does it really need to be implemented (I've seen version with question mark both before and after the parentheses with parameters like so: setDisabledState?(state: boolean): void { } but also like this: setDisabledState(state: boolean)?: void { }).

A: Read this article that explains the ControlValueAccessor in great details:

*

*Never again be confused when implementing ControlValueAccessor in Angular forms
You usually need to implement ControlValueAcceessor interface on a component if it's supposed to be used as part of an Angular form.

I commented out the second and third line of writeValue(...) method
and, as far I can tell, nothing broke.

This is probably because you're not applying any form directive - formControl or ngModel that links a FormControl to your custom input component. The FormControl uses writeValue method of the InputComponent for communication.
Here is the picture from the article I referenced above:

The writeValue method is used by formControl to set value to the native form control. The registerOnChange method is used by formControl to register a callback that is expected to be triggered every time the native form control is updated. The registerOnTouched method is used to indicate that a user interacted with a control.

Why is it important to execute the call to onChange(...) and
onTouch(...) in writeValue(...)? What will go wrong and under what
circumstances can it be expected?

This is the mechanism by which you custom control that implements ControlValueAcceessor notifies the Angular's FormControl that a value in the input has changed or the user interacted with the control.

...discovered that I couldn't tell anything going bananas when I
removed setDisabledState(...)...Does it really need to be implemented?

As specified in the interface this function is called by the forms API when the control status changes to or from "DISABLED". Depending on the value, it should enable or disable the appropriate DOM element.
You need to implement it if you want to be notified whenever the status of an associated FormControl becomes disabled and then you can perform some custom logic (for example, disable your input component).

A: I don't think the accepted answer answers the most central question in a succinct way:

Why is it important to execute the call to onChange(...) and onTouch(...) in writeValue(...)?

It isn't. You do not need to call onChange in writeValue. It is not the intended usage (see documentation link below).

What will go wrong and under what circumstances can it be expected?

Expect nothing to go wrong. Elaborate answer:
If you were to call onChange from inside writeValue you'll notice:

*

*First onChange call does nothing. That's because onChange callback hasn't been registered (ie registerOnChange not called) when writeValue is first called.

*Later calls to onChange from inside writeValue updates your model (with emitModelToViewChange = false to avoid recursively calling writeValue) with the value you gave it - which you just received - from your model.

In other words, unless you rely on your component to somehow immediately change the value it receives in writeValue, and for it to pass those changes back to your model but only on second and later invocations of writeValue, you're safe to not call onChange from writeValue.
See example in documentation here: https://angular.io/api/forms/ControlValueAccessor


text:
Q: How to move the bootloader (Windows 8) I have two disks in my computer ( a 80GB SSD ) and a normal 250GB (OLD DRIVE). I installed windows on the SSD.
I now want to remove my 250GB drive as its old and slow, but when i remove it windows dont boot up. Error is printed to insert a boot disk (bios error, cant remember exactly what it was, but i think peolpe know what im talking about, else i will find out and update).
I assume its because the bootloader is on this 250GB drive, and wonder how to move it such i can throw out the old disk.

A: Follow these simple steps:

*

*Boot from your Windows 8 install DVD.

*At the initial screen, pick Repair your computer.

*Then Troubleshoot -> Advanced Options and finally Command Prompt.

*At this command prompt, enter: bootrec /RebuildBCD (to rebuild boot configuration)

*and then bootrec /FixBoot  (to write a new boot sector)

A: Remove your unneeded 250 gigabyte drive.  Then, start up a Linux LiveCD or USB containing GParted (or get it here).  GParted is a graphical partition manager that allows you to easily modify partitions.  Use it to mark the "boot" flag as on on your Windows partition in your SSD.
Then, run Startup Repair from your Windows install disc.  It should automatically restore your Windows's boot ability, but if it doesn't, navigate to command prompt and run bootrec /RebuildBCD.  This will create a new Master Boot Record, which tells your computer where to look for the operating system.  Restart your computer without the CD in the tray and enjoy!


text:
Q: JSTree with Datatables I have two columns on a page, with a checkbox jstree on the left and a table using datatables on the right. The table rows and tree are all loaded at startup.
I would like to show a row when the node is selected on the tree and hide the row when its unchecked and I'm using a class for this. I am having problems with looping though all the rows in a datatables and setting a class, so I can filter it. This is the code I'm using below, but its not working. I can't get any id for the table row.
table.rows().iterator( 'row', function ( context, index ) {
                var tableNode = $(this.row(index).node());
                tableNode.removeClass('VisibleRow').removeClass('HiddenRow').addClass('HiddenRow');
            var id = tableNode.id;
            var treeNode = data.instance.get_node(id);

            if(treeNode != undefined){
                var currentId = '#row-' + node.id;
                var rowInTable =  table.row(currentId).node();
                $(rowInTable).removeClass("HiddenRow");
                $(rowInTable).addClass("VisibleRow");
            }

});

Let me know if there are better ways to do this.

A: I believe you can do it with the snippet below. The rows iteration is jQuery based, there is no DataTables-specific logic there.
Also check demo - Fiddle Demo
var $tableRows = $('#yourTableId').find('tr');

$('#yourTreeContainer').on('select_node.jstree', function(e, data) {

    $tableRows.each(function() {
        if (this.id === '#row-' + data.node.id) {
            $(this).removeClass('HiddenRow');
        } else {
            $(this).addClass('HiddenRow');
        }
    });

});

A: I created same with some changes and it works fine, but even with hidden row I don't want datatable showing empty pages. Any advice, please?
this my code
$('#jstree')
  .jstree({
    core: {
      data: treeData
    },
    checkbox: {
      three_state : false, // to avoid that fact that checking a node also check others
      whole_node : false,  // to avoid checking the box just clicking the node
      tie_selection : false // for checking without selecting and selecting without checking
    },
    "plugins" : ["checkbox","conditionalselect"]
  })
  .on("check_node.jstree uncheck_node.jstree", function(e, data) {

   $tableRows.each(function(){

   //$(this).addClass('HiddenRow'); //should not be there

     if( this.id === data.node.id ) {
       if(data.node.state.checked ){
         //alert("removeClass");
         $(this).removeClass('HiddenRow');
       }else{
         //alert("addClass");
         $(this).addClass('HiddenRow');
       };
     }else{

     }
   })
})

This is the link http://jsfiddle.net/cf7tata9/56/#&togetherjs=jqPTfx3gpk


text:
Q: Use MACROS to highlight a cell when any one checkbox is checked (multiple checkboxes, one cell) I'm a real newbie with excel (and coding).  I've figure out, using Conditional Formatting, to highlight one cell if the value of another cell changes (based on a checkbox changing).  What I have are multiple cells with checkboxes (cannot be ActiveX checboxes since MAC users need to be able to run it), if any one of those checkboxes are checked, another cell has to be highlighted.
For example, Cells A1, B1, C1, D1, E1 all have check boxes.  If any one of those are checked, cell F1 needs to be highlighted.  I was able to set it up so that if A1 is checked, then cell G1 says "TRUE" then cell F1 highlights.  When I link all the checkboxes to cell G1 and select only B1 - all cells (A1, C1, D1, E1) are checked AND cell F1 is highlighted.
I need to be able to have one cell highlighted if any one of (or all) A1, B1, C1, D1, and/or E1 is checked.

A: You can have each check box link to its own cell, for example A2, B2, C2, D2, E2. Then use a formula in G1
=COUNTIF(A2:E2,TRUE)

Use G1 as the input for your conditional format. If no box is checked it will be 0, if any box is checked it will be greater than 0.

Edit after comment: If you use hundreds of check boxes in the spreadsheet grid, then you're not using Excel efficiently. Check boxes are form controls, which means they are good for using in forms. In the grid they are best used sparingly, for exactly the issues that you are encountering.
Consider using cell values instead of check boxes. Format the cells with the Marlett font and type an "a" or a "b" to produce a check mark in the cell. Then you can use a Countif($A2:$F2,"a") as the input for your conditional formatting.


text:
Q: SP2013 - Adjust Row Height in List I have a multi-text column in a list. The text in the column can get lengthy causing a large gap between entries. I have attempted following the content in this question: sharepoint collapse list.
However, I could not get the rows to collapse either using the CEWP code or linking the .js file within the jslink property.
I would prefer adjusting the height of the rows, but collapsing the rows is fine too.

A: I wrote a CSR override script that will collapse long text fields, and provides a "show more / show less" link on each one that will allow you to expand the collapsed field so you can see the full text if you want (and then re-collapse it).
MultilineShowMoreLess.js
var DC = DC || {};

DC.multilineOverride = (function () {
    function renderLessAndMoreDivs(ctx) {
        var summaryLength = 75;
        var fullText = ctx.CurrentItem[ctx.CurrentFieldSchema.Name];
        if (fullText.length < summaryLength) {
            return "
" + fullText + "
";
        }
        var shortText = fullText.slice(0, summaryLength) + "...";
        var fullTextDivId = ctx.CurrentFieldSchema.Name + "_" + ctx.CurrentItem.ID + "_FullText";
        var shortTextDivId = ctx.CurrentFieldSchema.Name + "_" + ctx.CurrentItem.ID + "_ShortText";
        var fullTextDiv = "
" + fullText + "
Show less
";
        var shortTextDiv = "
" + shortText + "
Show more
";
        var returnHtml = "
" + fullTextDiv + shortTextDiv + "
";
        return returnHtml;
    }

    function buildShowHideJS(idToHide, idToShow) {
        var jsString = "document.getElementById(\"" + idToHide + "\").setAttribute(\"style\", \"display:none\");";
        jsString += "document.getElementById(\"" + idToShow + "\").setAttribute(\"style\", \"display:block\");";
        jsString += "return false;";
        return jsString;
    }

    return {
        render: function () {
            SPClientTemplates.TemplateManager.RegisterTemplateOverrides({
                Templates: {
                    Fields: {
                        "MultilineTextField_1": {
                            View: renderLessAndMoreDivs,
                        },
                        "MultilineTextField_2": {
                            View: renderLessAndMoreDivs,
                        }
                    },
                },
            });
        }
    }
})();
RegisterModuleInit(SPClientTemplates.Utility.ReplaceUrlTokens("~site/SiteAssets/Scripts/MultiLineShowMoreLess.js"), DC.multilineOverride.render);
DC.multilineOverride.render();

Things you would need to change:
Obviously you will need to provide the internal names of the fields as they exist in your list.
Also, make sure the URL in the RegisterModuleInit line matches where you put the JavaScript file.
And lastly, you can control exactly how much gets shown in the collapsed view by adjusting the summaryLength variable to set exactly how many characters you want to see.

NB: It is designed to work with plain text.  If you are using rich text fields you will probably need to add some code to deal with the HTML you'll get in the line
var fullText = ctx.CurrentItem[ctx.CurrentFieldSchema.Name];

because once you slice that down, you'll probably lose some end tags.

A: You can use below mention CSS to fix the height of all multi line textbox whether it is in list view or in quick edit view.
.ms-rtestate-field {
    max-height: 100px;
    overflow: auto;
    width: 250px;
    word-wrap: break-word;
}

Change the height & width as per your needs.
Apply this CSS in SharePoint master page if you want to to work for all multiline contents. If yo want it for a single page than add it to CEWP on specific page.
Happy Coding..... :)