text:
Q: \hfill inside a list does not work properly. What's going on? \documentclass[a4paper,12pt]{article}
\begin{document}
\begin{enumerate}
\item \begin{enumerate}
    \item
        \begin{enumerate}
         \item Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt \hfill [Lorem ipsum]
         \item I'm going to relate a time-traveling joke, but you didn't appreciate it. \hfill [Lorem ipsum]
        \end{enumerate}
    \end{enumerate}
\end{enumerate}
\end{document}

gives the following output:

Why is the second [Lorem ipsum] split up even though the item has less wording?

A: If you remove the misplaced first \item, it works as expected for me.
\documentclass[a4paper,12pt]{article}
\begin{document}
  \begin{enumerate}
    \item
      \begin{enumerate}
        \item Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt \hfill [Lorem ipsum]
        \item I'm going to relate a time-traveling joke, but you didn't appreciate it. \hfill [Lorem ipsum]
      \end{enumerate}
  \end{enumerate}
\end{document}

EDIT If a higher nesting is intended, I cite egreg's comment:

[...] TeX will prefer a paragraph where the last but one line is not hyphenated. The \hfill makes it possible.

\documentclass[a4paper,12pt]{article}
\begin{document}
  \begin{enumerate}
    \item
      \begin{enumerate}
        \item
        \begin{enumerate}
          \item Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt \hfill [Lorem ipsum]
          \item I'm going to relate a time-traveling joke, but you didn't appreciate it. \hfill [Lorem~ipsum]
        \end{enumerate}
      \end{enumerate}
  \end{enumerate}
\end{document}

Alternatively have a look at \linepenalty.

A: From the explanation by @Ulrike Fischer---        https://tex.stackexchange.com/a/16333/197451
Output with \newcommand\quelle

Output without \newcommand\quelle

Also, the first\item should be giving you an error since the enumerate environment has not \begin--probably you have edited out the first item before capturing your screenshot of the output--is that right?
    \documentclass[a4paper,12pt]{article}
    \begin{document}
      \newcommand\quelle[1]{{%
      \unskip\nobreak\hfil\penalty50
      \hskip2em\hbox{}\nobreak\hfil\textbf{#1}%
      \parfillskip=0pt \finalhyphendemerits=0 \par}}
    \begin{enumerate}
        \item fg \hfill [lorem ipsum]
            \begin{enumerate}
             \item Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed
              \quelle {[Lorem ipsum]}
             \item I'm going to relate a time-traveling joke, but you didn't
             appreciate
             it. \hfill [Lorem ipsum]
            \end{enumerate}
        \end{enumerate}
    \end{document}


text:
Q: AdControl An unexpected error occurred during call to the ad source (Name: CNTX).} i use Windows Phone 8.1 silverlight and i would insert an AdControl into project.
Receive errors:
An unexpected error occurred during call to the ad source (Name: CNTX).}
this is my xaml
<Grid x:Name="LayoutRoot" Background="Transparent">
    <Grid.RowDefinitions>
        <RowDefinition Height="Auto"/>
        <RowDefinition Height="*"/>
    </Grid.RowDefinitions>

    <Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
        <Button Click="Button_Click" Content="Open New page" />
    </Grid>

    <Grid x:Name="advertising" Grid.Row="1" VerticalAlignment="Bottom" Width="480" Height="80">
        <UI:AdControl Grid.Row="1" ApplicationId="test_client" AdUnitId="Image480_80" Height="80" Name="AdControlMain" Width="480" IsAutoCollapseEnabled="True" Margin="0,-2" AdRefreshed="AdControlMain_AdRefreshed" ErrorOccurred="AdControlMain_ErrorOccurred" />

    </Grid>

</Grid>

redpajama_set_name: RedPajamaStackExchange


text:
Q: Experience writing C-code for PCF8575 I/O-Expander on Raspberry Pi Has anyone attempted to write a C/C++ routine to expand the I/O on a Raspberry PI using the PCF8575 I/O-Expander from SparkFun?
I can find a lot of Python samples, which don't help me a lot since I need to develop in C.
I have everything configured right, and I know that my I2C device responds. For example I can do this from the command line:
i2cset -y 1 0x20 0xff 0xff
i2cset -y 1 0x20 0x00 0x00

and all 16 Outputs (in this case) will turn on/off
I also know I could simply do the system(); function from within my C-code,
but that is not the way I want to go about this, as I'd like to be able to address single Bits in that word and later do toggle modes, etc etc.
I took a look at the Arduino implementation and their sample code, which is (of course) all based on the Atmel processors and modifying all the libraries and files to be compliant with the ARM processor might bring me way beyond the deadline of my project. (It is a simple project to show the difference between populating regular I/O on the Pi, vs using I/O expander via I2C to save I/Os) I'm also writing on a tutorial for my personal reference and for anyone who is interested. But I'm stuck at this point.
Please help

A: With regard to addressing individual bits and changing modes: you can't. The PCF8575 is a very simple I/O expander, and only supports two operations:

*

*Writing two bytes to set the state of all pins.

*Reading two bytes to read the state of all pins. Pins are put into a quasi-input state (with pullup) if they're set high.
There is no way to change the state of one pin without writing to all other pins in the process, and there is no explicit input state for pins. If you want fancy features like that, you'll need a fancier I/O expander. :)

Now, that all being said, there is a way to read and write to I2C devices, such as this I/O expander, without shelling out to the i2cset command. Specifically, if you're working in C, you can read and write to the I2C device node to communicate with a device. Documentation on how to do this is available as part of the Linux kernel, at:
https://www.kernel.org/doc/Documentation/i2c/dev-interface


text:
Q: Add more elements in php array I have an Array like this
        $array1 = [
            0 => [
                'category_name' => 'Example 1'
            ],
            1 => [
                'category_name' => 'Example 2'
            ],
            2 => [
                'category_name' => 'Example 3'
            ],
        ];

I want to add more keys in each index of this array and finally I want to get output like this
        $array2 = [
            0 => [
                'import_id' => 10,
                'country_id' => 1,
                'category_name' => 'Example 1'
            ],
            1 => [
                'import_id' => 10,
                'country_id' => 1,
                'category_name' => 'Example 2'
            ],
            2 => [
                'import_id' => 10,
                'country_id' => 1,
                'category_name' => 'Example 3'
            ],
        ];

But I don't want to use any loop to do this. is it possible ??

A: One long way without using a loop :)
    $array2 = array_fill(0, count($array1), ['import_id' => 10, 'country_id' => 1]);
    $array2 = array_replace_recursive($array2, $array1);

demo


text:
Q: How can I show only the city name in a geo autocomplete input after a place is selected? Using jQuery Geocoding and Places Autocomplete Plugin is there a way to only show city name (not state or country) when I select a result from the suggestions list?

A: Yes, it's possible to only show a portion of the geocoded result after it's chosen from the autocomplete dropdown.
What you need to do is add a listener for the place_changed event, then trigger a "blur" and set whatever content you want the input box to display.
This should get you started:
function init(){
    var autocomplete = new google.maps.places.Autocomplete(
        // make sure we pass the HTML element and not the jquery object
        $('#my-input-field')[0]
        ,{
            types: ['geocode']
        }
    );

    // When the user selects an address from the dropdown,
    google.maps.event.addListener(autocomplete, 'place_changed', function() {
        var parts = [],
            city_name = '';

        // convert the address to something more usable
        $.each(place.address_components, function (i, value) {
            parts[value.types[0]] = value;
        });
        city_name = parts.locality ? parts.locality.long_name : '';

        $('#my-input-field')
            .one('blur', function(){
                // and here's where we set the input to whatever value we'd like
                $(this).val(city_name);
            })
            .trigger('blur');
    });
}


text:
Q: Cannot create items in database of keystone.js I created a keystone.js folder using Yeoman. In file keystone.js, I add a some code right before keystone.start() to add an new item and list all current items like this:
var newPost = new Post.model({
    title: 'New Post'
});

newPost.save(function(err) {
    // post has been saved
});

Post.model.find(function (err, posts) {
  if (err) return console.error(err);
  console.log(posts);
})
keystone.start();

However, the posts in Post.model.find is an empty array, which means there was no item added. Can anyone help me out?
Thank you in advance.

A: newPost.save method is async execute.
As in your code, your are query Posts before newPost was successfully saved.
newPost.save(function(err) {
    Post.model.find(function (err, posts) {
        if (err) return console.error(err);
        console.log(posts);
        keystone.start();
    });
});

You code should write like that.


text:
Q: Compare 2 Excel Files and output the difference only (Powershell) I am trying to compare 2 XLXS and I would like to output the difference only. Can this be done with Compare-Object?
I currently am using this script which works, but it does not capture what I exactly need:
#IMPORT PS EXCEL MODULE
import-module psexcel
#FILE TO BE COMPARED VARIABLES
$file1 = Import-XLSX C:\CurrentFile.xlsx
$file2 = Import-XLSX C:\PreviousFile.xlsx

#FILTER TO GET DATA ONLY FROM THE REFERENCE FILE ONLY
filter leftside{
param(
        [Parameter(Position=0, Mandatory=$true,ValueFromPipeline = $true)]
        [ValidateNotNullOrEmpty()]
        [PSCustomObject]
        $obj
    )

    $obj|?{$_.sideindicator -eq '<='}
}

#PROPERTY VARIABLE
$property = "Name" , "UserPrincipalName" , "NickName" , "Age" , "Sex"

#COMPARISON PROPER
$Comparison = Compare-Object -referenceobject $file1 -differenceobject $file2 -SyncWindow ($file1.Length / 2) -property $property | leftside

Here is how the sample files look like:
PreviousFile:

Name        UserPrincipalName   NickName    Age Sex
UserUser 1  User1@user.com      User1       20  M
UserUser 2  User2@old.com       User2       20  M
UserUser 3  User3@old.com       User3       20  M
UserUser 4  User4@old.com       User90      20  M
UserUser 5  User5@old.com       User91      20  M

CurrentFile:

Name        UserPrincipalName   NickName    Age Sex
UserUser 1  User1@user.com      User1       20  M
UserUser 2  User2@user.com      User2       20  M
UserUser 3  User3@user.com      User3       20  M
UserUser 4  User4@user.com      User4       20  M
UserUser 5  User5@user.com      User5       20  M

DIfferences:All items under UserPrincipalName except User1@user.com
UnderNickname User90-User4 , User91-User5
Output with the current script:
Output shows the complete info on rows that has differences.
Name        UserPrincipalName   NickName    Age Sex
UserUser 2  User2@user.com      User2       20  M
UserUser 3  User3@user.com      User3       20  M
UserUser 4  User4@user.com      User4       20  M
UserUser 5  User5@user.com      User5       20  M
UserUser 6  User6@user.com      User6       20  M

Expected output:
Name        UserPrincipalName   NickName    Age Sex
UserUser 1
UserUser 2  User2@user.com
UserUser 3  User3@user.com
UserUser 4  User4@user.com
UserUser 5  User5@user.com      User5
UserUser 6  User6@user.com      User6

I would like the script to output my identifier all the time, in this case "Name" I also would want it to output the Difference only. If any changes are found between old and current file, display the current file that has found differences only.
Is there a way to output it this way?
Any help, any assistance, will be really appreciated. Thank you!

After further analysis. I may have messed up on my example.
It is true that I need my identifier to output everytime. But I need it to output on entries that has differences only even if my identifier is not changed.
Here is a new example:
PreviousFile:

Name        UserPrincipalName   NickName    Age Sex
UserUser 1  User1@user.com      User1       20  M
UserUser 2  User2@user.com      User2       20  F
UserUser 3  User3@user.com      UserC       20  M
UserUser 4  User4@old.com       User4       20  M
UserUser 5  User5@old.com       User5       20  M

CurrentFile:

Name        UserPrincipalName   NickName    Age Sex
UserUser 1  User1@user.com      User1       20  M
UserUser 2  User2@user.com      User2       20  M
UserUser 3  User3@user.com      User3       20  M
UserUser 4  User4@user.com      User4       20  M
UserUser 5  User5@user.com      User5       20  M
UserUser 6  User6@user.com      User6       20  M

Expected output:

Name        UserPrincipalName   NickName    Age Sex
UserUser 2                                      F
UserUser 3                      UserC
UserUser 4  User4@user.com
UserUser 5  User5@user.com
UserUser 6  User6@user.com      User6       20  M

UserUser1 has no entries at all, because everything matches
UserUser2 has appeared on the list because the gender changed to F
UserUser3, has UserC for nickname
UserUser4 and 5 has the updated @user.com on user principal name
Useruser6 is a new object
all entries that has any difference will display the identifier 'Name' and the difference only.
I have tried playing with your code a bit, but I could not get this output. To be honest, I don't understand everything happening in your script, yet.
I hope you can help me out with this one, too.
Thank you and have a nice day!

A: For these more customized compare outputs I suggest ditching Compare-Object and going freestyle in order to control exactly what you want.
Once we determine how we want to match records between the two datasets we can loop through each property of the current objects and compare them to the same property of the matched object in the previous file.  If the values match then we should output an empty string.  If they do not match, they we should output the value of the current object.  We will always output the value of the property we choose to match on which in this case is the 'Name' property.
# TEST DATA
$previousFile = @'
Name        UserPrincipalName   NickName    Age  Sex
UserUser 1  User1@user.com      User1       20   M
UserUser 2  User2@old.com       User2       20   M
UserUser 3  User3@old.com       User3       20   M
UserUser 4  User4@old.com       User90      20   M
UserUser 5  User5@old.com       User91      20   M
'@

$currentFile = @'
Name        UserPrincipalName   NickName    Age  Sex
UserUser 1  User1@user.com      User1       20   M
UserUser 2  User2@user.com      User2       20   M
UserUser 3  User3@user.com      User3       20   M
UserUser 4  User4@user.com      User4       20   M
UserUser 5  User5@user.com      User5       20   M
UserUser 6  User6@user.com      User6       20   M
'@

$previous = $previousFile -replace ' {2,}', ',' | ConvertFrom-Csv
$current = $currentFile -replace ' {2,}', ',' | ConvertFrom-Csv
# END TEST DATA

# Set which property should be used to match records from current to previous
$matchPropertyName = 'Name'

$current | ForEach-Object {
    $obj = $_
    $match = $previous.where({ $_.$matchPropertyName -eq $obj.$matchPropertyName })
    if ($match) {
        $out = [ordered]@{}

        # loop through all the properties in current objects to determine whether to show them or not
        $obj.psobject.Properties | ForEach-Object {
            # if property = 'Name' then include the value as record Identifier
            if ($_.Name -eq $matchPropertyName) { $out[$_.Name] = $_.Value }

            # else if value of property in current matches previous set value to empty string
            elseif ($_.Value -eq $match[0].($_.Name)) {
                $out[$_.Name] = ''
            }

            # else current value does not match previous value so output current value
            else {
                $out[$_.Name] = $_.Value
            }
        }
        [pscustomobject]$out
    }

    # if not matched by 'Name' property then consider as new object and output all values
    else {
        $obj
    }
}

Output
Name       UserPrincipalName NickName Age Sex
----       ----------------- -------- --- ---
UserUser 1
UserUser 2 User2@user.com
UserUser 3 User3@user.com
UserUser 4 User4@user.com    User4
UserUser 5 User5@user.com    User5
UserUser 6 User6@user.com    User6    20  M

One thing to note about this solution is it does not account for lines that have been removed (i.e., lines that existed in previous but have been removed in current), though this appears to be what you were going for in your own example by filtering for only the leftside.

UPDATE
In response to your additional information, here is an updated solution  which does not include unchanged records and includes more detail to hopefully help you understand better what is happening.  To not output unchanged objects, when looping through and comparing the objects we can keep track of whether an object has changed in a variable and then only output the object if we know there were changes.
# TEST DATA
$previousFile = @'
Name        UserPrincipalName   NickName    Age  Sex
UserUser 1  User1@user.com      User1       20   M
UserUser 2  User2@user.com      User2       20   M
UserUser 3  User3@user.com      User3       20   M
UserUser 4  User4@user.com      User4       20   M
UserUser 5  User5@user.com      User5       20   M
UserUser 6  User6@user.com      User6       20   M
'@

$currentFile = @'
Name        UserPrincipalName   NickName    Age  Sex
UserUser 1  User1@user.com      User1       20   M
UserUser 2  User2@user.com      User2       20   M
UserUser 3  User3@user.com      User3       20   F
UserUser 4  User4@user.com      User_4       20   M
UserUser 5  User5@user.com      User_5       20   M
UserUser 6  User6@user.com      User_6       30   M
'@

$previous = $previousFile -replace ' {2,}', ',' | ConvertFrom-Csv
$current = $currentFile -replace ' {2,}', ',' | ConvertFrom-Csv
# END TEST DATA

# Set which property should be used to match records from current to previous
$matchPropertyName = 'Name'

$current | ForEach-Object {
    # in ForEach-Object scriptblock $_ is the current object being processed.
    # Below we assign $_ to $obj in order to reference it in the
    # $previous.where({}) scriptblock where $_ will reference it's own object
    # from the $previous array
    $obj = $_

    # Here we are looking for an object in $previous array where property $matchPropertyName, which we have
    # defined earlier as being equal to 'Name', matches our current object's 'Name' property.  We stick this match
    # in a variable called $match
    $match = $previous.where({ $_.$matchPropertyName -eq $obj.$matchPropertyName })

    # if we find a matching record in $previous
    if ($match) {
        # We will use $isModified to keep track of whether a changes was found in any of the properties
        $isModified = $false

        # create an ordereddictionary in which to build our own object with
        # we use this to capture the property names and values using key-value pairs
        # $out[<keyname>] = <value>
        # later we can easily convert this to an object using the [pscustomobject] type accelerator
        $out = [ordered]@{}

        # Loop through all the properties in current object to determine whether to show them or not.
        # Here we use the an intrinsic member called .psobject to access a collection containing all
        # the object's properties and values and loop through each of them.
        # i.e., we loop through objects that look like this
        #
        # Name              Value
        # ----              -----
        # Name              UserUser 1
        # UserPrincipalName User1@user.com
        # NickName          User1
        # Age               20
        # Sex               M

        # there are 5 properties so we will be looping 5 times in the following ForEach-Object call,
        # once for each property of the current object
        $obj.psobject.Properties | ForEach-Object {
            # if property = 'Name' then include the value as record Identifier
            if ($_.Name -eq $matchPropertyName) { $out[$_.Name] = $_.Value }

            # else if value of property in current matches previous set value to empty string
            elseif ($_.Value -eq $match[0].($_.Name)) {
                $out[$_.Name] = ''
            }

            # else current value does not match previous value so output current value
            else {
                # create a key-value pair in our dictionary containing the property name and value
                # e.g., $out['NickName'] = 'User1'
                $out[$_.Name] = $_.Value

                # update $isModified to true so we know to include in the output
                $isModified = $true
            }
        }

        # Check if the object has been modified and if so, output it.
        # We use the [pscustomobject] type accelerator here to convert our ordereddictionary to an object
        # containing our key-value pairs as properties.
        if ($isModified) { [pscustomobject]$out }
    }

    # if we don't find a matching object in $previous then consider as new object and output all values
    else {
        $obj
    }
}

References:

*

*.psobject intrinsic member

*[pscustomobject] type accelerator

*[ordered] type accelerator


text:
Q: Ввод массива посимвольно При присвоении строки массиву, массив принимает строку полностью, а не посимвольно, то есть элементом массива становится вся строка. Как сделать, чтобы можно было принимать посимвольно? Какждый символ строки - элемент массива.
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Scanner;
public class Program {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        ArrayList<String> arr = new ArrayList<>(Arrays.asList(sc.hasNext()));
        String f = arr.get(0);
        System.out.println(f);
        System.out.print(arr.size());
    }
}

A: Действия:

*

*Используйте Scanner для считывания введенной строки

*Разделите считанную строку на массив String

*Конвертирование массива строк в список строк

Пример:
Scanner sc = new Scanner(System.in);
String[] items = sc.nextLine().split("");

ArrayList<String> arr = new ArrayList<>(Arrays.asList(items));
System.out.println(arr);

Ввел:
123 vasas

Результат:
[1, 2, 3,  , v, a, s, a, s,  ]


text:
Q: Prove that a number consisting only of $7's$ is prime one time $7$ is prime.
However, $77$ is not prime. $777$ is also not prime.
Prove that a number consisting only of $7's$ is only prime one time.
I think this amounts to proving that $7$ is always a factor of a number entirely consisting of $7's,$ for at least two $7's$ in said number.

A: $7$ is obviously prime.
However, the successive numbers are obviously not. If the number is a repdigit of $n$ $7$'s, for $n\ge 2$, then the number factors into $7 \times r$, where $r$ is a repdigit of $n$ $1$'s.
For example:

*

*$77 = 7 \times 11$

*$777 = 7 \times 111$

*$7777 = 7 \times 1111$

A: Notice that the number
$$\begin{align*}
\underbrace{7\cdot \cdots\cdot 7}_{\color{red}{n\text{ times}}}
&=7\cdot10^{n-1}+7\cdot10^{n-2}+\cdots+7\cdot10^{0}\\\\
&=7\cdot\left(10^{n-1}+\cdots+10^{0}\right)\\\\
&=7k
\end{align*}$$
for some $k\in\mathbb{N}$

A: Not only is a string of 7's not prime ( divisibly by 7). Even if it were, it would need a prime length. Because, if not, divide up the number into substrings of length a factor of its total length. This substring divides into each substring cut once, making it divide the whole number.


text:
Q: SQL - Is there a way to check rows for duplicates in all columns of a table I have a big table with over 1 million rows and 96 columns.
Using SQL I want to find rows where every value is the same. The table doesn't have any primary key so I'm not sure how to approach this. I'm not permitted to change the table structure.
I've seen people use count(*) and group by but I'm not sure if this is effective for a table with 96 columns.

A: Using COUNT() as an analytic function we can try:
WITH cte AS (
    SELECT *, COUNT(*) OVER (PARTITION BY col1, col2, ..., col96) cnt
    FROM yourTable
)

SELECT col1, col2, ..., col96
FROM cte
WHERE cnt > 1;

A: you can use md5 function as primary key.
select count(1),md5_col,* from (
select md5(concat_ws('',col1,col2)) as md5_col,* from db_name.table_name) tt group by md5_col;

A: For convenience, use BINARY_CHECKSUM:
with cte as (
    select *, BINARY_CHECKSUM(*) checksum
    from mytable
), cte2 as (
    select checksum
    from cte
    group by checksum
    having count(*) > 1
)
select distinct t1.*
from cte t1
join cte t2 on t1.checksum = t2.checksum
  and t1.col1 = t2.col2
  and t1.col2 = t2.col2
  -- etc
where t1.checksum in (select checksum from cte2)

cte2 will return (almost) only truly matching rows, so join condition won't have many rows to exhaustively compare every column.

A: Rather than trying to boil the ocean and solve the entire problem with a single sql query (which you certainly can do...), I recommend using any indexes or statistics on the tables to filter out as many rows as you can.
Start by finding the columns with the most / fewest unique values (assuming you have statistics, that is), and smash them up against each other to rapidly exclude as many rows as possible. Take the results, dump them to a temp table, index fields as needed, and repeat.
Or you could just do this:
Declare @sql nvarchar(max);
Select @sql='select column1 from schema.table where case ' + stuff((select 'when col1!=' + quotename(name) + ' then 0 ' from sys.columns where object_id=object_id('schema.table') for xml path(''),Type).value('.','nvarchar(max)'),1,11,'') + 'else 1 end = 1';
Exec sp_executesql @sql;

If you must run that horrorshow of a query in production, please use snapshot isolation or move it to a temp table first (unless no one ever updates the table.
(Honestly, I would probably use something like that query on the temp table containing my filtered-down dataset... but anything you can do to makes sure that the comparisons aren't naïve (e.g. taking statistics into account) can improve your performance significantly. If you want to do it all at once, you could always join sys.tables to a temp table that puts your field comparisons into a thoughtful order. After all, once a case statement if found to be true, all the others will be skipped for that record. )


text:
Q: Looking for a temperature probe connector I have a temperature probe I need to connect to a PCB in a housing and I am looking for a good connector that require my needs.
The temperature probe has 3 wires of 26 AWG (0.1288 mm²).
Ideally I need something like a surface mount terminal block connector in which I don't need to physically join the wires. The connector ideally should have a height smaller then 5.00 mm due to the casing. It should be RoHS compliant and not too expensive (less than €1).
Can I possibly just use a crimp connection or will this affect the signal quality of the probe?
I have looked on all the big electronic component sites (Mouser, Farnell, Molex, ...) but with no luck so far.

A: For a Pt100 in 2-wire or 3-wire configuration, connector resistance directly affects accuracy (specifically variation between contacts in connector resistance in the 3-wire case).
Screw terminal blocks are commonly used, eg, 5mm or 5.08mm pitch. SMT is not really a good idea for something that invites an idiot with a screwdriver to torque on it, unless  you like field failures. Use through-hole parts, would be my recommendation.


text:
Q: Finite nonabelian groups with few positive real character values? This question was just raised by a colleague (who shall for the moment remain anonymous).  It may or may not have a reasonable answer.

For which finite nonabelian groups $G$ do all irreducible complex characters of degree $>1$ have at most one strictly positive real value (namely the degree)?

One small example is the alternating group $A_4$.   This could be viewed as a sort of degenerate Chevalley group, whose Steinberg character of degree $3$ has other values
$-1, 0, 0$.  But for most finite groups of Lie type over a finite field of order $q$, the Steinberg character of degree a power of $q$ will take on more than one positive integral value.   While an enumeration of finite groups having the stated property may well be out of reach, it would be of interest to know:

Are there infinitely many groups $G$ with the special property stated above?

A: Here are some classes of such groups I can think of:

*

*extraspecial $p$-groups (and probably some other $p$-groups)

*metacyclic groups, where $\lvert G: G'\rvert$ has odd order

*the groups $AGL(1,q)$ (this subsumes Tim Dokchitser's examples and the $A_4$ example). More generally, suppose a group $H$ with few positive real values acts sharply transitive on the nonzero elements of a finite vector space $V$. Then the semidirect product $HV$ has also only characters with at most one strictly positive value. An example is $Q_8$ acting on $C_3\times C_3$.

Here is an argument that rules out some groups: If a group $G$ acts $2$-transitively on some set, then the permutation character $\pi$ has the form $\pi= 1+\chi$ with $\chi \in \operatorname{Irr}(G)$. By assumption, if $g$ acts nontrivially, then $\chi(g)\leq 0$. This implies that every element not in the kernel $K$ of the action has at most one fixpoint. But then $G/K$ is a Frobenius group, the elements with no fixpoints form the Frobenius kernel.
While I'm not an expert for finite simple groups, I suppose this argument rules out many (all?) finite simple groups, namely all that admit a $2$-transitive permutation representation.
Since the property in the question is inherited by factor groups, this would also yield that there are no perfect groups with that property.
EDIT: Thanks to Jack for putting that right. Anyway, simple groups are ruled out by ARupinksi's comment.

A: Here is an argument that resticts the structure of such groups of even order, which expands on ARupinksi's comments above (inspiration came from a nice argument in this paper).
Namely, suppose that $1\neq t$ is a real element in $G$, where $G$ is as in the question. Form the following normal subgroups:
$$ K = \langle t \rangle^G = \bigcap_{\chi(1)=\chi(t)} \ker \chi
  \quad \text{and} \quad
   L = \bigcap_{\chi(t) \neq 0} \ker \chi < K , $$
where the intersections run over irreducible characters $\chi$ of $G$. Then we have
$$ t^G = K \setminus L,$$
that is, the elements in $K\setminus L$ are all conjugate in $G$ to $t$. In particular, it turns out that $t$ is rational in the sense that it is conjugate to every generator of $\langle t \rangle$, which is equivalent to every character having rational value at $t$.
Why is this true? Well, column orthogonality yields $\DeclareMathOperator{\Irr}{Irr}$
$$ 0 = \sum_{\chi \in \Irr G} \chi(t)\chi(1) = |G:K| + \sum_{\chi(t)<\chi(1)}\chi(t)\chi(1). $$
Now let $y\in K$ and suppose that $t$ and $y$ are not conjugate. Then plugging in $y$ instead of $1$ in the last formula, we see that
$$ \sum_{\chi(t)<\chi(1)} (-\chi(t))\chi(y) = |G:K|
  =\sum_{\chi(t)<\chi(1)} (-\chi(t))\chi(1) .$$
Since $-\chi(t)>0$ and $|\chi(y)|\leq\chi(1)$, it follows that $y$ is in the kernel of every irr char $\chi$ with $\chi(t)< 0$, that is, $y\in L$. Thus $K\setminus L = t^G$.
(Added later:) If $t$ is an involution, then it follows that $x^t=x^{-1}$ for all $x\in L$, in particular $L$ must be abelian, and elements of $L$ are real.
The "dual" argument (exchanging the roles of characters and conjugacy classes) shows the following: Suppose $1\neq \chi$ is real valued, and let $V= \operatorname{\mathbf{V}}(\chi)$ be the vanishing-off group of $\chi$, generated by all group elements on which $\chi$ is non-zero. Then
$$ \Irr( G/\ker \chi ) = \{ \chi \} \cup \Irr(G/V). $$
From this it follows easily that $V/\ker\chi$ is a conjugacy class of $G/\ker\chi$ and that the only value of $\chi$ besides $0$ and $\chi(1)$ is $-\chi(1)/(|V/\ker\chi|-1)$. (In particular, any real character is rational.) Groups with such an character have been studied by Zhmud, where more information can be found.
I suppose there is also literature on groups having normal subgroups $L\subset K$ such that $K\setminus L$ is a conjugacy class of $G$. The notion of a Camina pair/group seems to be related (see this paper and papers that refer to it).


text:
Q: In python is there a way to delete parts of a column? I want to trim the values of a pandas data frame. For example, I have the following:
 A            B        C
 33344-10   5555-78  999902
 3444441    5555679  2334
 2334       5555     3344

And I would like the result to be:
A            B         C
3334       5555     9999
3444       5555     2334
2334       5555     3344

If anyone could help it would be very appreciated.

A: slice each column in a loop as below
columns = df.columns
for column in columns:
    df[column] = df[column].astype(str).str[:4]
df

which gives you the following output
    A   B   C
0   3334    5555    9999
1   3444    5555    2334
2   2334    5555    3344

A: To keep first 4 characters in string columns:
for c in ['A', 'B', 'C']:
    df[c] = df[c].str.slice(stop=4)

A: Use DateFrame.applymap:
new_df = df.applymap(lambda s: str(s)[:4])

The str takes care of those values which are not strings (e.g. int).


text:
Q: Recurrence relation for the coefficients of the polynomial $p_n(x) = \prod_{i=0}^{n-1}(x-i)$ Let's consider the polynomials
$$ p_n(x) = \prod_{i=0}^{n-1}(x-i)=\sum_{i=1}^{n} a_{n,i}x^i$$.
for all $n \in \mathbb{N}$. If $n=1$, then $p_1(x) = x$ and $a_{1,1} = 1$.
Since I know that:
$$p_{n+1}(x) = p_n(x)(x-n)$$
then I can deduce the following:
$$\begin{eqnarray}
\sum_{i=1}^{n+1} a_{n+1,i}x^i & = & \sum_{i=1}^{n} a_{n,i}x^i(x-n) = \\
& = & \sum_{i=1}^{n} a_{n,i}x^{i+1}-\sum_{i=1}^{n} na_{n,i}x^i = \\
& = & \sum_{i=2}^{n+1} a_{n,i-1}x^{i}-\sum_{i=1}^{n} na_{n,i}x^i = \\
& = & a_{n,n}x^{n+1} + \sum_{i=2}^{n} (a_{n,i-1}-na_{n,i})x^i -na_{n,1}x.\\
\end{eqnarray}$$
Then I get this recurrence relation for the coefficients $a$:
$$\left\{\begin{array}{lcll}
a_{n+1,n+1} & = & a_{n,n} & \\
a_{n+1,i} & = & a_{n,i-1}-na_{n,i} &~\forall i \in \{2, \ldots, n\}, ~\forall n \geq 2 \\
a_{n+1,1} & = & -na_{n,1} & \\
a_{1,1} & = & 1 &
\end{array}\right.$$
Is this right? I wrote a Matlab code for this but it seems to work only up to $n=19$!!! I mean, I produce two polynomials, one using the formula
$$p_n(x) = \prod_{i=0}^{n-1}(x-i)$$
and one using the recurrence relation I found. When $n=20$, the difference between the two polynomial is not $0$. Is my maths correct or I have to review my code?

A: Hint: $a_{n,i}$ are  the Stirling numbers of the first kind


text:
Q: Exponential backoff for business exceptions when using reactive spring-amqp? I'm using Spring AMQP 2.1.6 and Spring Boot 2.1.5 and I'm looking for the recommended way to configure spring-amqp to retry business exceptions for reactive components (Mono) with exponential backoff. For example:
@RabbitListener
public Mono<Void> myListener(MyMessage myMessage) {
    Mono<Void> mono = myService.doSomething(myMessage);
    return mono;
}

I'd like spring-amqp to retry automatically if doSomething returns an error. Usually one can configure this for blocking RabbitListener's when setting up the container factory:
SimpleRabbitListenerContainerFactory factory = new SimpleRabbitListenerContainerFactory();
...
factory.setAdviceChain(retryInterceptor(..));

Where retryInterceptor might be defined like this:
private static RetryOperationsInterceptor retryInterceptor(long backoffInitialInterval, double backoffMultiplier, long backoffMaxInterval, int maxAttempts) {
    ExponentialBackOffPolicy backOffPolicy = new ExponentialBackOffPolicy();
    backOffPolicy.setInitialInterval(backoffInitialInterval);
    backOffPolicy.setMultiplier(backoffMultiplier);
    backOffPolicy.setMaxInterval(backoffMaxInterval);

    RetryTemplate retryTemplate = new RetryTemplate();
    retryTemplate.setRetryPolicy((new SimpleRetryPolicy(maxAttempts)));
    retryTemplate.setBackOffPolicy(backOffPolicy);

    StatelessRetryOperationsInterceptorFactoryBean bean = new StatelessRetryOperationsInterceptorFactoryBean();
    bean.setRetryOperations(retryTemplate);
    return bean.getObject();
}

But the advice chain doesn't seem to be used for reactive RabbitListener's. This is probably because, if I understand it correctly, the RetryTemplate/ExponentialBackOffPolicy actually blocks the thread.
As a workaround I could of course do something like (switching to Kotlin because it's a bit easier):
@RabbitListener
fun myListener(MyMessage myMessage) : Mono<Void> {
    return myService.doSomething(myMessage)
                    .retryExponentialBackoff(10, Duration.ofMillis(100), Duration.ofSeconds(5)) { ctx ->
            log.info("Caught exception ${ctx.exception()}")
        }
}

But I'd like this retry logic to be applied to for all instances of Mono returned from RabbitListener's. Is something like this possible or should you configure this another way when using reactive sequences from project reactor with spring-amqp?

A: It is really better to apply retry logic into your reactive sequence, similar way you do with the retryExponentialBackoff(). Just because the Reactive Streams execution doesn't happen on the same thread we can apply that Retrytemplate for the myListener().
Right now the logic internally is like this:
private static class MonoHandler {

    static boolean isMono(Object result) {
        return result instanceof Mono;
    }

    @SuppressWarnings("unchecked")
    static void subscribe(Object returnValue, Consumer<? super Object> success,
            Consumer<? super Throwable> failure) {

        ((Mono<? super Object>) returnValue).subscribe(success, failure);
    }

}

That Consumer<? super Throwable> failure does this:
private void asyncFailure(Message request, Channel channel, Throwable t) {
    this.logger.error("Future or Mono was completed with an exception for " + request, t);
    try {
        channel.basicNack(request.getMessageProperties().getDeliveryTag(), false, true);
    }
    catch (IOException e) {
        this.logger.error("Failed to nack message", e);
    }
}

So, we don't have any way to to initiate that RetryTemplate at all, but at the same time with an explicit basicNack() we have a natural retry with the re-fetching the same message from the RabbitMQ back.
We could probably apply a Reactor retry for that Mono internally, but it doesn't look like RetryOperationsInterceptor can simply be converted to the Mono.retry().
So, in other words, the RetryOperationsInterceptor is a wrong way for reactive processing. Use Mono.retry() explicitly in your own code.
You may expose some common utility method and apply it as a Mono.transform(Function<? super Mono<T>, ? extends Publisher<V>> transformer) whenever you have a reactive return for the @RabbitListener method.


text:
Q: XPC and cross-architecture OSX applications for a desktop application I am developing, I have to stick with a 32-bit framework. I am looking for the best path to run the framework in its proper process and develop the rest of the application in a 64-bit process. The application is also meant to be sold in the AppStore, so it should support Apple sandboxing.
I am thinking about XPC: is it suitable for these purposes? Why can't I find it in the Apple documentation related to cross-architecture programming?

A:
XPC: is it suitable for these purposes?

Yes, XPC should work correctly between 32-bit and 64-bit processes.

Why can't I find it in the Apple documentation related to cross-architecture programming?

Because XPC is new in 10.7, and that 64-bit Transition Guide document is rather old and hasn't been updated since 10.6.  Apple is not always good at updating older documentation.


text:
Q: Error with request using auth0 JWT token in Angular Problem with request when using auth0 JWT token in Angular.
I'm use angular2-jwt by Auth0
Scenario: I have an angled application using JWT Auth0 working perfectly, but I have discovered a request problem. When I log in to another application that uses XSRF-TOKEN in the browser, my application stops working and no longer supplies the correct header.
Request Headers
> Accept:application/json, text/plain, */* Accept-Encoding:gzip,
> deflate, br Accept-Language:pt-BR,pt;q=0.8,en-US;q=0.6,en;q=0.4
> Authorization:JWT
> eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoxLCJ1c2VybmFtZSI6ImFkbWluIiwiZXhwIjoxNTA1MTYwNDU1LCJlbWFpbCI6InN1cG9ydGVAbXd0aS5jb20uYnIifQ.HK7nxI3ZTMbtczKKFNwduMqfUCsSDPnR9ROKoFbIbaw
> Connection:keep-alive Content-Length:51 Content-Type:application/json
> Host:127.0.0.1:8000 Origin:http://localhost:4200
> Referer:http://localhost:4200/login User-Agent:Mozilla/5.0 (Macintosh;
> Intel Mac OS X 10_12_6) AppleWebKit/537.36 (KHTML, like Gecko)
> Chrome/60.0.3112.113 Safari/537.36

Now the request when there is an XSRF-TOKEN inside the cookie
> Accept:*/* Accept-Encoding:gzip, deflate, br
> Accept-Language:pt-BR,pt;q=0.8,en-US;q=0.6,en;q=0.4
> Access-Control-Request-Headers:authorization,x-xsrf-token
> Access-Control-Request-Method:GET Connection:keep-alive
> Host:127.0.0.1:8000 Origin:http://localhost:4200
> Referer:http://localhost:4200/login User-Agent:Mozilla/5.0 (Macintosh;
> Intel Mac OS X 10_12_6) AppleWebKit/537.36 (KHTML, like Gecko)
> Chrome/60.0.3112.113 Safari/537.36

When an XSRF-TOKEN exists my header with JWT is not sent and replaced.


text:
Q: Perlin Noise in Java For a cellular automata project I'm working on I need to generate two dimensional boolean arrays randomly using different algorithms and techniques. At the moment I have just one type of randomization in the application - looping through every cell in the array and generating a random double variable, then if the random number is higher than 0.5 then I set that cell to true, if not it gets set to false.
I would like to look into generating these boolean matrices using more interesting algorithms such as Perlin Noise or something like that. Noise generators that are used in terrain generation or something like that might be good if you know of any other than Perlin Noise (Minecraft's world generation gave me this idea).
The only problem is I have no idea where to start (any ideas?) :)

A: I have some perlin noise implementations and some other noise generation functions in my library code:
http://code.google.com/p/mikeralib/source/browse/#svn%2Ftrunk%2FMikera%2Fsrc%2Fmain%2Fjava%2Fmikera%2Fmath
Feel free to explore / use (code is open source GPL, based on the J3D code).

A: The first thing I thought of was a random displacement fractal. It is also used to generate terrain and is easier than Perlin Noise.
package so;

import java.util.Random;

public class Noise {
    /** Source of entropy */
    private Random rand_;

    /** Amount of roughness */
    float roughness_;

    /** Plasma fractal grid */
    private float[][] grid_;

    /** Generate a noise source based upon the midpoint displacement fractal.
     *
     * @param rand The random number generator
     * @param roughness a roughness parameter
     * @param width the width of the grid
     * @param height the height of the grid
     */
    public Noise(Random rand, float roughness, int width, int height) {
        roughness_ = roughness / width;
        grid_ = new float[width][height];
        rand_ = (rand == null) ? new Random() : rand;
    }

    public void initialise() {
        int xh = grid_.length - 1;
        int yh = grid_[0].length - 1;

        // set the corner points
        grid_[0][0] = rand_.nextFloat() - 0.5f;
        grid_[0][yh] = rand_.nextFloat() - 0.5f;
        grid_[xh][0] = rand_.nextFloat() - 0.5f;
        grid_[xh][yh] = rand_.nextFloat() - 0.5f;

        // generate the fractal
        generate(0, 0, xh, yh);
    }

    // Add a suitable amount of random displacement to a point
    private float roughen(float v, int l, int h) {
        return v + roughness_ * (float) (rand_.nextGaussian() * (h - l));
    }

    // generate the fractal
    private void generate(int xl, int yl, int xh, int yh) {
        int xm = (xl + xh) / 2;
        int ym = (yl + yh) / 2;
        if ((xl == xm) && (yl == ym)) return;

        grid_[xm][yl] = 0.5f * (grid_[xl][yl] + grid_[xh][yl]);
        grid_[xm][yh] = 0.5f * (grid_[xl][yh] + grid_[xh][yh]);
        grid_[xl][ym] = 0.5f * (grid_[xl][yl] + grid_[xl][yh]);
        grid_[xh][ym] = 0.5f * (grid_[xh][yl] + grid_[xh][yh]);

        float v = roughen(0.5f * (grid_[xm][yl] + grid_[xm][yh]), xl + yl, yh
                + xh);
        grid_[xm][ym] = v;
        grid_[xm][yl] = roughen(grid_[xm][yl], xl, xh);
        grid_[xm][yh] = roughen(grid_[xm][yh], xl, xh);
        grid_[xl][ym] = roughen(grid_[xl][ym], yl, yh);
        grid_[xh][ym] = roughen(grid_[xh][ym], yl, yh);

        generate(xl, yl, xm, ym);
        generate(xm, yl, xh, ym);
        generate(xl, ym, xm, yh);
        generate(xm, ym, xh, yh);
    }

    /**
     * Dump out as a CSV
     */
    public void printAsCSV() {
        for(int i = 0;i < grid_.length;i++) {
            for(int j = 0;j < grid_[0].length;j++) {
                System.out.print(grid_[i][j]);
                System.out.print(",");
            }
            System.out.println();
        }
    }

    /**
     * Convert to a Boolean array
     * @return the boolean array
     */
    public boolean[][] toBooleans() {
        int w = grid_.length;
        int h = grid_[0].length;
        boolean[][] ret = new boolean[w][h];
        for(int i = 0;i < w;i++) {
            for(int j = 0;j < h;j++) {
                ret[i][j] = grid_[i][j] < 0;
            }
        }
        return ret;
    }

    /** For testing */
    public static void main(String[] args) {
        Noise n = new Noise(null, 1.0f, 250, 250);
        n.initialise();
        n.printAsCSV();
    }
}


text:
Q: ggplot2: setting guide ticks in scale_color_gradient() I'd like to change x values in the legend below so that they are nice round numbers (e.g. 0.01, 1, 10) instead of the crazy long, seemingly arbitrary decimals. How do I do so?  I generated the plot using the code further below. This seems like there should be a really easy option to set, but I googled around and read the help files and for the life of me, I can't figure it out.
I'm currently using ggplot2_1.0.1.

library(ggplot2)
d = data.frame(x = 10^seq(-2,2,length.out=10),y=10^(seq(-2,2,length.out=10)))
g = ggplot(data=d,aes(x=x,y=y,group=x,color=x)) + geom_point()
g = g + scale_color_gradient(trans="log",guide="legend")
print(g)

A: Just add breaks= argument to the function scale_color_gradient() to set desired levels.
ggplot(data=d,aes(x=x,y=y,group=x,color=x)) + geom_point() +
      scale_color_gradient(trans="log",guide="legend",breaks=c(0.01,1,10))


text:
Q: Dovecot: How to unset namespace configuration from dovecot.conf in conf.d/99-custom.conf? My /etc/dovecot/dovecot.conf that is shipped with the Linux (Ubuntu 16.04) distro has a namespace section:
namespace inbox {
  ...
  mailbox Sent {
    ...
  }
  ...
}

I need to remove this whole section from the configuration, but I need to do this in a file such as /etc/dovecot/conf.d/99-custom.conf because I want this modification to be stable against automatic updates of dovecot.conf shipped by the distro.
How do I "unset" an earlier namespace configuration at a later point in 99-custom.conf? The desired behavior is the configuration of dovecot that results from the namespace passage completely removed in dovecot.conf. Basically, I would like to achieve this without modifying dovecot.conf.
Thanks.

A: It looks like your dovecot.conf has already been modified.
The dovecot-core package of Ubuntu 16.04 LTS uses ucf to handle configuration files, so a copy of the distribution's current "factory default" dovecot.conf should be at /usr/share/dovecot/dovecot.conf on your system. The same should be true for essentially all the Dovecot configuration files supplied by the package.
(There's a fairly substantial bit of scripting to handle these configuration files in the postinst script of the package.)
I've just downloaded and extracted dovecot-core of 16.04 LTS and checked the default configuration file. It has no namespace entries at all, and in fact has a comment that confirms that there is supposed to be no active namespace nor plugin settings in it by default:
# Default values are shown for each setting, it's not required to uncomment
# those. These are exceptions to this though: No sections (e.g. namespace {})
# or plugin settings are added by default, they're listed only as examples.

ucf attempts to preserve local configuration changes, so it is possible that your namespace configuration is in fact either something that's been done locally, or a remnant from a yet earlier version that has been preserved just fine so far, if you've upgraded this system from an earlier major release.
On my Debian 10 system with Dovecot in use, /etc/dovecot/dovecot.conf is 100% identical to /usr/share/dovecot/dovecot.conf. Neither of them contains any namespace sections.
You should probably run diff -u /usr/share/dovecot/dovecot.conf /etc/dovecot/dovecot.conf to find the differences between the distribution's "factory default" configuration and your current one. Perhaps it's just the namespace declaration that has been placed in dovecot.conf instead of /etc/dovecot/conf.d/99-custom.conf back when the system was new and you didn't know of a better way.
Or perhaps you'll find that there are a lot of differences, probably because the current dovecot.conf has been carried over from an older release? In that case, it would seem you've incurred some technical debt over at least one release cycle, and today might be a good day to start getting rid of it, by carefully picking apart the differences and moving local customizations to 99-custom.conf.

When using hosting control panel such as Plesk, there may be major differences in configuration. Plesk documentation says this about using Dovecot:

Due to high diversity of Dovecot versions in OS vendor repositories, we build our own packages. Many Dovecot features that do not make much sense in Plesk context are left out (the provided version is built without their support).

So you may be getting a Dovecot configuration that is effectively partially hard-coded and/or restricted in other ways too. It seems that the Plesk-provided Dovecot configuration may be optimized for being administered mostly or exclusively through the hosting control panel.
However, with the dpkg packaging system, there is a feature you can use in situations like this.
sudo dpkg-divert --local --rename --add /etc/dovecot/dovecot.conf

This command will cause the package management to rename the existing dovecot.conf file to /etc/dovecot/dovecot.conf.distrib and it will keep redirecting any future versions of the package-provided file to the new name so that the actual dovecot.conf is no longer managed by packages at all.
After that command, you can/must run:
sudo cp /etc/dovecot/dovecot.conf.distrib /etc/dovecot/dovecot.conf

and then you can manipulate dovecot.conf as you please, secure in the knowledge that any changes the package management would apply will go into dovecot.conf.distrib instead. Effectively, you have told dpkg that "when a package talks about dovecot.conf, it actually means dovecot.conf.distrib instead."
Please use this knowledge wisely, as it also allows you to shoot yourself in the foot in spectacular ways, if used without due consideration.


text:
Q: Nodejs async & sync reading & writing of files - when to use which? It's a very general question, but I don't quite understand. When would I prefer one over the other? I don't seem to understand what situations might arise, which would clearly favour one over the other. Are there strong reasons to avoid x / use x?

A:
When would I prefer one over the other?

In a server intended to scale and serve the needs of many users, you would only use synchronous I/O during server initialization.  In fact, require() itself uses synchronous I/O.  In all other parts of your server that handle incoming requests once the server is already up and running, you would only use asynchronous I/O.
There are other uses for node.js besides creating a server.  For example, suppose you want to create a script that will parse through a giant file and look for certain words or phrases.  And, this script is designed to run by itself to process one file and it has no persistent server functionality and it has no particular reason to do I/O from multiple sources at once.  In that case, it's perfectly OK to use synchronous I/O.  For example, I created a node.js script that helps me age backup files (removing backup files that meet some particular age criteria) and my computer automatically runs that script once a day.  There was no reason to use asynchronous I/O for that type of use so I used synchronous I/O and it made the code simpler to write.

I don't seem to understand what situations might arise, which would clearly favour one over the other. Are there strong reasons to avoid x / use x?

Avoid ever using synchronous I/O in the request handlers of a server.  Because of the single threaded nature of Javascript in node.js, using synchronous I/O blocks the node.js Javascript thread so it can only do one thing at a time (which is death for a multi-user server) whereas asynchronous I/O does not block the node.js Javascript thread (allowing it to potentially serve the needs of many users).
In non-multi-user situations (code that is only doing one thing for one user), synchronous I/O may be favored because writing the code is easier and there may be no advantages to using asynchronous I/O.

I thought of an electron application with nodejs, which is simply reading a file and did not understand what difference that would make really, if my software really just has to wait for that file to load anyways.

If this is a single user application and there's nothing else for your application to be doing while waiting for the file to be read into memory (no sockets to be responding to, no screen updates, no other requests to be working on, no other file operations to be running in parallel), then there is no advantage to using asynchronous I/O so synchronous I/O will be just fine and likely a bit simpler to code.

A:
When would I prefer one over the other?

Use the non-Sync versions (the async ones) unless there's literally nothing else you need your program to do while the I/O is pending, in which case the Sync ones are fine; see below for details...

Are there strong reasons to avoid x / use x?

Yes. NodeJS runs your JavaScript code on a single thread. If you use the Sync version of an I/O function, that thread is blocked waiting on I/O and can't do anything else. If you use the async version, the I/O can continue in the background while the JavaScript thread gets on with other work; the I/O completion will be queued as a job for the JavaScript thread to come back to later.
If you're running a foreground Node app that doesn't need to do anything else while the I/O is pending, you're probably fine using Sync calls. But if you're using Node for processing multiple things at once (like web requests), best to use the async versions.
In a comment you added under the question you've said:

I thought of an electron application with nodejs, which is simply reading a file and did not understand what difference that would make really, if my software really just has to wait for that file to load anyways.

I have virtually no knowledge of Electron, but I note that it uses a "main" process to manage windows and then a "rendering" process per window (link). That being the case, using Sync functions will block the relevant process, which may affect application or window responsiveness. But I don't have any deep knowledge of Electron (more's the pity).

Until somewhat recently, using async functions meant using lots of callback-heavy code which was hard to compose:
// (Obviously this is just an example, you wouldn't actually read and write a file this way, you'd use streaming...)
fs.readFile("file1.txt", function(err, data) {
    if (err) {
        // Do something about the error...
    } else {
        fs.writeFile("file2.txt", data, function(err) {
            if (err) {
                // Do something about the error...
            } else {
                // All good
        });
    }
});

Then promises came along and if you used a promisified* version of the operation (shown here with pseudonyms like fs.promisifiedXYZ), it still involved callbacks, but they were more composable:
// (See earlier caveat, just an example)
fs.promisifiedReadFile("file1.txt")
.then(function(data) {
    return fs.promisifiedWriteFile("file2.txt", data);
})
.then(function() {
    // All good
})
.catch(function(err) {
    // Do something about the error...
});

Now, in recent versions of Node, you can use the ES2017+ async/await syntax to write synchronous-looking code that is, in fact, asynchronous:
// (See earlier caveat, just an example)
(async () => {
    try {
        const data = await fs.promisifiedReadFile("file1.txt");
        fs.promisifiedWriteFile("file2.txt", data);
        // All good
    } catch (err) {
        // Do something about the error...
    }
})();

Node's API predates promises and has its own conventions. There are various libraries out there to help you "promisify" a Node-style callback API so that it uses promises instead. One is promisify but there are others.


text:
Q: Rocksdb undefined symbol: ZSTD_versionNumber Cpython [2021-06-18 17:52:53,711: ERROR]: [^Worker]: Error: ImproperlyConfigured('RocksDB bindings not installed? pip install python-rocksdb',)
Traceback (most recent call last):
  File "/usr/local/lib/python3.6/site-packages/faust/stores/rocksdb.py", line 159, in __init__
    import rocksdb as _rocksdb  # noqa: F401
  File "/usr/local/lib/python3.6/site-packages/rocksdb/__init__.py", line 1, in <module>
    from ._rocksdb import *
ImportError: /usr/local/lib/python3.6/site-packages/rocksdb/_rocksdb.cpython-36m-x86_64-linux-gnu.so: undefined symbol: ZSTD_versionNumber

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "/usr/local/lib/python3.6/site-packages/mode/worker.py", line 264, in execute_from_commandline
    self.loop.run_until_complete(self._starting_fut)
  File "/usr/local/lib/python3.6/asyncio/base_events.py", line 488, in run_until_complete
    return future.result()
  File "/usr/local/lib/python3.6/site-packages/mode/services.py", line 719, in start
    await self._default_start()
  File "/usr/local/lib/python3.6/site-packages/mode/services.py", line 726, in _default_start
    await self._actually_start()
  File "/usr/local/lib/python3.6/site-packages/mode/services.py", line 750, in _actually_start
    await child.maybe_start()
  File "/usr/local/lib/python3.6/site-packages/mode/services.py", line 778, in maybe_start
    await self.start()
  File "/usr/local/lib/python3.6/site-packages/mode/services.py", line 719, in start
    await self._default_start()
  File "/usr/local/lib/python3.6/site-packages/mode/services.py", line 726, in _default_start
    await self._actually_start()
  File "/usr/local/lib/python3.6/site-packages/mode/services.py", line 750, in _actually_start
    await child.maybe_start()
  File "/usr/local/lib/python3.6/site-packages/mode/services.py", line 778, in maybe_start
    await self.start()
  File "/usr/local/lib/python3.6/site-packages/mode/services.py", line 719, in start
    await self._default_start()
  File "/usr/local/lib/python3.6/site-packages/mode/services.py", line 726, in _default_start
    await self._actually_start()
  File "/usr/local/lib/python3.6/site-packages/mode/services.py", line 743, in _actually_start
    await self.on_start()
  File "/usr/local/lib/python3.6/site-packages/faust/tables/manager.py", line 130, in on_start
    await self._update_channels()
  File "/usr/local/lib/python3.6/site-packages/faust/tables/manager.py", line 140, in _update_channels
    await table.maybe_start()
  File "/usr/local/lib/python3.6/site-packages/mode/services.py", line 778, in maybe_start
    await self.start()
  File "/usr/local/lib/python3.6/site-packages/mode/services.py", line 719, in start
    await self._default_start()
  File "/usr/local/lib/python3.6/site-packages/mode/services.py", line 726, in _default_start
    await self._actually_start()
  File "/usr/local/lib/python3.6/site-packages/mode/services.py", line 743, in _actually_start
    await self.on_start()
  File "/usr/local/lib/python3.6/site-packages/faust/tables/base.py", line 195, in on_start
    await self.add_runtime_dependency(self.data)
  File "/usr/local/lib/python3.6/site-packages/faust/tables/base.py", line 190, in data
    self._data = self._new_store()
  File "/usr/local/lib/python3.6/site-packages/faust/tables/base.py", line 171, in _new_store
    return self._new_store_by_url(self._store or self.app.conf.store)
  File "/usr/local/lib/python3.6/site-packages/faust/tables/base.py", line 182, in _new_store_by_url
    options=self.options,
  File "/usr/local/lib/python3.6/site-packages/faust/stores/rocksdb.py", line 161, in __init__
    raise error from exc
faust.exceptions.ImproperlyConfigured: RocksDB bindings not installed? pip install python-rocksdb

I am using python 3.6, and RocksDB is installed in the container by following command:
  9 RUN git clone https://github.com/facebook/rocksdb.git /tmp/roc    ksdb
 10 WORKDIR /tmp/rocksdb
 11 RUN make shared_lib INSTALL_PATH=/usr && make install && rm -rf /tmp/rocksdb
 12
 13 ENV CGO_CFLAGS  "-I/usr/local/include"
 14 ENV CGO_LDFLAGS "-L/usr/local/lib -lrocksdb -lstdc++ -lm -lz -lbz2 -lsnappy"
 15 ENV LD_LIBRARY_PATH="/usr/local/lib"

It looks like a version issue for me. Not sure how to resolve it. Tried add rocksdb and python-rocksdb to the requirement file. But not work either. The service was working before. However, the last working docker container was built a year ago. Many error raise when I try to re build this time.
Appreciate for any help!

A: Don't use the latest version of anything for automated builds, pin the version to the most recent, tested, working version. It looks like this project uses tags to denote release versions. You'll need to figure out the date of the last build, go to the repository, find the tag immediately preceding the date of the last working build and check it out before running make.

RUN git clone https://github.com/facebook/rocksdb.git /tmp/rocksdb
WORKDIR /tmp/rocksdb
RUN git checkout tags/<tag_name>
RUN make shared_lib INSTALL_PATH=/usr && make install && rm -rf /tmp/rocksdb

Replace <tag_name> with the name of the appropriate tag. For example, say you want to install version 6.1.1.

RUN git checkout tags/v6.1.1

You may need to try a couple tags from around that time because the last working build actually installed the latest commit on the master branch. Once you have a successful build you can begin the process of testing new versions of rocksdb to find the newest version that works with your app.
Another thing: While you're at it, pin the version of your docker image. For instance: don't use debian:latest, use debian:9.13.


text:
Q: Testing web pages using Java I am looking for java tests that I can use in automation testing of web pages hosted locally.
These are for RESTful web services.
The situation is we have some web pages or web service hosted locally and I need to run several tests on this.

A: Maybe Selenium? You can use it to drive a web browser to browse through your pages. You can use Java code to make assertions about what the page looks like after you do certain things (click a button, type some text, etc).

A: Selenium for webpages, soapUI for RESTful web services.

A: You can use the URL class in Java: http://docs.oracle.com/javase/7/docs/api/java/net/URL.html
I feel that you don't need to use Selenium as the REST calls you will be making are independent of the browser. You don't need an actual browser to make these calls. If you do that, your automation will run a lot faster.
If you also have an authentication and authorization service then you will need to take care of it using the Set-Cookie HTTP header.


text:
Q: Qt C++ Help Showing a Moving Image using PixMap I'm using Qt in c++ to code plants z zombies which involves me moving things across the screen.
To do that, I'm using QTimer which I've connected to the advance() function.
I'm able to get my object to move (using qDebug and seeing the coordinates) but I don't physically see the picture change unless I refresh the screen or switch windows (e.g. pressing alt tab twice or clicking the windows key button)
This is an example of one of my classes. Here I'm trying to get my peas move across the screen.
#ifndef BULLETS_H
#define BULLETS_H

#include <QPoint>
#include <QGraphicsScene>
#include <QGraphicsPixmapItem>
#include <QGraphicsItem>
#include <QRectF>
#include <QPainter>
#include <QVector>
#include <QImage>
#include <QWidget>
//#include "mainwindow.h"

class bullets : public QGraphicsItem
{
public:
    QRectF boundingRect() const {return QRectF(this->x,0, 20,20);}
    void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget);

    bullets(int xPlant, int yPlant, QImage bullet);
    ~bullets() {}

    void advance(int phase); //Moves the bullet across the screen

    int x;
    int y;

    QGraphicsPixmapItem *bulletsPixMap;
    QImage pea_picture;

    int velocity;
};

#endif

along with the corresponding cpp file
#include "bullets.h"

#include <QDebug>
#include <QPainter>

int counter = 0;

bullets::bullets(int xPlant, int yPlant,QImage bullet)
{
    velocity = 10;
    x = xPlant;
    y = yPlant;
    pea_picture = bullet;
}

void bullets::advance(int phase)
{
    if (!phase)
        return;
    x += (velocity * 0.5);
    //  setPos(x,y);
}

void bullets::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
{
    painter->drawPixmap(this->x,this->y,QPixmap::fromImage(pea_picture));

    /*
    QBrush b(QColor(0,252,0));
    painter->setBrush(b);
    painter->drawEllipse(boundingRect());
    */
}


text:
Q: Max baudrate of FT2232H in synchronous FIFO mode In datasheet at FT2232H chip:

The FT2232H has the following advanced functions:

*

*...

*Single channel synchronous FIFO mode for transfers upto 40 Mbytes/Sec.

*...

I configure device with the recommended settings, according to FTDI application note AN_130 and other.
When in the program I call FT_SetBaudRate() function, maximum value of baud rate is 8_000_000, which provides the max speed 8 Mbytes/sec (parallel interface). Attempts to set the upper baud rate are throw error FT_INVALID_BAUD_RATE.
So, how can be reached the maximum promised speed?


text:
Q: Initializing structs inside a struct with malloc? Here is my data structure for an NPC.
typedef struct npc {
   npc_characteristics_t characteristics;
   position pc_last_known_position;
   position npc_position;
   int speed;
   int turn;
} npc_t;

I initialize it with this:
void gen_monsters(dungeon *d, int nummon) {
  int i;
  for (i = 0; i < nummon; i++) {
    npc_t *monster;
    if (!(monster = malloc(sizeof (*monster)))) {
      perror("malloc");
      exit(1);
    } else {
      init_monster(monster);
    }
  }
}

static void init_monster(npc_t *m) {
  int charact = rand()%3;

  if (charact == 0)
    m->characteristics = 0x00000000;
  else if (charact == 1)
    m->characteristics = NPC_SMART;
  else if (charact == 2)
    m->characteristics = NPC_TELEPATH;

  m->pc_last_known_position = {0, 0};
  m->npc_position = {0, 0};
  m->speed = rand() % 15 + 6;
  m->turn = 0;
}

And this is my position struct:
typedef struct position_t {
  int x, y;
} position;

Why isn't this working? I'm getting this:
npc.c:22:1: error: expected identifier or '(' before '}' token
 }
 ^
npc.c: In function 'init_monster':
npc.c:35:30: error: expected expression before '{' token
  m->pc_last_known_position = {0,0};
                          ^
npc.c:37:20: error: expected expression before '{' token
  m->npc_position = {0,0};
                    ^
make: *** [npc.o] Error 1

And what's the correct way to do this? I'm supposed to use malloc to get some room in memory for the structure right? But then wouldn't I need to do this for position also and give the NPC the pointer to the position struct?

A: Although you can't use an initializer list that way, you can use the memset() function from the string.h header, this way
memset(&(m->pc_last_known_position), 0, sizeof(m->pc_last_known_position));
memset(&(m->npc_position), 0, sizeof(m->pc_last_known_position));


text:
Q: Hibernate getting slower after many inserts I've got a problem. In my sollution I need to insert thousands datas to database. I am using batch prepare statement to insert many rows in one request. After i call inserting few times, hibernate goes much more slower.
I guess it checks database for changes after my commites. Maybe I need to tel hibernate not to do it, but idk how.
Session session = em.unwrap(Session.class);
        while (!stop) {
            if (data.size() == 0) {
                try {
                    t.sleep(100); // další kontrola fronty
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            } else {
                session.doWork(new Work() {
                    @Override
                    public void execute(Connection connection) throws SQLException {
                        try {
                            PreparedStatement ps = connection.prepareStatement("INSERT INTO data_data (Data_channelId,Data_nodeAddress,Data_subsystemId,data) VALUES (?,?,?,?)");
                            int pocet = data.size();
                            for (int i = 0; i < pocet; i++) {
                                Data item = data.get(0);
                                try {
                                    ps.setByte(1, item.getGlobal_id().getChannelId());
                                    ps.setShort(2, item.getGlobal_id().getNodeAddress());
                                    ps.setInt(3, item.getGlobal_id().getSubsystemId());
                                    ps.setDouble(4, item.getData().get(0));
                                    ps.addBatch();
                                } catch (SQLException e) {
                                    e.printStackTrace();
                                }
                                data.remove(0);
                            }
                            ps.executeBatch();
                            System.out.println(System.currentTimeMillis() + " Commited: " + pocet);

                        } catch (SQLException e) {
                            e.printStackTrace();
                        }
                    }
                });
                session.clear();

                try {
                    t.sleep(100); // Zjistit, zda je úspornější nechat větší frontu, nebo ne
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }

When I do not use session from hibernate but cerate another one simple Connection con = DriverManager.getConnection(... then it works fine.
Thanks for your help guys.

A: Many inserts in sequence causes hibernate to slow down gradually. This is because the rows you insert stays in the session until the session is closed or  session is flushed and clear.
I am unable to understand the clearly why did you code in this way, but I would suggest you to call session.flush() and session.clear() inside the for loop after regular intervals. For example if you want to keep batch size as 20 and number of records are 10000, then call flush and clear methods after every 20 records fetched. This will drastically increase the performance.


text:
Q: Add Gesture Reconizer Outside UItableView Inside ContentOffSetView I have added content offset to my UITableView.
For better positioning of my Table and now, I would like to dismiss my UITableView When User taps on the Content Offset Part of My table view.
How can i add this?
Strictly i dont want to add anymore views above the table in my screen.

Have done like Reference to the answer
https://stackoverflow.com/a/39062209/5215474

A: Without seeing exact code, I would do the following:
Add a UIGestureRecognizer to UITableView
Use a combination of scroll position and the point touched in screenspace to determine if a touch happened where you want.


text:
Q: Get entities by passing just the name of the entity I'm using entity framework, and I need to get a list of entities only by passing the name of the entity.
Example:
string tableName = "PRODUCT";

List<tableName> myList = (from prod in dbContext.tableName
                          select prod).ToList();

What I can't get to do, is that, using the table name (string) to make a EF query (or LINQ).
I'm trying to get this to work by using Reflection or EntityDataModel, but I just can't.

A: Have you tried something like this (source):
var table = context.ExecuteStoreQuery<ResultTableTemplate>("SELECT ... FROM " + tableName);


text:
Q: Drag and drop stored procedure on .dbml file(VS 2010) and upon saving it creates another designer1.cs file In my project, I have a data-access layer that contains .dbml file(named test.dbml) used to drag and drop stored procedures and tables. Two days ago when I drag and drop the stored procedure onto my test.dbml file. Upon saving it creates another test.designer1.cs class and the old test.designer.cs class remains unchanged. I use visual studio 2010 and it was very weird for me. I've checked my rights on the folder which contains my project but all seems ok because two days earlier it was working fine and suddenly it happened. I Google it but find no solution so I decided to write this question.

A: At-last i've solved it myself.........and i am going to share it that what i have done. my dbml file name was test.dbml having test.dbml.layout and test.designer.cs files now the problem was when ever i drag and drop stored procedure or table it creates a new designer file with name test.desginer1.cs and when i build data-ccess layer it gives me hell of errors my brain was out at that time and with angry face i delete the test.designer.cs (original file) from the solution after that there was only one file test.designer1.cs which i renamed from test.designer1.cs to test.designer.cs and build data-access layer and i was wondered that it was build successfully. this solve my problem however there are other points as well to keep in mind

*

*make sure your dbml files should not be read-only

*you have full access to write file on disk (means check your rights on directory where your solution is placed)


text:
Q: Biased coin check How many trials are needed to decide with 50% confidence that a coin is biased?
I suspect there is some missing information. Any ideas / pointers?

A: This is  a "hypothesis testing" problem of roughly standard shape. However, the figure of $50\%$ makes no practical sense at all in this context.
We have the null hypothesis $H_0$ that says the coin is unbiased, and the alternate hypothesis $H_1$ that says the coin is biased. The test is two-sided, since the alternate hypothesis makes no reference to the direction of the bias.
Suppose that we toss the coin $n$ times. We will reject the null hypothesis in favour of the alternate hypothesis if, assuming the coin is fair, the proportion of heads we got would happen less than $50\%$ of the time.
Let $n=2$ and suppose that we reject the null hypothesis if we get $2$ heads or $2$ tails. With a fair coin, this would happen exactly $50\%$ of the time. So perhaps $n=2$ is the intended answer. However, a more sensible answer (to a quite unreasonable question) is to take $n=3$, and to reject the null hypothesis if we get $3$ heads or $3$ tails. Then, when the null hypothesis is true, we will reject it with probability $\frac{1}{8}+\frac{1}{8}$, which is under $50\%$.
Remark: Traditionally, one rejects the null hypothesis $H_0$ in favour of $H_1$ if, on the hypothesis that $H_0$ is true, the experimental result has probability $\lt 5\%$ of happening. Or else one may use the more stringent $1\%$ criterion. The figure of $50\%$ makes no practical sense: obviously one would not reject the hypothsis that a coin is fair if we got $3$ heads or $3$ tails.


text:
Q: php replacing text in a template engine we have a situation where we have a template file like the following
<?php
  $tpl = '

This is the header

    {if "IS VALID"}

The value is valid
      {if "IS NUMBER"}
        and it is a number
      {/if}

    {/if}
 ';

  $is_valid = false;
  $is_number = true;

  if ($is_valid){
    $tpl = preg_replace('/\{if "IS VALID"\}(.*)\{\/if\}/sU','\1',$tpl);
  }else{
    $tpl = preg_replace('/\{if "IS VALID"\}(.*)\{\/if\}/sU','',$tpl);
  }

  if ($is_number){
    $tpl = preg_replace('/\{if "IS NUMBER"\}(.*)\{\/if\}/sU','\1',$tpl);
  }else{
    $tpl = preg_replace('/\{if "IS NUMBER"\}(.*)\{\/if\}/sU','',$tpl);
  }

  echo $tpl;
?>

The problem is that the first replacement, replaces all way to the FIRST {/if} block. We want it to replace the matching {/if}, that is, take into consideration the nesting of {if}s.
What is the most efficient way to accomplish this?
Thank you in advance!

A: Put this statment first
if ($is_number){
    $tpl = preg_replace('/\{if "IS NUMBER"\}(.*)\{\/if\}/sU','\1',$tpl);
  }else{
    $tpl = preg_replace('/\{if "IS NUMBER"\}(.*)\{\/if\}/sU','',$tpl);
  }

Your have to check the deepest level fisrt like that it will not be overwriten by others
EDIT:
If you remove 'U' option your regexp will take the latest closing {/if}:
$tpl = preg_replace('/\{if "IS VALID"\}(.*)\{\/if\}/s','\1',$tpl);

$tp1 will contain:
{if "IS VALID"}

The value is valid
{if "IS NUMBER"}
and it is a number
{/if}

witch shoul math your others statment


text:
Q: Convert afterSubmit script to Worfkflow Action Script? We have a custom script on our Sales Order that sets the Shipping Address to match the Location field in the header when the user submits the order. We're not using Cash Sales (long story) or POS. These are standard sales orders with Netsuite Basic. We have a decent amount of counter sales and our employees need the ability to quickly enter an order for a cash customer without having to add a shipping address every time. They choose "Customer Pick Up" from the Shipping Method dropdown, click Save, the script sees that option was chosen and it updates the address. This has been working great. We just installed Avatax, and it does NOT like this setup. It needs the Shipping Address selected on the order BEFORE we click Save on the order. I was hoping I could use a workflow that would trigger on field change/sourcing and run that script instead of waiting for the Save. But I can't figure out how to do it. I would be fine with a button or other mechanism as well - I just need a way to quickly set the Shipping Address to match the Location's address prior to saving the order. I started looking into converting this script to a Workflow Action Script so I can call it from a workflow, but I'm lost..
var salesOrderUE = {

    afterSubmit :function (type) {
        if (type == 'create' || type == 'edit') {
            var salesOrder = nlapiLoadRecord(nlapiGetRecordType(), nlapiGetRecordId(), { recordmode: 'dynamic'});
            var customerPickUp = salesOrder.getFieldValue('shipmethod')
            if (customerPickUp == '16853') {
                var location = salesOrder.getFieldValue('location');
                var locationRec = nlapiLoadRecord('location', location);
                salesOrder.setFieldValue('shipaddresslist', -2);
                var subrecord = salesOrder.createSubrecord('shippingaddress');
                subrecord.setFieldValue('country', locationRec.getFieldValue('country'));
                subrecord.setFieldValue('isresidential', 'F');
                subrecord.setFieldValue('attention', locationRec.getFieldValue('attention'));
                subrecord.setFieldValue('addressee', locationRec.getFieldValue('addressee'));
                subrecord.setFieldValue('addr1', locationRec.getFieldValue('addr1'));
                subrecord.setFieldValue('addr2', locationRec.getFieldValue('addr2'));
                subrecord.setFieldValue('city', locationRec.getFieldValue('city'));
                subrecord.setFieldValue('state', locationRec.getFieldValue('state'));
                subrecord.setFieldValue('zip', locationRec.getFieldValue('zip'));
                subrecord.commit();
                salesOrder.setFieldValue('shipaddress', locationRec.getFieldValue('addr1') +
                        '\n' + locationRec.getFieldValue('city') + ' ' + locationRec.getFieldValue('state') + ' ' + locationRec.getFieldValue('zip') + '\n'+
                        locationRec.getFieldValue('country'));

                nlapiSubmitRecord(salesOrder, true, true);
            }
        }
    }
}

A: Huge shoutout to @battk on Slack. They walked me through the whole process of converting this to a Client script, and using the Field Changed Function to run it.
Here's the updated code: (I still need to edit the if statement to check for location == null)
function setCPUshipto(type, name, linenum) {
  if (name !== "shipmethod" || nlapiGetFieldValue("shipmethod") !== "16853")
  {
        return;
  }

  var locationId = nlapiGetFieldValue("location");
  var locationRec = nlapiLoadRecord("location", locationId);
  var subrecord = nlapiCreateSubrecord("shippingaddress") || nlapiEditSubrecord("shippingaddress")
  subrecord.setFieldValue("country", locationRec.getFieldValue("country"));
  subrecord.setFieldValue("isresidential", "F");
  subrecord.setFieldValue("attention", locationRec.getFieldValue("attention"));
  subrecord.setFieldValue("addressee", locationRec.getFieldValue("addressee"));
  subrecord.setFieldValue("addr1", locationRec.getFieldValue("addr1"));
  subrecord.setFieldValue("addr2", locationRec.getFieldValue("addr2"));
  subrecord.setFieldValue("city", locationRec.getFieldValue("city"));
  subrecord.setFieldValue("state", locationRec.getFieldValue("state"));
  subrecord.setFieldValue("zip", locationRec.getFieldValue("zip"));
  subrecord.commit();

}


text:
Q: Firefox 54 Stopped Trusting Self-Signed Certs With the recent upgrade of Firefox 54, my self-signed localhost SSL certificate stopped being trusted.
I've been using a Firefox AutoConfigure script to install this certificate, and the technique has been working successfully for several years.  Firefox uses its own certificate store, cert8.db which contains the certificate, verified using Firefox Preferences, Advanced, Certificates, View Certificates, Authorities.
This is reproducible on both MacOS as well as Windows.  I've attached a sample certificate for reference.  This is identical to one we would install.
What changed in Firefox 54?  I've reviewed the changelog and can't find anything specific to how it trusts certificates.
Edit: Link to Firefox bug that most likely introduced this change: firefox #1294580
-----BEGIN CERTIFICATE-----
MIID/DCCAuSgAwIBAgIEDZj+fTANBgkqhkiG9w0BAQsFADCBmjELMAkGA1UEBhMC
VVMxCzAJBgNVBAgTAk5ZMRIwEAYDVQQHEwlDYW5hc3RvdGExGzAZBgNVBAoTElFa
IEluZHVzdHJpZXMsIExMQzEbMBkGA1UECxMSUVogSW5kdXN0cmllcywgTExDMRww
GgYJKoZIhvcNAQkBFg1zdXBwb3J0QHF6LmlvMRIwEAYDVQQDEwlsb2NhbGhvc3Qw
HhcNMTcwMjEyMDMzMjEwWhcNMzcwMjEyMDMzMjEwWjCBmjELMAkGA1UEBhMCVVMx
CzAJBgNVBAgTAk5ZMRIwEAYDVQQHEwlDYW5hc3RvdGExGzAZBgNVBAoTElFaIElu
ZHVzdHJpZXMsIExMQzEbMBkGA1UECxMSUVogSW5kdXN0cmllcywgTExDMRwwGgYJ
KoZIhvcNAQkBFg1zdXBwb3J0QHF6LmlvMRIwEAYDVQQDEwlsb2NhbGhvc3QwggEi
MA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQCemwdWhvytOwhsRyEo/9ck3nKP
oBvMdkaiXKbMWlYZfYyb/EsJzw/LiEqGGhflWjneQLcgq0nuTtRaA9cm/vgPtVRX
OHewJeYBI2C4avJyjdFfQYHJKxuLi3nwmZ5JwcDm04H6SADwdyQuYB4AFr32uY5D
3id0gyDV+EX9sSOPThtdBpEbaBcFmAdAGdQUCzSJyi4Yu6UkIs7OPBHp9lOvm8VQ
r6ZVnqdFEXmxgpgMS0sQwDwZnBB3hFcVmE/sYy+2gV/h+yvRUjgqwC/SoLh9f4D0
eG19E3OEmsSyFM9K2Wl4ltOE/Aq1KFm7dPw34nDKxYcVDpm6JczWycbCi4zjAgMB
AAGjSDBGMCUGA1UdEQQeMByCCWxvY2FsaG9zdIIPbG9jYWxob3N0LnF6LmlvMB0G
A1UdDgQWBBT3Qs6/qQSmunLIGKQxz3GBO+RgIzANBgkqhkiG9w0BAQsFAAOCAQEA
lVI3sWr6wTtVtc7gsV9Kk99xNOUm5W2kp/Ot5CHvUIw68Ar1WIiouWT9BbjkvFc+
QpbtqKhluTdHI1/JP44r7A8qMApyYQLhw3AS/WTzRoOBOECJk3hYgGBIxAaoqvKY
HKCOULTqkoX8pgNhYobebn/BpeoSvXW+oxT21y7ElE01eMtrLsqXKaN5FODxVzJq
7jatxCaRZCy2Ki3R0cB5ZMIVvWSDeT1TLgh5UKWdldNsTdTNhbQSdm8ayU0uj4fH
tKqwh9lKvrBJiawghmADjZjeNEQzIJfjznF/soqVZnRNZO/phDH327lDE2UcD1IN
k4BqNRJmz5lrQeYz8GcfYA==
-----END CERTIFICATE-----

A: As @tresf and @Zombaya have stated, Firefox requires two certificates:

*

*An authority certificate

*A development certificate

The authority certificate is used to sign the development certificate.  The development certificate is bound to an HTTP port.  The web server listens to that port for requests.
Windows Development Environment
Other answers explain what to do in Java and Unix environments.  Here's what I do in my Windows development environment.  This creates certificates trusted by Firefox, Chrome, and Internet Explorer:
Override DNS with an entry in C:\Windows\System32\drivers\etc\hosts file.
127.0.0.1  dev.brainstorm.com

Create the authority and development certificates and store them in the local machine certificate store using PowerShell.  Substitute "Brainstorm" with your company name and DNS entry.  Run PowerShell as an administrator.
# Create authority certificate.
# TextExtension adds the Server Authentication enhanced key usage and the CA basic contraint.
$authorityCert = New-SelfSignedCertificate `
    -Subject "CN=Brainstorm CA,OU=IT,O=Brainstorm Certificate Authority,C=US" `
    -KeyAlgorithm RSA `
    -KeyLength 4096 `
    -KeyUsage CertSign, CRLSign, DigitalSignature, KeyEncipherment, DataEncipherment `
    -KeyExportPolicy Exportable `
    -NotBefore (Get-Date) `
    -NotAfter (Get-Date).AddYears(10) `
    -HashAlgorithm SHA256 `
    -CertStoreLocation "Cert:\LocalMachine\My" `
    -FriendlyName "Brainstorm CA" `
    -TextExtension @("2.5.29.37={text}1.3.6.1.5.5.7.3.1", "2.5.29.19={critical}{text}ca=1")

# Create development certificate.
# Sign it with authority certificate.
# TextExtension adds the Server Authentication enhanced key usage.
$devCert = New-SelfSignedCertificate `
    -Subject "CN=Brainstorm,OU=Application Development,O=Brainstorm,C=US" `
    -DnsName dev.brainstorm.com `
    -KeyAlgorithm RSA `
    -KeyLength 4096 `
    -KeyUsage DigitalSignature, KeyEncipherment, DataEncipherment `
    -KeyExportPolicy Exportable `
    -NotBefore (Get-Date) `
    -NotAfter (Get-Date).AddYears(10) `
    -HashAlgorithm SHA256 `
    -CertStoreLocation "Cert:\LocalMachine\My" `
    -FriendlyName "Brainstorm" `
    -TextExtension @("2.5.29.37={text}1.3.6.1.5.5.7.3.1") `
    -Signer $authorityCert

# Export authority certificate to file.
$directory = "C:\Users\Erik\Documents\Temp\Certificates\"
if(!(test-path $directory))
{
New-Item -ItemType Directory -Force -Path $directory
}
$authorityCertPath = 'Cert:\LocalMachine\My\' + ($authorityCert.ThumbPrint)
$authorityCertFilename = $directory + "Authority.cer"
Export-Certificate -Cert $authorityCertPath -FilePath $authorityCertFilename

# Import authority certificate from file to Trusted Root store.
Import-Certificate -FilePath $authorityCertFilename -CertStoreLocation "Cert:\LocalMachine\Root"

# Delete authority certificate file.
Remove-Item -Path $authorityCertFilename

Grant developer permission to host a website and service at specific URLs and ports (via IIS Express).  Use standard SSL port for website, use another port for service.  Why?  IIS Express cannot simultaneously host two applications on same port differentiated by host name.  They must use different ports.
netsh http add urlacl url=https://dev.brainstorm.com:443/ user="Erik"
netsh http add urlacl url=https://dev.brainstorm.com:44300/ user="Erik"

If you need to remove developer permission to host website at URL:
netsh http delete urlacl url=https://dev.brainstorm.com:443/
netsh http delete urlacl url=https://dev.brainstorm.com:44300/

List the certificates in Local Computer store.
Get-ChildItem -path "Cert:\LocalMachine\My"

Copy the thumbprint of the development certificate (not the authority certificate).
List the certificates bound to HTTP ports.  (IIS Express configures ports 44300 - 44399 with its own SSL certificate.)
netsh http show sslcert

Copy the Application ID (it's the same for all IIS Express ports 44300 - 44399).  Replace the website and service ports already bound by IIS Express with our development certificate (the certhash is the thumbprint from above).  You may need to run netsh first, then enter http command, then enter add sslcert... command.
netsh http add sslcert hostnameport=dev.brainstorm.com:443 certhash=FE035397A4C44AB591A1D9D4DC0B44074D0F95BA appid={214124cd-d05b-4309-9af9-9caa44b2b74a} certstore=my
netsh http add sslcert hostnameport=dev.brainstorm.com:44300 certhash=FE035397A4C44AB591A1D9D4DC0B44074D0F95BA appid={214124cd-d05b-4309-9af9-9caa44b2b74a} certstore=my

If you need to unbind certificates from HTTP ports:
netsh http delete sslcert hostnameport=dev.brainstorm.com:443
netsh http delete sslcert hostnameport=dev.brainstorm.com:44300

In Visual Studio, configure the service's launchSettings.json file (in Properties folder):
{
  "iisSettings": {
    "windowsAuthentication": false,
    "anonymousAuthentication": true,
    "iisExpress": {
      "applicationUrl": "https://dev.brainstorm.com:44300/",
      "sslPort": 44300
    }
  },
  "profiles": {
    "Default": {
      "commandName": "IISExpress",
      "use64Bit": true
    }
  }
}

In Visual Studio, configure the website's launchSettings.json file (in Properties folder):
{
  "iisSettings": {
    "windowsAuthentication": false,
    "anonymousAuthentication": true,
    "iisExpress": {
      "applicationUrl": "https://dev.brainstorm.com/",
      "sslPort": 443
    }
  },
  "profiles": {
    "Default": {
      "commandName": "IISExpress",
      "launchBrowser": true,
      "use64Bit": true
    }
  }
}

Configure IIS Express (in hidden .vs/config folder):
<sites>
  <site name="Website" id="1" serverAutoStart="true">
    <application path="/">
      <virtualDirectory path="/" physicalPath="%IIS_SITES_HOME%\WebSite" />
    </application>
    <bindings>
      <binding protocol="https" bindingInformation="*:443:dev.brainstorm.com" />
    </bindings>
  </site>
  <site name="Service" id="2">
    <application path="/">
      <virtualDirectory path="/" physicalPath="%IIS_SITES_HOME%\IIS Service" />
    </application>
    <bindings>
      <binding protocol="https" bindingInformation="*:44300:dev.brainstorm.com" />
    </bindings>
  </site>
  <siteDefaults>
    <logFile logFormat="W3C" directory="%IIS_USER_HOME%\Logs" />
    <traceFailedRequestsLogging directory="%IIS_USER_HOME%\TraceLogFiles" enabled="true" maxLogFileSizeKB="1024" />
  </siteDefaults>
  <applicationDefaults applicationPool="Clr4IntegratedAppPool" />
  <virtualDirectoryDefaults allowSubDirConfig="true" />
</sites>

In Firefox, navigate to about:config and set the security.enterprise_roots.enabled parameter to true.

A: Inspired by the answer of @tresf and based largely on the blogpost How to Create Your Own SSL Certificate Authority for Local HTTPS Development by
Brad Touesnard, I created a set of commands using openssl.
# Generate the root key
openssl genrsa -des3 -out myCA.key 2048

# Generate a root-certificate based on the root-key
openssl req -x509 -new -nodes -key myCA.key -sha256 -days 1825 -out myCA.pem

# Generate a new private key
openssl genrsa -out example.com.key 2048

# Generate a Certificate Signing Request (CSR) based on that private key
openssl req -new -key example.com.key -out example.com.csr

# Create a configuration-file
echo \
"authorityKeyIdentifier=keyid,issuer
basicConstraints=CA:FALSE
keyUsage = digitalSignature, nonRepudiation, keyEncipherment, dataEncipherment
subjectAltName = @alt_names

[alt_names]
DNS.1 = example.com
"> example.com.conf

# Create the certificate for the webserver to serve
openssl x509 -req -in example.com.csr -CA myCA.pem -CAkey myCA.key -CAcreateserial \
-out example.com.crt -days 1825 -sha256 -extfile example.com.conf

How to use these files
1. Let your CA be trusted by your browser/keychain
Add myCa.pem to your browser/keychain to trust certificates signed by your new root certificate
2. Sign requests with your certificate
Add example.com.crt and example.com.key to the configuration of your webserver to sign requests to your domain

A: To mimic the CA-chain requirements mandated by Firefox 54, the following is required:

*

*Keypair marked as a Root-CA, capable of generating an SSL certificate.

*Second keypair marked for SSL which obtains a chained certificate from Root-CA

To illustrate how this is done with Java keytool including the steps to create private keystores:
# Create a Root-CA private keystore capable of issuing SSL certificates
keytool -genkeypair -noprompt -alias my-ca -keyalg RSA -keysize 2048 -dname CN=localhost -validity 3650 -keystore .\my-ca.jks -storepass pass77 -keypass pass77 -ext ku:critical=cRLSign,keyCertSign -ext bc:critical=ca:true,pathlen:1

# Export the Root-CA certificate, to be used in the final SSL chain
keytool -exportcert -alias my-ca -keystore .\my-ca.jks -storepass pass77 -keypass pass77 -file .\my-ca.crt -rfc -ext ku:critical=cRLSign,keyCertSign -ext bc:critical=ca:true,pathlen:1

# Create a container SSL private keystore (external localhost.foo.bar dns entry optional:IE11 domain intranet policy)
keytool -genkeypair -noprompt -alias my-ssl -keyalg RSA -keysize 2048 -dname CN=localhost -validity 3650 -keystore .\my-ssl.jks -storepass pass77 -keypass pass77 -ext ku:critical=digitalSignature,keyEncipherment -ext eku=serverAuth,clientAuth -ext san=dns:localhost,dns:localhost.foo.bar -ext bc:critical=ca:false

# Create a certificate signing request (CSR) from our SSL private keystore
keytool -certreq -keyalg RSA -alias my-ssl -file .\my-ssl.csr -keystore .\my-ssl.jks -keypass pass77 -storepass pass77

# Issue an SSL certificate from the Root-CA private keystore in response to the request (external localhost.foo.bar dns entry optional)
keytool -keypass pass77 -storepass pass77 -validity 3650 -keystore .\my-ca.jks -gencert -alias my-ca -infile .\my-ssl.csr -ext ku:critical=digitalSignature,keyEncipherment -ext eku=serverAuth,clientAuth -ext san=dns:localhost,dns:localhost.foo.bar -ext bc:critical=ca:false -rfc -outfile .\my-ssl.crt

# Import Root-CA certificate into SSL private keystore
keytool  -noprompt -import -trustcacerts -alias my-ca -file my-ca.crt -keystore my-ssl.jks -keypass pass77 -storepass pass77

# Import an SSL (chained) certificate into keystore
keytool -import -trustcacerts -alias my-ssl -file my-ssl.crt -keystore my-ssl.jks -keypass pass77 -storepass pass77 -noprompt

Once this is done, only the Root-CA certificate needs to be trusted by Firefox, and can be imported using the GUI or via AutoConfig script.
The SSL server must be restarted using the new SSL private keystore, which will contain the chain of trust to work via SSL.
Since my-ssl.jks contains the entire chain of trust my-ca.jks, my-ca.crt, my-ssl.crt and my-ssl.csr can all safely be deleted (assuming my-ca.crt has been imported properly)

A: What you'll probably want to do is generate another self-signed certificate with the same subject, issuer, and public key as the one you're trying to trust. However, instead of end-entity extensions, you'll want to specify that it's a CA certificate with "basicConstraints:cA" and that it can issue certificates with "keyUsage:cRLSign,keyCertSign". It might also be a good idea to add a nameConstraints extension to restrict it to only apply to a certain set of domains. If you add that certificate to Firefox's trust DB, everything should work as before.