text:
Q: do fortran functions always copy the results of the retun value into the accepting variable? mac osx catalina (latest)
gfortran 9.2
fortran standard "gnu"

Through something like the code below, I came to understand that, at least in this case, that within the function get_number the result value is constructed, and then results are copied over to the receiving variable.  Probably I've also done a no-no by having a pointer target a local variable inside that function, but perhaps the compiler was being nice to me by not deallocating a local variable so my pointer was still okay.
My question is, is this how all function calls behave, namely that the value, whether a simple type or a complex type, is constructed in memory, and then the values are copied over and the original result is thrown away?  I was under the impression that the variable receiving the value of the function call was just given the memory of the constructed result.
Suppose I felt that lots of memory copying was wasteful, or suppose as in the code below that it breaks my code, and I wanted to avoid it when doing many many function calls.  Is the solution to replace them with subroutine calls? But I like function calls.  If memory copying is what happens normally, is there a way to avoid memory copying when doing function calls?
module nums
  type number
     real :: n
  end type number

  type number_parent
     type(number), pointer :: p
   contains
     procedure, pass(this) :: get_number
  end type number_parent

contains

  function get_number(this) result(n)
    class(number_parent) :: this
    type(number), allocatable, target :: n
    allocate(n)
    n%n = 1.0
    this%p => n
  end function get_number

end module nums

program main
  use nums
  implicit none

  type(number) :: n
  type(number_parent) :: np

  n = np%get_number()

  print *, n%n
  print *, np%p%n

  n%n = n%n + 1.0

  print *, n%n
  print *, np%p%n

end program main

program output
> ./a.out
   1.00000000
   1.00000000
   2.00000000
   1.00000000

A: I understood your question is about a thing called return value optimization and you mainly were thinking about simple variables, non-pointer, non-allocatable. My answer will only touch these. I will also assume no advanced derived type features like polymorphism and finalization.
I will also assume you use the function only in a simple assignment. Of course, functions can appear in many complicated expressions in general.
When you return a simple variable from a function
   integer :: ext

   ext = func(1)

 contains

   integer function func(loc) result(res)
     res = loc + 1
   end function

  end

then what conceptually happens is that a local variable is used for the return value res and its value will be copied to the outer variable after the assignment.
In practice, if a separate variable will indeed be used, it will be allocated on the stack (that costs nothing, not just almost nothing, really nothing). Heap may be used for large objects (mostly arrays) and compilers often have settings for that, but normal variables will be on the stack. Then, when the function returns, the value is copied to the location of the outer variable ext and the stack pointer is reset (that just means some other function or subroutine will use that memory later).
The copying can indeed cost something and it may or may not be negligible. compilers will very often be able to optimize this and make the function to use the outer variable ext directly for its result variable res so that no copying is necessary. However, to see whether it is or is not happening you will have to check the machine code/assembly (or, if available, any intermediate representation) generated by the compiler. It may vary depending on the optimization level (-O1, -O2, -O3) and on the exact context of the function call in the source code.


text:
Q: How do I use the output of an ls command in an if statement in a bash shell I want to check if only one instance of a file exists before going on to process that file.
I can check how many instances exist using this command:
ls -l $INPUT_DIR/${INPUT_FILE_PREFIX}cons*.csv.gz | wc -l;

However, when I go to use this within an if statement, I am warned that the ls: command not found.
if [ls -l $INPUT_DIR/${INPUT_FILE_PREFIX}cons*.csv.gz | wc -l = '1']
 then
 echo "Only 1 File Exists";
fi

I've tried adding a semicolon at the end of the ls command and enclosing it in square brackets - neither of these yielded any results.
I very rarely have to do any Shell scripting, and I suspect this a very basic error, so any help would be much appreciated.

A: Change your if condition as below:
if [ "$(ls -l $INPUT_DIR/${INPUT_FILE_PREFIX}cons*.csv.gz | wc -l)" = "1" ]

*

*There need to be a space after [ and before ]

*Running the command within $() will invoke a subshell and run the command.

*Placing the $() within double-quotes will avoid error thrown in case of empty output.

A: You were almost there:
if [ $(ls $INPUT_DIR/${INPUT_FILE_PREFIX}cons*.csv.gz 2>/dev/null | wc -l) == 1 ]
 then
 echo "Only 1 File Exists";
fi

evaluates the result and compares with double equals. Also, put spaces before and after square brackets.
Also, filter out the case where no file matches (avoids no such file or directory error)
Note: you don't even need the -l option. When outputting to a non-interactive terminal (i.e a file or a pipe), ls issues 1 line per file. You can also force it with -C1 option. You'll gain 3 nanoseconds (at least :)) not performing extra stat calls to get date, size, etc.. which are not needed.

A: You will want to do something like this:
if [[ $(ls -l $INPUT_DIR/${INPUT_FILE_PREFIX}cons*.csv.gz | wc -l) == '1' ]]; then
  # Something
fi

The $(command) syntax captures the output. I am not sure if the equal comparison is correct thought, but according to this stackoverflow it is.

A: Few subtleties that the previous answers didn't cover:
if [ "$(ls -1d $INPUT_DIR/${INPUT_FILE_PREFIX}cons*.csv.gz 2>/dev/null | wc -l)" -eq 1 ]; then
  echo 'Only 1 file';
fi

First use -1d (one, dee) will do 2 things: it won't expand directories (if you have a directory name ending in .csv.gz for some odd reason) and will only display 1 entry per line with no (total header) header or other output that is uneeded.  Redirecting stderr to /dev/null will prevent the ls: cannot access z*: No such file or directorymessage.
Finally, you should either use = or -eq as == is not compatible with zsh if using the single [ test operator (if you care about bash/zsh compatibility).  Also BSD/OSX wc puts some leading space in the output so you might want to pipe to awk to strip out so the comparison can be made.

A: I hope "-l" option is not needed for checking the presence of files. We can also use command substitution to get the same result.
#!/bin/bash
if [ `ls -l $INPUT_DIR/${INPUT_FILE_PREFIX}cons*.csv.gz | wc -l` -eq 1 ];then
    echo "One exists"
fi

redpajama_set_name: RedPajamaStackExchange


text:
Q: Regex to find all the words with at least 3 specific characters I am solving a problem using regular expressions in which I need to find all the words in a sentence having at least 3 specific characters. Let's say I have following data:
Define a pattern for selecting all words containing at least three times the character a (including its uppercase variant A).

The example sentence for the test is:
Anastasia would like to have a banana split.

So what I have done is that I've compiled all the possible situations that I can face:

So far I have written a regular expression using pipes for the 4th and 6th situation and it works for the given text.
"\\b(\\b[Aa]{1}[^Aa\\W\\s]*[Aa]{1}[^Aa]*[Aa]{1,}\\w*\\b)|(\\b[^Aa\\W]*[Aa]{1}[^Aa\\W]*[Aa]{1}[^Aa\\W]*[Aa]{1,}\\w*\\b)"

*

*Am I doing it right?

*Is it efficient?

*Is there a concept in regular expressions that allow me to count for specific characters?

*I learnt in "Theory of Automata" that NFA/DFA are limited in a way that count can not be tracked. So do I have to use advanced turing machines?

A: That looks quite convoluted. I think it would be quicker and easier to start at a word boundary, and repeat a group that contains (zero or more non-A, non-space characters, followed by a single A character) 3 times, followed by more characters until you get to the next space:
\b(?:[^a ]*a){3}\w*

https://regex101.com/r/ZVxATc/2
(of course, make sure to use the case-insensitive flag so you don't have to spell out things like [aA])

A: How about /^([^a]*a){3}[^a]*$/.
This will find exactly 3 a characters in a string.
This can be seen working here, and I add a few test strings in the following:

const regex = /^([^a]*a){3}[^a]*$/;
const strings = ['abcabcabc', 'abcabc', 'abcabcabcabc', 'aaa', 'abab', 'ababa', 'a a a', 'a ba ba', 'a ab ab', 'a ab ab ab', 'b ab ab ab'];

for (let i = 0; i < strings.length; i++) {
  console.log(strings[i] + ": " + regex.test(strings[i]));
}

A: Here is a solution, that uses look ahead:
\b(?=([^ ]*a){3,})\w*\b

It starts at a word boundary, then creates a look ahead checking:
zero or more non Space chacacters followed by a 'a'. It repeats this 3 or more times.
Then it matches zero or more Word characters and finally a Word boundary.
You should use the 'IgnoreCase' flag.
Examples of match:
abcabcabc banana aaa aaabbaa

const regex = /\b(?=([^ ]*a){3,})\w*\b/;
const strings = ['abcabcabc', 'abcabc', 'abcabcabcabc', 'aaa', 'abab', 'ababa', 'a a a', 'a ba ba', 'a ab ab', 'a ab ab ab', 'b ab ab ab'];

for (let i = 0; i < strings.length; i++) {
  console.log(strings[i] + ": " + regex.test(strings[i]));
}


text:
Q: Sencha Touch 2 PhoneGap issue for 4.0.x I have an Android HTC Amaze and an Android HTC Desire. My Sencha Touch 2 apps wrapped by PhoneGap work excellent for the Desire but they refuse to load on the HTC Amaze 4.0.3.
I'm getting this kind of errors in log -

08-24 17:08:37.577: E/chromium(16106): external/chromium/net/disk_cache/stat_hub.cc:190: [0824/170837:ERROR:stat_hub.cc(190)] StatHub::Init - App "appname" isn't supported.

A: Try to update cordova version as latest one.
cordova -v
npm install -g cordova

current recent cordova version is 8.x.
and please check which cordova plugins are installed.

A: PhoneGap gives errors while compiling for production builds. Rather than PhoneGap use IONIC framework which under the hood run different libraries of PhoneGap but does not return such errors.
https://ionicframework.com/
If your application is in javascript use IONIC 1.

A: If you are using WebView mecanism in your app, try to change for Crosswalk.
In my case, replacing interaction with android.webkit.WebView with crosswalk fixed the issue.
I don't really understand why, but Crosswalk is known for "Uniform runtime across all devices and so you don't have to deal with runtime differences on different devices running different versions of the OS. "

A: Try updating your cloud build and re-install it on your Android 4.0.
Seems it needs to be re-installed for the new permissions to be noticed by the Android OS.


text:
Q: Use =MAX on external workbook using certain variables I'm a total noob when it comes to code, so apologies for what you're about to see.
I have a workbook with a list of orders from suppliers, along with their value. I'm trying to create a macro that does the following, but I'm running into a brick wall.

I want the macro to check cell B of the active row, then access they hyperlinked workbook and output the =MAX value in cell D of the active row.
Sub Find_PO_Total()

Range("Supplier" & ActiveCell.Row).Select

If Range("Supplier" & ActiveCell.Row) = "Supplier1, Supplier2" Then
Range("Value" & ActiveCell.Row).Max ("_hyperlink_here_!G1:G709")

ElseIf Range("Supplier" & ActiveCell.Row) = "Supplier3" Then
    Range("Value" & ActiveCell.Row).Max ("_hyperlink_here_!H1:H709")

ElseIf Range("Supplier" & ActiveCell.Row) = "Supplier4, Supplier5" Then
    Range("Value" & ActiveCell.Row).Max ("_hyperlink_here_!I1:I709")

End If
End Sub

A: i have made the required changes to your code
Sub Find_PO_Total()

If Cells(ActiveCell.Row, 2).Value = "Supplier1" Or Cells(ActiveCell.Row, 2).Value = "Supplier2" Then
    Cells(ActiveCell.Row, 4).Value = "=MAX(_hyperlink_here_!G1:G709)"

ElseIf Cells(ActiveCell.Row, 2).Value = "Supplier3" Then
    Cells(ActiveCell.Row, 4).Value = "=MAX(_hyperlink_here_!H1:H709)"

ElseIf Cells(ActiveCell.Row, 2).Value = "Supplier4" Or Cells(ActiveCell.Row, 2).Value = "Supplier5" Then
    Cells(ActiveCell.Row, 4).Value = "=MAX(_hyperlink_here_!I1:I709)"
End If

End Sub


text:
Q: Looping user based filters to pull out products MYSQL Currently, i have a system set that displays products from a database based on what filters are set in a control panel.
It loops like this:
1. Begin loop
2. Pick Filter
3. Search product database for product matching the filter AND search term
4. Return a table row of products matching these terms
5. End Loop

This works fine except for the load times. Because it has to loop through all the products for each filter with search term the time involved only gets higher with each filter added on the back end.
My question: Is there a smaller way to write in say.. any array of the filters into one mysql statement? like this:
SELECT FROM products Where A line matches one of the array of filters AND search term?

The other reason i need this is because currently it's pullin gout duplicate product rows. While i've nastily hidden the doubles with javascript, it's not exactly good to keep it like this.
Currently, this is the code being used. If anyone can offer any suggestions as to how the best way to do this is, i'm all ears.
//connect and fetch all entries from the filter table

$filterproducts = $dbh->prepare("SELECT * FROM table_filter_selection ORDER BY filter ASC");
$filterproducts->execute();
$filterselect = $filterproducts->fetchAll();
//for each entry found loop through a second loop

foreach($filterselect as $rows){
$wildcard = "%" . $rows['filter'] . "%";
//make a variable into a regex of the row

$query = "PRODUCT_NAME LIKE '%" . implode("%' AND PRODUCT_NAME LIKE '%", $breakdown) . "%'";
$sqlstring= "SELECT * FROM product_list WHERE PRODUCT_NAME  LIKE :filterfind AND " . $query;
$searchproducts = $dbh->prepare($sqlstring);
$searchproducts->bindParam(":filterfind", $wildcard, PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$searchproducts->execute();

//search for all products that match the wildcard AND the current filter

foreach($searchproducts as $rows2){

//for every one found, make a row.
echo "
" . $rows2['SKU'] ." ". $rows2['COMMENTS'] . "". $rows2['PRODUCT_NAME'] ."	". $rows2['QTY'] . "
";
   }
}

I have editted to include a very quick mock-up of the code I'm using.

A: save the filters in an array. then use a loop to make a sql stament. like this:
$query= "SELECT * FROM products ";
$filters= 'Where '; //Sets a varible for fileters.
foreach($filters as $key=$value) //Loop threw each filter
{
    $filters.= $key . '= ' . $value . 'AND ';
}
rtrim('AND '); //Remove extra 'AND' from end of filters string
$query.= $filters;

Now you will have to adjust the code depending on how your filters a stored. and the rtrim() may need tweeking.


text:
Q: Can't Forward X11 from ubuntu 14.04 I'm trying to forward x11 traffic through ssh tunnel from my ubuntu 14.04 to another ubuntu machine in my lan, i connect to ubuntu ssh server using ssh -X myuser@172.16.31.2 ,it connects but when i try to open an app like opera it shows
(opera:13046): Gtk-WARNING **: cannot open display:

i enabled x11 forwarding and tcp forwarding in sshd_config file but still the same thing even when i connect to localhost to debug same thing
ssh -X -v localhost

shady@shady:~$ opera

(opera:13046): Gtk-WARNING **: cannot open display:

i cant figure out why, i read on a forum that lightdm blocks TCP by default but i'm using gdm and even editing the flag under
/etc/gdm/custom.conf

[security]
DisallowTcp = Flase

didn't helped i'm pretty much lost now and there isn't enough threads to troubleshoot this on my own.This is my

/etc/ssh/sshd_config

# Package generated configuration file
# See the sshd_config(5) manpage for details

# What ports, IPs and protocols we listen for
Port 22
# Use these options to restrict which interfaces/protocols sshd will bind to
#ListenAddress ::
#ListenAddress 0.0.0.0
Protocol 2
# HostKeys for protocol version 2
HostKey /etc/ssh/ssh_host_rsa_key
HostKey /etc/ssh/ssh_host_dsa_key
HostKey /etc/ssh/ssh_host_ecdsa_key
HostKey /etc/ssh/ssh_host_ed25519_key
#Privilege Separation is turned on for security
UsePrivilegeSeparation yes

# Lifetime and size of ephemeral version 1 server key
KeyRegenerationInterval 3600
ServerKeyBits 1024

# Logging
SyslogFacility AUTH
LogLevel INFO

# Authentication:
LoginGraceTime 120
PermitRootLogin without-password
StrictModes yes

RSAAuthentication yes
PubkeyAuthentication yes
#AuthorizedKeysFile %h/.ssh/authorized_keys

# Don't read the user's ~/.rhosts and ~/.shosts files
IgnoreRhosts yes
# For this to work you will also need host keys in /etc/ssh_known_hosts
RhostsRSAAuthentication no
# similar for protocol version 2
HostbasedAuthentication no
# Uncomment if you don't trust ~/.ssh/known_hosts for RhostsRSAAuthentication
#IgnoreUserKnownHosts yes

# To enable empty passwords, change to yes (NOT RECOMMENDED)
PermitEmptyPasswords no

# Change to yes to enable challenge-response passwords (beware issues with
# some PAM modules and threads)
ChallengeResponseAuthentication no

# Change to no to disable tunnelled clear text passwords
#PasswordAuthentication yes

# Kerberos options
#KerberosAuthentication no
#KerberosGetAFSToken no
#KerberosOrLocalPasswd yes
#KerberosTicketCleanup yes

# GSSAPI options
#GSSAPIAuthentication no
#GSSAPICleanupCredentials yes

X11Forwarding yes
X11DisplayOffset 10
PrintMotd no
PrintLastLog yes
TCPKeepAlive yes
#UseLogin no

#MaxStartups 10:30:60
#Banner /etc/issue.net

# Allow client to pass locale environment variables
AcceptEnv LANG LC_*

#Subsystem sftp /usr/lib/openssh/sftp-server

# Set this to 'yes' to enable PAM authentication, account processing,
# and session processing. If this is enabled, PAM authentication will
# be allowed through the ChallengeResponseAuthentication and
# PasswordAuthentication.  Depending on your PAM configuration,
# PAM authentication via ChallengeResponseAuthentication may bypass
# the setting of "PermitRootLogin without-password".
# If you just want the PAM account and session checks to run without
# PAM authentication, then enable this but set PasswordAuthentication
# and ChallengeResponseAuthentication to 'no'.
UsePAM yes
Subsystem sftp internal-sftp
Match group ftpaccess
ChrootDirectory %h
AllowTcpForwarding yes
ForceCommand internal-sftp

i have a sftp setup with a nologon chroot user but i think that is irrelevant in this problem
and when i did

ssh -X -v localhost

to debug it showed this output
shady@shady:~$ ssh -X -v localhost
OpenSSH_6.6.1, OpenSSL 1.0.1f 6 Jan 2014
debug1: Reading configuration data /etc/ssh/ssh_config
debug1: /etc/ssh/ssh_config line 19: Applying options for *
debug1: Connecting to localhost [127.0.0.1] port 22.
debug1: Connection established.
debug1: identity file /home/shady/.ssh/id_rsa type 1
debug1: identity file /home/shady/.ssh/id_rsa-cert type -1
debug1: identity file /home/shady/.ssh/id_dsa type -1
debug1: identity file /home/shady/.ssh/id_dsa-cert type -1
debug1: identity file /home/shady/.ssh/id_ecdsa type -1
debug1: identity file /home/shady/.ssh/id_ecdsa-cert type -1
debug1: identity file /home/shady/.ssh/id_ed25519 type -1
debug1: identity file /home/shady/.ssh/id_ed25519-cert type -1
debug1: Enabling compatibility mode for protocol 2.0
debug1: Local version string SSH-2.0-OpenSSH_6.6.1p1 Ubuntu-2ubuntu2.3
debug1: Remote protocol version 2.0, remote software version OpenSSH_6.6.1p1 Ubuntu-2ubuntu2.3
debug1: match: OpenSSH_6.6.1p1 Ubuntu-2ubuntu2.3 pat OpenSSH_6.6.1* compat 0x04000000
debug1: SSH2_MSG_KEXINIT sent
debug1: SSH2_MSG_KEXINIT received
debug1: kex: server->client aes128-ctr hmac-md5-etm@openssh.com none
debug1: kex: client->server aes128-ctr hmac-md5-etm@openssh.com none
debug1: sending SSH2_MSG_KEX_ECDH_INIT
debug1: expecting SSH2_MSG_KEX_ECDH_REPLY
debug1: Server host key: ECDSA af:06:10:6a:e2:d2:bc:67:3b:48:e1:ca:ba:96:99:ca
debug1: Host 'localhost' is known and matches the ECDSA host key.
debug1: Found key in /home/shady/.ssh/known_hosts:2
debug1: ssh_ecdsa_verify: signature correct
debug1: SSH2_MSG_NEWKEYS sent
debug1: expecting SSH2_MSG_NEWKEYS
debug1: SSH2_MSG_NEWKEYS received
debug1: Roaming not allowed by server
debug1: SSH2_MSG_SERVICE_REQUEST sent
debug1: SSH2_MSG_SERVICE_ACCEPT received
debug1: Authentications that can continue: publickey,password
debug1: Next authentication method: publickey
debug1: Offering RSA public key: /home/shady/.ssh/id_rsa
debug1: Authentications that can continue: publickey,password
debug1: Trying private key: /home/shady/.ssh/id_dsa
debug1: Trying private key: /home/shady/.ssh/id_ecdsa
debug1: Trying private key: /home/shady/.ssh/id_ed25519
debug1: Next authentication method: password
shady@localhost's password:
debug1: Authentication succeeded (password).
Authenticated to localhost ([127.0.0.1]:22).
debug1: channel 0: new [client-session]
debug1: Requesting no-more-sessions@openssh.com
debug1: Entering interactive session.
debug1: Sending environment.
debug1: Sending env LANG = en_IN
Welcome to Ubuntu 14.04.3 LTS (GNU/Linux 3.13.0-74-generic x86_64)

 * Documentation:  https://help.ubuntu.com/

Last login: Fri Jan 15 02:37:54 2016 from 172.16.31.5
shady@shady:~$

A: This is a real issue for a newbie like me, and i'm amazed that there isn't any thread about this topic in this website,i just wasted several hours of my life for this tiny configuration i don't know why they did it but by default sshd only listens on localhost for X11 traffic we have to explicitly tell ubuntu sshd daemon to accept any host by adding this line in

/etc/ssh/sshd_config

X11UseLocalHost no

I got this idea from CentOS ssh configuration, and here i was tweaking gdm and stuff, ubuntu didn't even mention this in official ssh documentation anyways this may help someone like me.


text:
Q: iphone - Making a MKMap black and white There's a thread that asks the same thing, Black and white overlay for an MKMapView
but I have my doubts if the answer will work, no-one claimed to get it done.
A filter is a function applied to the pixels of an image, so making a Overlay with a monochrome filter will only be applied to the Overlay, not to the map.
Am I right?If not please tell me so, If Im right do you know any other way to make a MKMap to appear in B&W?
Thanks.


text:
Q: Symfony2 - ajax/long pool/WS events Доброго времени суток.
Преамбула
Есть пользователь. Иногда этого пользователя в режиме "онлайн" необходимо уведомлять о каком-либо событии, которое произошло. Например, получил новое сообщение, в его адрес оставили отзыв и т.д. Есть подобие RIA (Rich Internet Application)
Теперь по существу
Задача уведомлять об этих событиях пользователя (если он есть на сайте).
Думаю, что свой велосипед говорить не следует (в Symfony большое кол-во бандлов).
Может, кто-то сталкивался с подобной задачей и уже решил ее. Подскажите, пожалуйста, нужный бандл :)
Спасибо за внимание :)
A: На хабре была как-то статья по поводу WebSocket-ов http://habrahabr.ru/post/205934/
Но если вы будете их использовать, то далеко не все пользователи со старыми браузерами будут вам рады :)
VK, Facebook, etc. используют Ajax Long Polling. Не уверен, что найдете что-нибудь хорошее из готовых бандлов. Лучше пилить своё. Могу посоветовать модуль Nginx-а для push-а нотификаций клиенту https://github.com/slact/nginx_http_push_module


text:
Q: Возможно ли изменить системное приложение? Добрый день, есть системное android приложение которое использует камеру телефона REQUEST_CODE_PHOTO, возможно ли добраться до его исходного кода и соответственно как если это возможно ?

A: Для этого вам потребуется root-доступ.
При помощи root, Достаньте APK-файл системмного приложения, декомпилируйте его, и читайте его исходники сколько пожелаете.
Я предполагаю, что вы столкнетесь с другой проблемой - у системмных приложений есть разрешения, которые доступны только для системмных приложений.

UPD
Точно, на чтение открыта. Поэтому, рут доступ в общем не нужен


text:
Q: How to fix an "error MSB4068: The element  is unrecognized" when trying to create an migration in command line (Entity Framework) Command:
dotnet ef migrations add addListModel --project <path to the .csproj file>

Error:
 error MSB4068: The element <NDepend> is unrecognized, or not supported in this context.
Unable to retrieve project metadata. Ensure it's an MSBuild-based .NET Core project. If you're using custom BaseIntermediateOutputPath or MSBuildProjectExtensionsPath values, Use the --msbuildprojectextensionspath option.

Dotnet core version 2.1


text:
Q: When would I post something to Programmers instead of Stack Overflow and vice versa?
Possible Duplicate:
Choosing between Stack Overflow and Programmers Stack Exchange

I've read the descriptions of both Stack Exchange's "Programmers" and "Stack Overflow" sites.  But it is not clear to me when I should ask a question on Programmers instead of Stack Overflow.  With the exception of THIS question, so far everything I've asked has been (mostly) technical in nature and I've always asked on Stack Overflow.  But I see lots of technical questions in Programmers.
Does anyone have a good rule of thumb for knowing when to post where?

A: The FAQs for each site should be explanatory enough, but the short short version is

*

*When you have an actual programming problem to solve, like a piece of code that doesn't work or something you just can't figure out how to do

*

*ask it on Stack Overflow (FAQ)

*When you want to talk about topics relevant to programmers (ie., learning, careers, etc.) but not an actual programming problem

*

*ask on Programmers (FAQ)

*When you want to talk about how you might improve a piece of code

*

*ask on Code Review (still in beta) (FAQ)

*When you want to talk about Fight Club

*

*Take it to Meta (FAQ)


text:
Q: Trying to convert Python code to Pyspark code dictr_s = df_external['clean'].progress_apply(lambda x: ngrams_prod_desc(x, str(attribute_list)))

This is the python code in which "ngrams_prod_desc" function is taking two parameters

*

*String

*List

and "clean" has 2k number of rows which I want to enter one by one into the function
df_external['clean'] contains "string" type data
This function should return a dataframe
sample of code output
I am using this syntax to convert it :
upperCaseUDF = udf(lambda z:ngrams_prod_desc(z,attribute_list),StringType())

dictr_s = df_external.withColumn(['clean1'].upperCaseUDF(col("clean"))).show(truncate=False)

which is throwing this error :
AttributeError: 'list' object has no attribute 'upperCaseUDF'


text:
Q: Bring process to foreground I have a process (which reads and writes to terminal type) that has been exec'd by a background process. I can see it using ps.
Trying to bring it to foreground, this is what I attempted:
int main()

{

    FILE* fd = popen("pidof my_program","r");

    // ...
    // Some code to get the pid of my_program as mpid
    //...

    printf("pid of my_program is %d",mpid);
    signal(SIGTTOU, SIG_IGN);
    setpgid(mpid,0); // Set program group id to pid of process
    tcsetpgrp(0,mpid); // Give it terminal stdin access
    tcsetpgrp(1,mpid); // Give it terminal stdout access
    return 0;
}

It isn't working though. Can someone help me on this?
Thanks.

A: You could do it the "soft" way, by calling the shell command fg and pass it the pid (adviced).
If you want to code it, this is how fg/bg is coded into bash (don't don't don't):
static int
fg_bg (list, foreground)
     WORD_LIST *list;
     int foreground;
{
  sigset_t set, oset;
  int job, status, old_async_pid;
  JOB *j;

  BLOCK_CHILD (set, oset);
  job = get_job_spec (list);

  if (INVALID_JOB (job))
    {
      if (job != DUP_JOB)
    sh_badjob (list ? list->word->word : _("current"));

      goto failure;
    }

  j = get_job_by_jid (job);
  /* Or if j->pgrp == shell_pgrp. */
  if (IS_JOBCONTROL (job) == 0)
    {
      builtin_error (_("job %d started without job control"), job + 1);
      goto failure;
    }

  if (foreground == 0)
    {
      old_async_pid = last_asynchronous_pid;
      last_asynchronous_pid = j->pgrp;  /* As per Posix.2 5.4.2 */
    }

  status = start_job (job, foreground);

  if (status >= 0)
    {
    /* win: */
      UNBLOCK_CHILD (oset);
      return (foreground ? status : EXECUTION_SUCCESS);
    }
  else
    {
      if (foreground == 0)
    last_asynchronous_pid = old_async_pid;

    failure:
      UNBLOCK_CHILD (oset);
      return (EXECUTION_FAILURE);
    }
}

A: When you have a process that is in the background or suspended, you can move it to the foreground with
the fg command. By default, the process most recently suspended or moved to the background moves to
the foreground. You can also specify which pid it is using to make it foreground.


text:
Q: When a user opens a team site in sharepoint online it should display name Is there a way to show the user name when user logins to team site it should Show welcome the user with current user name
Welcome CurrentUser

A: There is no OOB way to do that, you can use JSOM to achieve it.
An example for you:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript">

var loginName = "";
var userid = _spPageContextInfo.userId;
GetCurrentUser();

function GetCurrentUser() {
var requestUri = _spPageContextInfo.webAbsoluteUrl + "/_api/web/getuserbyid(" + userid + ")";

var requestHeaders = { "accept" : "application/json;odata=verbose" };

$.ajax({
  url : requestUri,
  contentType : "application/json;odata=verbose",
  headers : requestHeaders,
  success : onSuccess,
  error : onError
  });
}

function onSuccess(data, request) {
    var loginName = data.d.Title;
   // alert("Hello " + loginName);

    // to set the "hello username" into the page
    document.getElementById("welcomediv").innerHTML = "Welcome " + loginName;
    }

function onError(error) {
  alert(error);
  }

</script>

<div id="welcomediv">

If you want to show it on a modern page, you need to install modern script editor web part, then add the above code into it.
About installing modern script editor web part, you can refer to:
SharePoint | Online | Best Practice | install Modern Script Editor Web Part for SharePoint Online Modern Site.

A: It already displays the current user's photo in the upper right hand corner. If you want a customized welcome message, there is no oob method, but this can be done via code, either an SPFx web part or perhaps a custom SPFx extension.

A: I am not sure, there is OOB method available to get that. But you can use JSOM to get user display name and show it on page.
Below link may help to get started:
https://stackoverflow.com/questions/20981226/sharepoint-2013-get-current-user-using-javascript
If you are using classic experience, you can add Script editor webpart to add script on page.
If you are using Modern experience, you will need to either use SPFX or react-script-editor webpart available on Github.


text:
Q: Magento 2: Update Product Data Outside Magento with Tier Pricing I have below script for Update Product records with Tier Pricing.
I have already Product SKU in CSV. On basis of that fetching Product Id & Try to update Record.
$mysqli = mysqli_connect('localhost', 'root', '', 'magento2');

if (!$mysqli) {
    echo "Error: Unable to connect to MySQL." . PHP_EOL;
    echo "Debugging errno: " . $mysqli->connect_errno . PHP_EOL;
    echo "Debugging error: " . $mysqli->connect_error . PHP_EOL;
    exit;
}

$file_name = "final_sheet.csv";

// MAGENTO START
include('app/bootstrap.php');

use Magento\Framework\App\Bootstrap;

$bootstrap = Bootstrap::create(BP, $_SERVER);
$objectManager = $bootstrap->getObjectManager();

$state = $objectManager->get('Magento\Framework\App\State');
$state->setAreaCode('frontend');

if (($handle = fopen($file_name, "r")) !== FALSE) {
    $i = 0;
    while (($data = fgetcsv($handle, 0, ",")) !== FALSE) {
        $i++;

        if ($i > 1) {

            $_product = $objectManager->create('Magento\Catalog\Model\Product');
            $_productTierPrice = $objectManager->create('Magento\Catalog\Api\ProductTierPriceManagementInterface');

            $productSKU = $mysqli->real_escape_string(trim($data[0]));
            $productDesc = $mysqli->real_escape_string(trim($data[1]));
            $productTierPrice = $mysqli->real_escape_string(trim($data[2]));
            $productTierPrice = (!empty($productTierPrice)) ? number_format($productTierPrice, 4) : '';

            $sql = "SELECT entity_id FROM catalog_product_entity WHERE  sku = '" . $productSKU . "';";
            $result = $mysqli->query($sql);

            if ($result->num_rows > 0) {
                while ($row = $result->fetch_array()) {
                    $entityId = $row['entity_id'];
                }

                echo "Product Id. " . $entityId . "
";

                $_product->load($entityId);
                $_product->setDescription($productDesc);

                $_product->save();

                $getData = $_product->getData();
                $_product->setData($getData);
                $_product->save();

                $sku = $productSKU; //Product sku
                $customerGroupId = 2; //Wholsaler group id
                $price = $productTierPrice;
                $qty = 1;

                $_productTierPrice->add($sku, $customerGroupId, $price, $qty);

                $_productTierPrice->save();
            } else {
                echo "Product Not Found";
                exit;
            }

            if ($i > 3)
                break;
        }
    }
    fclose($handle);
}

mysqli_close($mysqli);

echo 'Done';

It's saving product description data in Database, but not showing in Admin.

A: // MAGENTO START
include('app/bootstrap.php');

use Magento\Framework\App\Bootstrap;

$bootstrap = Bootstrap::create(BP, $_SERVER);
$objectManager = $bootstrap->getObjectManager();

$state = $objectManager->get('Magento\Framework\App\State');
$state->setAreaCode('frontend');

$file_name = "final_sheet.csv";

if (($handle = fopen($file_name, "r")) !== FALSE) {
    $i = 0;
    while (($data = fgetcsv($handle, 0, ",")) !== FALSE) {
    $i++;

    if ($i > 1) {

        $_product = $objectManager->create('Magento\Catalog\Model\Product');
        $_productTierPrice = $objectManager->create('Magento\Catalog\Api\ProductTierPriceManagementInterface');

        $productSKU = trim($data[0]);
        $productDesc = trim($data[1]);
        $productTierPrice = trim($data[2]);
        $productTierPrice = (!empty($productTierPrice)) ? number_format($productTierPrice, 4) : '';

        $entityId = $_product->getIdBySku($productSKU);

        if ($entityId) {

            echo "Product Id. " . $entityId . "
";

            $_product->load($entityId);
            $_product->setStoreId(0);
            $_product->setDescription($productDesc);

            $_product->save();

            $sku = $productSKU; //Product sku
            $customerGroupId = 2; //Wholsaler group id
            $price = $productTierPrice;
            $qty = 1;

            $_productTierPrice->add($sku, $customerGroupId, $price, $qty);

        } else {
            echo "Product Not Found";
            exit;
        }

        if ($i > 3)
            break;
    }
    }
    fclose($handle);
}

echo 'Done';


text: Q: Add authentication before installing any apk in android I need to know that is there any other app or source code in android who can restrict or authenticate before installing other apk. Means if some one knows device pattern and try to install any apk, before installing apk need to confirm with some password or pattern to go forward. Thanks


text:
Q: shorthand syntax for a radiobuttonlist SelectedItem.Text only if one is selected? Sorry, difficult to give the question a proper title?
I'm basically appending a lot of text together to form the email body in my application from several radiobuttonlists in my web form. So my code looks like this:
StringBuilder body = new StringBuilder();
body.Append("For question1:   " + ((rblQuestion1.SelectedIndex > -1) ?  rblQuestion1.SelectedItem.Text : "") + "

");

So my question is do I have to use the following syntax:
((rblQuestion1.SelectedIndex > -1) ?  rblQuestion1.SelectedItem.Text : "")

Where what I really want is:
(rblQuestion1.SelectedIndex > -1) ?  rblQuestion1.SelectedItem.Text

I don't need the empty string alternative if false, if you understand my point.
It's just me being a bit pedantic with my code really. Thanks in advance.

A: The only alternative I see when you per se need to check for
rblQuestion1.SelectedIndex > -1

is the following:
if (rblQuestion1.SelectedIndex > -1)
  someStringVar = rblQuestion1.SelectedItem.Text;

There is no other solution because conditional statements need to be formatted in the following pseudo-code:
toBeAssigned = boolean expression ? assigner if true : assigner if false;


text:
Q: ¿Cómo retornar la respuesta de un PHPMailer en la página del formulario de envío? Tengo una página .html donde dentro contiene un form action="fichero.php" como sería lo normal. Me funciona, y me envía el correo.
Ahora bien, necesito que dependiendo de si el retorno del php es trueo false salga en la misma página del form un pop-up que informe si el correo se ha enviado correctamente o no.
Actualmente me sale el log del cliente y un echo que le he configurado.
¿Cómo lo hago?
(Me sirve un ejemplo simple para saber qué estructura debo implementar para hacer esto)
Gracias de antemano y un saludo.

A: Creo que la mejor forma seria hacerlo con AJAX, en lugar de enviar la petición a través del form, enviarla con Javascript.
Algo asi:

function enviarPeticion() {
  var data = new FormData(document.querySelector('form'));
  var url = '/peticion.php';
  var xhr = new XMLHttpRequest();
  xhr.open('POST', url, true);
  xhr.onload = function () {
    var res = this.responseText;
    if(res === 'true'){
      alert('Enviado');
    }else{
      alert('Error');
    }
  };
  xhr.send(data);
}


text:
Q: Mejorar Wifi y LAN de Ubuntu Actualmente, la velocidad máxima para la LAN de ubuntu viene de 100MB a pesar de que la tarjeta de red es de 1000 y la velocidad del servicio de internet es de 400MB alguna idea de como puedo abordar este problema.

A: Segun el foro de AskUbuntu usuarios que reportaron el mismo problema lo solucionaron actualizando un parámetro del GRUB con los siguientes comandos:
sudo nano /etc/default/grub

# Buscar y editar la siguiente línea pcie_aspm=off

GRUB_CMDLINE_LINUX_DEFAULT="splash pcie_aspm=off"

sudo update-grub


text:
Q: getting 24 hours difference in android I want to call an activity which downloads the data if the data has not been downloaded in last 24 hours.But I have no idea how to do this.Can some one help me out?

A: At first save the Datatime then start a Scheduling background task using Alarm Manager and check the datatime with first save datatime. if datatime different is 24 hours then run the download activity.
Scheduling background task using Alarm Manager
Thanks

A: What about the modification time of the files you have downloaded?
http://developer.android.com/reference/java/io/File.html#lastModified()
Or you could save the last download time in the SharedPreferences:
http://developer.android.com/guide/topics/data/data-storage.html#pref
I don't think using the AlarmManager is the right way to go, this would force users to download the files or data every 24 hours, even if they are not using your app for a some days or maybe weeks. This can be very annoying, i think you should not use the AlarmManager but just check for a download update when users start the app.


text:
Q: Flutter App Crash since Flutter / Android Studio Update I upgraded Android Studio to 3.3.0 and Flutter to 1.0.0.
The first thing that happened, was all the packages were highlighted as missing, and I upgraded all the versions to the latest versions
Packages:
**Pubspec.yaml**

cupertino_icons: ^0.1.2
url_launcher: 3.0.2 > updated to 5.0.0
firebase_admob: 0.5.5 > updated to 0.8.0
path_provider: 0.4.1 > updated to 0.5.0
flutter_html: 0.7.0 > updated to 0.9.3
geolocator: 1.7.0 > updated to 2.1.1
sqflite: ^1.1.0
http: ^0.12.0+1 > this was added cos it started showing as missing since the update.

I then updated to the latest versions for the other files
**In /android/build.gradle**
distributionUrl=https\://services.gradle.org/distributions/gradle-4.10.1-all.zip

**In /android/build.gradle**
buildscript {
ext.kotlin_version = '1.3.20'
repositories {
    google()
    jcenter()
}

dependencies {
    classpath 'com.android.tools.build:gradle:3.3.0'
    classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
}
}

**In /android/app/build.gradle**
dependencies {
implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.2'
androidTestImplementation 'com.android.support.test.espresso:espresso-
core:3.0.2'
}

With the changes made, I ran the app in the emulator and it immedietly crashed with no error messages
Launching lib\main.dart on Android SDK built for x86 in debug mode...
Initializing gradle...
Resolving dependencies...
Gradle task 'assembleDebug'...
Built build\app\outputs\apk\debug\app-debug.apk.
Application finished.

I then tried reverting all the versions, including the packages in pubspec.yaml back to the previous ones.
com.android.tools.build:gradle:3.1.4
gradle-4.4-all.zip
ext.kotlin_version = '1.2.61'
implementation "org.jetbrains.kotlin:kotlin-stdlib-jre7:$kotlin_version"

This still crashed the app instantly on running.
At this point, I deleted the virtual devices and created new ones, and I also tried running it on my own phone plugged in. Same result - the app crashes instantly.
As a last resort, I completely removed all the packages and re-made the main.dart page to a simple page that doesn't use any packages - and even this crashes instantly.
However, if I created a new Flutter app, it is able to run.
What am I missing? Is there somewhere else that I need to change the version to the older one that I've missed?

A: I compared file-by-file a new flutter app with mine, and finally realised the entire kotlin directory was missing from android/app/src/main/kotlin
I copied over the directory from an earlier version, and it works now.

A: An other case could be that your device was too old to support the AndroidX environment (api >= 28).
androidX support is needed to include path_provider (perhaps firebase_admob too)
Personnally, I replace the call to path_provider (getApplicationDocumentsDirectory) with sqflite (getDatabasesPath) and I remove path_provider. My app is running good on Marshmallow without path_provider.


text:
Q: Authenticating as an Application Where you type these things?:
curl -F type=client_cred \
     -F client_id=your_app_id \
     -F client_secret=your_app_secret \
     https://graph.facebook.com/oauth/access_token

In other words, how I'll do it in PHP? Or manually?
source

A: Use the PHP curl function or use the PHP+Javascript example on the page you link to...


text:
Q: I am Having issue with google Spreadsheet, how can I convert the 6.50min to 6.30 min enter image description here
In this I am not able to convert the time from 6.50 to 6.30 can anyone help. I have used this formula =SUM(D10-C10)*24 pls help
Please click the above link for image.

A: Since you are calculating the total number of hours it looks like it is just right to show 6.5 hours since you are displaying it in a decimal float format.
Unless you want to display it as hours & minutes (HH:MM) format you can do so just by =SUM(D10-C10), then manually set the formatting of the cell to HH:MM by highlighting the cell then going to Format tab > Number > Custom date and time > Scroll down and select the time format which is in your case you want it to be in HH:MM

HOUR:MINUTE

It will show as 6:30, as shown in below screenshot:

or if you really want it to be displayed in decimal float format you can also manually do so in the Format tab > Number > Custom number format > In the box you can just type "h"."mm".

*

*Refer to this link for more details on Date and Number Formats: https://developers.google.com/sheets/api/guides/formats

A: I suggest you to not use h.mm if you want to have "numeric" hours. You will never be sure how many minutes you have.
On the contrary, when you see 6.10 you will be able to know that you have 6 hours and 6 minutes (1/10th of an hour), and when you see 6:30 you will be able to know that you have 10 minutes.

A: Another alternative that can also be used

=TEXT(D10-C10,"h.mm")

I used the example image to create my own sheet and run some test based on the formatting nature of the Google Sheets. It gives me the exact 6.30 that you need, without the need of making too many changes on the formats.
You can review it over my testing Sheet


text:
Q: Планировщик задач artisan laravel Запустил на своем хосте команду php artisan shedule:run, но он выполняетcя только один раз.
Мой kernel
$schedule->command('xml:parse')->everyMinute();

Проект висит на виртуальном хостинге, подскажите как можно решить эту проблему.

A: Планирование выполнения задач на сервере

*

*Выполнением запланированных в Laravel заданий занимается команда schedule:run

*В свою очередь её непосредственным вызовом занимается планировщик задач, той системы, на которой развернут проект.
Если проект работает на unix'е (с вероятностью 99.9% так и будет), то этим будет заниматься CRON
Соответственно, Вам необходимо в CRON запланировать выполнение команды schedule:run.
Для этого необходимо знать путь к папке в которой расположен ваш проект.
Допустим, что этой папкой является /var/www/project/
Нам необходимо отредактировать файл с расписанием CRON'а
Сам файл находится как правило по пути: /etc/crontab
Отредактировать в терминале его можно с помощью nano
nano /etc/crontab

И там вам нужно добавить следующую строку
* * * * * cd /var/www/project && php artisan schedule:run >> /dev/null 2>&1

Разберем что там происходит:

*

** * * * *  - это значит каждую минуту, каждый час, каждый день и т.д. (то есть ежеминутно)

*cd /var/www/project - это переход в папку вашего проекта

*&& - данный оператор говорит, что команда справа должна выполниться вместе с левой, при условии что предыдущая команда завершилась усешно

*php artisan schedule:run - выполняем команду schedule:run для запуска запланированных в даравел задач

*>> /dev/null 2>&1 - это мы перенаправляем поток вывода в виртуальное устройство, которое как черное дыра поглатит весь вывод из команды без возможности вернуть его обратно. В противном случае можете перенаправить поток в какой-то лог-файл

ВНИМАНИЕ!
НЕ ЗАБУДЬТЕ ЗАМЕНИТЬ /var/www/project НА ПУТЬ ДО ВАШЕГО ПРОЕКТА!

Планирование выполнения задач на локальном компьютере в среде разработки
В среде разработки на локальном компьютере как правило не требуется постоянное выполнение заданий
Их выполнение требуется, как правило, только при решении связанных с этими командами задач.
И для этого в Laravel есть команда:
php artisan schedule:work

Пока она запущена - планировщик Laravel будет выполнять запланированные задания

Источники:

*

*Запуск планировщика в производственной среде:
https://laravel.com/docs/9.x/scheduling#running-the-scheduler

*Запуск планировщика на локальной машине в среде разработки:
https://laravel.com/docs/9.x/scheduling#running-the-scheduler-locally


text:
Q: How can I debug why my built-in bluetooth is not working? I would like to see bluetooth devices over my computer. I have a Asus x79 Deluxe which supports Bluetooth 4.0. It would be nice if that worked under Linux.
I have installed the following packages:

*

*bluez-utils

*libopenobex1
I have blueman installed and clicked on "turn bluetooth on". After that, when I click on devices it does not see any. When I click on "Adapters" I get an empty popup.
What is the problem and how can I further investigate it / solve it?
My System
$ uname -a
Linux pc09 3.13.0-36-generic #63-Ubuntu SMP Wed Sep 3 21:30:07 UTC 2014 x86_64 x86_64 x86_64 GNU/Linux

$ cat /etc/issue
Linux Mint 17 Qiana \n \l

$ lspci | grep -i blu
$ lsusb | grep -i blu
$ lshw | grep -i blu
$ lsmod | grep -i blu
bluetooth             391136  10 bnep,rfcomm
$ hciconfig --all

$ dmesg | grep -i blue
[    3.746659] Bluetooth: Core ver 2.17
[    3.746667] Bluetooth: HCI device and connection manager initialized
[    3.746672] Bluetooth: HCI socket layer initialized
[    3.746673] Bluetooth: L2CAP socket layer initialized
[    3.746675] Bluetooth: SCO socket layer initialized
[    3.796894] Bluetooth: BNEP (Ethernet Emulation) ver 1.3
[    3.796898] Bluetooth: BNEP filters: protocol multicast
[    3.796904] Bluetooth: BNEP socket layer initialized
[    3.797018] Bluetooth: RFCOMM TTY layer initialized
[    3.797021] Bluetooth: RFCOMM socket layer initialized
[    3.797024] Bluetooth: RFCOMM ver 1.11

$ sudo hcitool scan
Device is not available: No such device

$ rfkill list
0: phy0: Wireless LAN
    Soft blocked: no
    Hard blocked: no
1: brcmwl-0: Wireless LAN
    Soft blocked: no
    Hard blocked: no

I am not sure, but I think the WLAN chipset BCM4352 is also the part that handles bluetooth.

A: I am afraid BCM4352 is not supported by current Linux kernel's b43 driver. I would suggest trying Dell's or Broadcom's proprietary drivers instead, see also this answer for same problem on an older version of Ubuntu.
If they provide a .deb package for Ubuntu 14, you'll likely be able to see the device with blueman and use it.
NOTE: it will affect your wifi functionality as well


text:
Q: Tensorflow GCP online Endpoint prediction instance Key and values format Running a time series analysis on Iowa liquor sales data.
I am able to train the model using TensorFlow and deployed it to an endpoint
As per the GCP docs, I am referring to this code sample to invoke an API endpoint for prediction:
https://github.com/googleapis/python-aiplatform/blob/master/samples/snippets/predict_custom_trained_model_sample.py
I am running into an issue where no matter how I enter instance values I am running into formatting errors.
currently the way I am calling the method is :
 predict_custom_trained_model_sample(
    project="XXXX",
    endpoint_id="YYY",
    location="us-central1",
    instance_dict={ "instances":[
                                    {
                                    "date" : '03-10-2021',
                                    "store_name" : "CENTRAL CITY LIQUOR, INC.",
                                    "category_name" : "IMPORTED DISTILLED SPIRIT SPECIALTY",
                                    "vendor_name" : "JINRO AMERICA INC",
                                    "item_description" : "JINRO CHAMISUL FRESH SOJU"
                                    }
                                ]})

The error I am getting :
InvalidArgument: 400 Failed to handle request. endpoint_id: xxxxx, deployed_model_id: xxxxx with error: `{
    "error": "Failed to process element: 0 key: instances of 'instances' list. Error: Invalid argument: JSON object: does not have named input: instances"
}`

I am trying to run the prediction on a single item value. Can someone point to the right syntax or if there are any other deeper issues to my problem?

A: From the example, I understand that the instance_dict contain only the array of instance and not the instances key
 predict_custom_trained_model_sample(
    project="XXXX",
    endpoint_id="YYY",
    location="us-central1",
    instance_dict=[
      {
        "date" : '03-10-2021',
        "store_name" : "CENTRAL CITY LIQUOR, INC.",
        "category_name" : "IMPORTED DISTILLED SPIRIT SPECIALTY",
        "vendor_name" : "JINRO AMERICA INC",
        "item_description" : "JINRO CHAMISUL FRESH SOJU"
      }
    ])

A: Can you try this instead? From looking at the code, looks like it only accepts one instance that needs to be a Dict:
 predict_custom_trained_model_sample(
    project="XXXX",
    endpoint_id="YYY",
    location="us-central1",
    instance_dict={
        "date" : '03-10-2021',
        "store_name" : "CENTRAL CITY LIQUOR, INC.",
        "category_name" : "IMPORTED DISTILLED SPIRIT SPECIALTY",
        "vendor_name" : "JINRO AMERICA INC",
        "item_description" : "JINRO CHAMISUL FRESH SOJU"
    })


text:
Q: Multiple measurements of a single datapoint: what to do with variability? I am interested in a general question about research design, but I will explain it on a specific example.
Suppose I want to determine if one group of people has higher heart rate than the other group. Let's consider two methods to do that, two scenarios:
Scenario 1: we get one measurement of heart rate from 5 people in each of the two groups. Then for each group we can calculate the mean and standard deviation, and run a t-test with that data to see if groups are different.
Scenario 2: we get several, let's say 3, measurements from each of 5 people in each of the two groups, then average the 3 measurements for each person and use it a single datapoint for this individual. Then proceed as in scenario 1.
I want to understand if the second scenario is valid. Such a design is commonly used and it seems to reduce the variability compared to the first scenario. But I am very concerned that in scenario 2, we are simply discarding, or ignoring, the intra-individual variability.
So is it ok to do that? What is the cost of this?
Can this lead to incorrect conclusions (false-positive, false-negative)?
Or maybe the conclusion has to formulated in a very specific way?
What exactly are we characterizing with this method?
Average heart rate of a person, as opposed to a random heart rate reading of a person? Is it what we should be interested from a biological standpoint?
Sorry, if the question is not totally clear, but it is not clear to me either, and may be you can point me in the right direction. Any thoughts are welcome.
Update: I just realized that there is a third scenario: start as second, but use each measurement (not each person) as a datapoint, which increases the number of observations 3-fold. What are the advantages or limitations of doing that?

A: Your concerns are legitimate.
Scenario 1 is valid, but unless you have a very large number of people in your group, your results won't reflect "real" difference or they might be biased. For example, the first time you take heart rate, the subject are stressed by the procedure and all have a very high heart rate. By taking more than one measurement, you reduce that bias.
Scenario 2 is better, altought by making a mean you lose information. You might be more precise in your evaluation of heart rate, but you won't take into consideration all the heart rates possible in the 2 groups.
I usually use scenario 3 but the way you describe the analysis is pseudoreplication. I recommend the classic ecological article of Hulbert, to read on the subject :
Hurlbert, S. H. 1984. Pseudoreplication and the design of ecological field experiments. — Ecol. Monogr. 54: 187-211.
Now, there is a way to use all the information and not being pseudoreplicated. You can use a mixed model (so basically, an ANOVA), with in the fixed terms the group and in the random term, the ID of the subject. I hope I used the correct terms, as sometimes I get mixed up. If someone see a mistake, please correct me.


text:
Q: Reason for CORS preflight request error If I receive this error when making a call to a third-party API service...

Response to preflight request doesn't pass access control check: No
  'Access-Control-Allow-Origin' header is present on the requested
  resource.

... is this something that the third-party needs to allow, as opposed to something I need to change with my request?

A: Yes this header needs to be included in the response from server. (Not in your request.)
Example from mozilla.org:

To allow any resource to access your resource, you can specify:
Access-Control-Allow-Origin: *
To allow https://developer.mozilla.org to access your resource, you
  can specify:
Access-Control-Allow-Origin: https://developer.mozilla.org


text:
Q: jquery fire event after timeout I've implemented auto page scrolling using the jQuery plugin datatables.
I'm attempting to add two buttons, one that stops the auto scrolling and one that starts it again.  I've gotten this working, but I want it to begin scrolling again if the page has been stopped for a period of time.  Here is what I have tried:
var refreshRate = 5;
var totalPages = 0;
var currentPage = 0;
var upTime = 0;

$('document').ready(function(){
var interval = window.setInterval('$("#start").click()',refreshRate);

    $("#start").click(function(){
        function start(){
            clearInterval(timeout);
            $("#stop").show();
            $("#start").hide();
            currentPage = table.api().page.info().page + 1;
            totalPages = table.api().page.info().pages;
            table.api().ajax.reload(function(json){

                if (currentPage != totalPages){
                    table.api().page('next').draw(false);
                }
                else{
                    table.api().page('first').draw(false);
                }
            });

            upTime = upTime + (refreshRate / 1000);
            clearInterval(interval);
            interval = setInterval('$("#start").click()', refreshRate);
        }
        start();
    });

    $("#stop").click(function(){
        $("#stop").hide();
        $("#start").show();
        timeout();

        clearInterval(interval);

    });

//call start on doc ready to auto start scrolling
    start();

    function timeout(){
        var timeout = window.setInterval(function(){

            start();
        }, 10000);
    }
});

As you can see I am attempting to call the start() function embedded within the button click after a 10 second timeout.  I am also getting a TypeError when I call start() at DOM ready to begin page scrolling.
Uncaught TypeError: object is not a function

But besides the error it scrolls as it should.
Any assistance?

A: You are having issues with function scope. Your code that called start towards the bottom did not have start in its scope since you defined it inside the click handler. Also, timeout was outside of the scope too, which would cause the interval to go on forever:
$('document').ready(function(){
    var timeout,
        interval = window.setInterval('$("#start").click()',refreshRate);
    function start(){
            clearInterval(timeout);
            $("#stop").show();
            $("#start").hide();
            currentPage = table.api().page.info().page + 1;
            totalPages = table.api().page.info().pages;
            table.api().ajax.reload(function(json){

                if (currentPage != totalPages){
                    table.api().page('next').draw(false);
                }
                else{
                    table.api().page('first').draw(false);
                }
            });

            upTime = upTime + (refreshRate / 1000);
            clearInterval(interval);
            interval = setInterval('$("#start").click()', refreshRate);
    }

    function timeout(){
        timeout = setInterval(function(){
            start();
        }, 10000);
    }

    $("#start").click(function(){
        start();
    });

    $("#stop").click(function(){
        $("#stop").hide();
        $("#start").show();
        timeout();
        clearInterval(interval);

    });

    //call start on doc ready to auto start scrolling
    start();
});


text:
Q: Changing the for loop to a matrix operation when calculating the RSI _compute_indicator is the function which the RSI is calculated with:
    def _compute_indicator(data_: pd.Series, period: int):
        clean_data = data_.dropna()
        delta = clean_data.diff()
        delta_up = delta.clip(lower=0)
        delta_down = delta.clip(upper=0).abs()
        avg_gain = pd.Series(
            np.full(len(delta_up), np.nan), index=delta_up.index.copy(), name=data_.name
        )
        avg_loss = pd.Series(
            np.full(len(delta_down), np.nan),
            index=delta_down.index.copy(),
            name=data_.name,
        )
        avg_gain[period] = delta_up[: period + 1].mean()
        avg_loss[period] = delta_down[: period + 1].mean()
        for i in range(period + 1, avg_gain.shape[0]):
            avg_gain.iloc[i] = (
                avg_gain.iloc[i - 1] * (period - 1) + delta_up.iloc[i]
            ) / period
            avg_loss.iloc[i] = (
                avg_loss.iloc[i - 1] * (period - 1) + delta_down.iloc[i]
            ) / period
        rs = avg_gain / avg_loss
        rsi_calc = 100 - (100 / (1 + rs))
        return rsi_calc

This is the Code where the function is implemented in:
    if isinstance(data, pd.DataFrame):
        indicator = data.apply(_compute_indicator, period=periods)
        indicator = indicator.reindex(data.index)

    else:
        indicator = _compute_indicator(data, periods)
        indicator = indicator.reindex(data.index)

    return indicator

The Code is checking in an If-Else Statement if it is an pd.Dataframe or a Series-
Question: How to change the for loop to something quicker? Maybe a Matrix operation?
for i in range(period + 1, avg_gain.shape[0]):
            avg_gain.iloc[i] = (
                avg_gain.iloc[i - 1] * (period - 1) + delta_up.iloc[i]
            ) / period
            avg_loss.iloc[i] = (
                avg_loss.iloc[i - 1] * (period - 1) + delta_down.iloc[i]
            ) / period

This is the part which is super slow. But I have no Idea how to make it quicker


text:
Q: Is it possible to mount Google Filestore in GAE Flexible custom runtime The documentation for Google Filestore only makes specific reference to using it with "Google Compute Engine and Kubernetes Engine instances".
Following the instructions here I have been successfully able to mount a Filestore share in a Compute Engine instance.
Is it possible to mount a Filestore share in a custom runtime (Docker container) that is running in a Google App Engine Flexible instance and if so what would be the best way to do it ?
Thanks

A: Yes, you could do it. But as the App Engine environment says:

Flexible environment VM instances are restarted on a weekly basis.
  During restarts, Google's management services apply any necessary
  operating system and security updates.
You always have root access to Compute Engine VM instances. By
  default, SSH access to the VM instances in the flexible environment is
  disabled. If you choose, you can enable root access to your app's VM
  instances.

But, the disk is ephemeral. So, each week the VM is restarted, the disk get's deleted. Also, you could enable debug, SSH into the VM and mount the Filestore client but once you disable debug, the VM get's restarted as a fresh new VM.
You could try by editing the Dockerfile of the Flexible enviroment to achieve this.


text:
Q: NSString - Unicode to ASCII equivalent I need to convert NSString in unicode to NSString in ASCII changing all local characters:
Ą to A,
Ś to S,
Ó to O,
ü to u,
And so on...
What is the simplest way to do it?

A: NSString *unicode = @"Chào mừng đến với Việt Nam.";
NSString *standard = [unicode stringByReplacingOccurrencesOfString:@"đ" withString:@"d"];
standard = [standard stringByReplacingOccurrencesOfString:@"Đ" withString:@"D"];
NSData *decode = [standard dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *ansi = [[NSString alloc] initWithData:decode encoding:NSASCIIStringEncoding];
NSLog(@"ANSI: %@", ansi);

A: -[NSString dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES].
All of the examples you gave are handled as you want.  Looks like characters with no obvious analog, such as ☃, go to '?'.

A: Ken answer will replace "æ" with "ae" and "ß" with "s", but won't replace ligatures œ, ij, ff, fi, fl, ffi, ffl, ſt, st, ...
An improved solution is to first insert additional lines of mapping to handle everything fine:
string = [string stringByReplacingOccurrencesOfString:@"Œ" withString:@"OE"];
string = [string stringByReplacingOccurrencesOfString:@"œ" withString:@"oe"];
string = [string stringByReplacingOccurrencesOfString:@"Đ" withString:@"D"];
string = [string stringByReplacingOccurrencesOfString:@"đ" withString:@"d"];
string = [string precomposedStringWithCompatibilityMapping];

NSData *data = [string dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *newString = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];

A: Objective C's NSASCIIEncoding only supports upto 127 , the character set you are looking for are beyond 127 in ASCII table.
NSASCIIStringEncoding
Strict 7-bit ASCII encoding within 8-bit chars; ASCII values 0…127 only.
Available in Mac OS X v10.0 and later.
Declared in NSString.h.

A: NSData *data = [decode dataUsingEncoding:[NSString defaultCStringEncoding]];
decode = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];

A: NSUTF8StringEncoding, and [NSSring UTF8String] was not working for me under Xcode 12.2
Here is a my custom NSString Category which works for all ASCII values 0..255 in objective c
Header-fle
#import <Cocoa/Cocoa.h>

@interface NSString (ASCIIEncode)

- (const char*)ASCIIEncode;

@end

Implementation
#import "NSString+ASCIIEncode.h"

@implementation NSString (ASCIIEncode)

- (const char*)ASCIIEncode {

    static char output[1024];

    // https://tools.piex.at/ascii-tabelle/
    // https://www.ionos.de/digitalguide/server/knowhow/ascii-american-standard-code-for-information-interchange/

    NSMutableArray *ascii = [NSMutableArray new];
// Hex
// 000                          Dez Hex
    [ascii addObject:@"\0"]; // 000 000 NUL
    [ascii addObject:@( 1)]; // 001 001 SOH
    [ascii addObject:@( 2)]; // 002 002 STX
    [ascii addObject:@( 3)]; // 003 003 ETX
    [ascii addObject:@( 4)]; // 004 004 EOT
    [ascii addObject:@( 5)]; // 005 005 ENQ
    [ascii addObject:@( 6)]; // 006 006 ACK
    [ascii addObject:@"\a"]; // 007 007 BEL
    [ascii addObject:@"\b"]; // 008 008 BS
    [ascii addObject:@( 9)]; // 009 009 TAB
    [ascii addObject:@"\n"]; // 010 00A LF
    [ascii addObject:@(11)]; // 011 00B VT
    [ascii addObject:@(12)]; // 012 00C FF
    [ascii addObject:@"\r"]; // 013 00D CR
    [ascii addObject:@(14)]; // 014 00E SO
    [ascii addObject:@(15)]; // 015 00F NAK
// 010
    [ascii addObject:@(16)]; // 016 010 DLE
    [ascii addObject:@(17)]; // 017 011 DC1
    [ascii addObject:@(18)]; // 018 012 DC2
    [ascii addObject:@(19)]; // 019 013 DC3
    [ascii addObject:@(20)]; // 020 014 DC4
    [ascii addObject:@(21)]; // 021 015 NAK
    [ascii addObject:@(22)]; // 022 016 SYN
    [ascii addObject:@(23)]; // 023 017 ETB
    [ascii addObject:@(24)]; // 024 018 CAN
    [ascii addObject:@(25)]; // 025 019 EM
    [ascii addObject:@(26)]; // 026 01A SUB
    [ascii addObject:@(27)]; // 027 01B ESC
    [ascii addObject:@(28)]; // 028 01C FS
    [ascii addObject:@(29)]; // 029 01D GS
    [ascii addObject:@(30)]; // 030 01E RS
    [ascii addObject:@(31)]; // 031 01F US
// 020
    [ascii addObject:@" "];  // 032 020 Space
    [ascii addObject:@"!"];  // 033 021
    [ascii addObject:@"\""]; // 034 022
    [ascii addObject:@"#"];  // 035 023
    [ascii addObject:@"$"];  // 036 024
    [ascii addObject:@"%"];  // 037 025
    [ascii addObject:@"&"];  // 038 026
    [ascii addObject:@"'"];  // 039 027
    [ascii addObject:@"("];  // 040 028
    [ascii addObject:@")"];  // 041 029
    [ascii addObject:@"*"];  // 042 02A
    [ascii addObject:@"+"];  // 043 02B
    [ascii addObject:@","];  // 044 02C
    [ascii addObject:@"-"];  // 045 02D
    [ascii addObject:@"."];  // 046 02E
    [ascii addObject:@"/"];  // 047 02F
// 030
    [ascii addObject:@"0"];  // 048 030
    [ascii addObject:@"1"];  // 049 031
    [ascii addObject:@"2"];  // 050 032
    [ascii addObject:@"3"];  // 051 033
    [ascii addObject:@"4"];  // 052 034
    [ascii addObject:@"5"];  // 053 035
    [ascii addObject:@"6"];  // 054 036
    [ascii addObject:@"7"];  // 055 037
    [ascii addObject:@"8"];  // 056 038
    [ascii addObject:@"9"];  // 057 039
    [ascii addObject:@":"];  // 058 03A
    [ascii addObject:@";"];  // 059 03B
    [ascii addObject:@"<"];  // 060 03C
    [ascii addObject:@"="];  // 061 03D
    [ascii addObject:@">"];  // 062 03E
    [ascii addObject:@"?"];  // 063 03F
// 040
    [ascii addObject:@"@"];  // 064 040
    [ascii addObject:@"A"];  // 065 041
    [ascii addObject:@"B"];  // 066 042
    [ascii addObject:@"C"];  // 067 043
    [ascii addObject:@"D"];  // 068 044
    [ascii addObject:@"E"];  // 069 045
    [ascii addObject:@"F"];  // 070 046
    [ascii addObject:@"G"];  // 071 047
    [ascii addObject:@"H"];  // 072 048
    [ascii addObject:@"I"];  // 073 049
    [ascii addObject:@"J"];  // 074 04A
    [ascii addObject:@"K"];  // 075 04B
    [ascii addObject:@"L"];  // 076 04C
    [ascii addObject:@"M"];  // 077 04D
    [ascii addObject:@"N"];  // 078 04E
    [ascii addObject:@"O"];  // 079 04F
// 050
    [ascii addObject:@"P"];  // 080 050
    [ascii addObject:@"Q"];  // 081 051
    [ascii addObject:@"R"];  // 082 052
    [ascii addObject:@"S"];  // 083 053
    [ascii addObject:@"T"];  // 084 054
    [ascii addObject:@"U"];  // 085 055
    [ascii addObject:@"V"];  // 086 056
    [ascii addObject:@"W"];  // 087 057
    [ascii addObject:@"X"];  // 088 058
    [ascii addObject:@"Y"];  // 089 059
    [ascii addObject:@"Z"];  // 090 05A
    [ascii addObject:@"["];  // 091 05B
    [ascii addObject:@"\\"]; // 092 05C
    [ascii addObject:@"]"];  // 093 05D
    [ascii addObject:@"^"];  // 094 05E
    [ascii addObject:@"_"];  // 095 05F
// 060
    [ascii addObject:@"`"];  // 096 060
    [ascii addObject:@"a"];  // 097 061
    [ascii addObject:@"b"];  // 098 062
    [ascii addObject:@"c"];  // 099 063
    [ascii addObject:@"d"];  // 100 064
    [ascii addObject:@"e"];  // 101 065
    [ascii addObject:@"f"];  // 102 066
    [ascii addObject:@"g"];  // 103 067
    [ascii addObject:@"h"];  // 104 068
    [ascii addObject:@"i"];  // 105 069
    [ascii addObject:@"j"];  // 106 06A
    [ascii addObject:@"k"];  // 107 06B
    [ascii addObject:@"l"];  // 108 06C
    [ascii addObject:@"m"];  // 109 06D
    [ascii addObject:@"n"];  // 110 06E
    [ascii addObject:@"o"];  // 111 06F
// 070
    [ascii addObject:@"p"];  // 112 070
    [ascii addObject:@"q"];  // 113 071
    [ascii addObject:@"r"];  // 114 072
    [ascii addObject:@"s"];  // 115 073
    [ascii addObject:@"t"];  // 116 074
    [ascii addObject:@"u"];  // 117 075
    [ascii addObject:@"v"];  // 118 076
    [ascii addObject:@"w"];  // 119 077
    [ascii addObject:@"x"];  // 120 078
    [ascii addObject:@"y"];  // 121 079
    [ascii addObject:@"z"];  // 122 07A
    [ascii addObject:@"{"];  // 123 07B
    [ascii addObject:@"|"];  // 124 07C
    [ascii addObject:@"}"];  // 125 07D
    [ascii addObject:@"~"];  // 126 07E
    [ascii addObject:@(127)];// 127 07F DEL
// 080
    [ascii addObject:@"€"];  // 128 080
    [ascii addObject:@(129)];// 129 081
    [ascii addObject:@"'"];  // 130 082
    [ascii addObject:@"ƒ"];  // 131 083
    [ascii addObject:@"""];  // 132 084
    [ascii addObject:@"…"];  // 133 085
    [ascii addObject:@"†"];  // 134 086
    [ascii addObject:@"‡"];  // 135 087
    [ascii addObject:@"ˆ"];  // 136 088
    [ascii addObject:@"‰"];  // 137 089
    [ascii addObject:@"Š"];  // 138 08A
    [ascii addObject:@"‹"];  // 139 08B
    [ascii addObject:@"Œ"];  // 140 08C
    [ascii addObject:@(141)];// 141 08D
    [ascii addObject:@"Ž"];  // 142 08E
    [ascii addObject:@(143)];  // 143 08F
// 090
    [ascii addObject:@(144)];// 144 090
    [ascii addObject:@"'"];  // 145 091
    [ascii addObject:@"'"];  // 146 092
    [ascii addObject:@"""];  // 147 093
    [ascii addObject:@"""];  // 148 094
    [ascii addObject:@"•"];  // 149 095
    [ascii addObject:@"–"];  // 150 096
    [ascii addObject:@"—"];  // 151 097
    [ascii addObject:@"˜"];  // 152 098
    [ascii addObject:@"™"];  // 153 099
    [ascii addObject:@"š"];  // 154 09A
    [ascii addObject:@"›"];  // 155 09B
    [ascii addObject:@"œ"];  // 156 09C
    [ascii addObject:@(157)];// 157 09D
    [ascii addObject:@"ž"];  // 158 09E
    [ascii addObject:@"Ÿ"];  // 159 09F
// 0A0
    [ascii addObject:@(160)];// 160 0A0
    [ascii addObject:@"¡"];  // 161 0A1
    [ascii addObject:@"¢"];  // 162 0A2
    [ascii addObject:@"£"];  // 163 0A3
    [ascii addObject:@"¤"];  // 164 0A4
    [ascii addObject:@"¥"];  // 165 0A5
    [ascii addObject:@"¦"];  // 166 0A6
    [ascii addObject:@"§"];  // 167 0A7
    [ascii addObject:@"¨"];  // 168 0A8
    [ascii addObject:@"©"];  // 169 0A9
    [ascii addObject:@"ª"];  // 170 0AA
    [ascii addObject:@"«"];  // 171 0AB
    [ascii addObject:@"¬"];  // 172 0AC
    [ascii addObject:@(173)];// 173 0AD
    [ascii addObject:@"®"];  // 174 0AE
    [ascii addObject:@"¯"];  // 175 0AF
// 0B0
    [ascii addObject:@"°"];  // 176 0B0
    [ascii addObject:@"±"];  // 177 0B1
    [ascii addObject:@"²"];  // 178 0B2
    [ascii addObject:@"³"];  // 179 0B3
    [ascii addObject:@"´"];  // 180 0B4
    [ascii addObject:@"µ"];  // 181 0B5
    [ascii addObject:@"¶"];  // 182 0B6
    [ascii addObject:@"·"];  // 183 0B7
    [ascii addObject:@"¸"];  // 184 0B8
    [ascii addObject:@"¹"];  // 185 0B9
    [ascii addObject:@"º"];  // 186 0BA
    [ascii addObject:@"»"];  // 187 0BB
    [ascii addObject:@"¼"];  // 188 0BC
    [ascii addObject:@"½"];  // 189 0BD
    [ascii addObject:@"¾"];  // 190 0BE
    [ascii addObject:@"¿"];  // 191 0BF
// 0C0
    [ascii addObject:@"À"];  // 192 0C0
    [ascii addObject:@"Á"];  // 193 0C1
    [ascii addObject:@"Â"];  // 194 0C2
    [ascii addObject:@"Ã"];  // 195 0C3
    [ascii addObject:@"Ä"];  // 196 0C4
    [ascii addObject:@"Å"];  // 197 0C5
    [ascii addObject:@"Æ"];  // 198 0C6
    [ascii addObject:@"Ç"];  // 199 0C7
    [ascii addObject:@"È"];  // 200 0C8
    [ascii addObject:@"É"];  // 201 0C9
    [ascii addObject:@"Ê"];  // 202 0CA
    [ascii addObject:@"Ë"];  // 203 0CB
    [ascii addObject:@"Ì"];  // 204 0CC
    [ascii addObject:@"Í"];  // 205 0CD
    [ascii addObject:@"Î"];  // 206 0CE
    [ascii addObject:@"Ï"];  // 207 0CF
// 0D0
    [ascii addObject:@"Ð"];  // 208 0D0
    [ascii addObject:@"Ñ"];  // 209 0D1
    [ascii addObject:@"Ò"];  // 210 0D2
    [ascii addObject:@"Ó"];  // 211 0D3
    [ascii addObject:@"Ô"];  // 212 0D4
    [ascii addObject:@"Õ"];  // 213 0D5
    [ascii addObject:@"Ö"];  // 214 0D6
    [ascii addObject:@"×"];  // 215 0D7
    [ascii addObject:@"Ø"];  // 216 0D8
    [ascii addObject:@"Ù"];  // 217 0D9
    [ascii addObject:@"Ú"];  // 218 0DA
    [ascii addObject:@"Û"];  // 219 0DB
    [ascii addObject:@"Ü"];  // 220 0DC
    [ascii addObject:@"Ý"];  // 221 0DD
    [ascii addObject:@"Þ"];  // 222 0DE
    [ascii addObject:@"ß"];  // 223 0DF
// 0E0
    [ascii addObject:@"à"];  // 224 0E0
    [ascii addObject:@"á"];  // 225 0E1
    [ascii addObject:@"â"];  // 226 0E2
    [ascii addObject:@"ã"];  // 227 0E3
    [ascii addObject:@"ä"];  // 228 0E4
    [ascii addObject:@"å"];  // 229 0E5
    [ascii addObject:@"æ"];  // 230 0E6
    [ascii addObject:@"ç"];  // 231 0E7
    [ascii addObject:@"è"];  // 232 0E8
    [ascii addObject:@"é"];  // 233 0E9
    [ascii addObject:@"ê"];  // 234 0EA
    [ascii addObject:@"ë"];  // 235 0EB
    [ascii addObject:@"ì"];  // 236 0EC
    [ascii addObject:@"í"];  // 237 0ED
    [ascii addObject:@"î"];  // 238 0EE
    [ascii addObject:@"ï"];  // 239 0EF
// 0F0
    [ascii addObject:@"ð"];  // 240 0F0
    [ascii addObject:@"ñ"];  // 241 0F1
    [ascii addObject:@"ò"];  // 242 0F2
    [ascii addObject:@"ó"];  // 243 0F3
    [ascii addObject:@"ô"];  // 244 0F4
    [ascii addObject:@"õ"];  // 245 0F5
    [ascii addObject:@"ö"];  // 246 0F6
    [ascii addObject:@"÷"];  // 247 0F7
    [ascii addObject:@"ø"];  // 248 0F8
    [ascii addObject:@"ù"];  // 249 0F9
    [ascii addObject:@"ú"];  // 250 0FA
    [ascii addObject:@"û"];  // 251 0FB
    [ascii addObject:@"ü"];  // 252 0FC
    [ascii addObject:@"ý"];  // 253 0FD
    [ascii addObject:@"þ"];  // 254 0FE
    [ascii addObject:@"ÿ"];  // 255 0FF

    NSInteger i;

    for (i=0; i < self.length; i++) {

        NSRange range;
        range.location = i;
        range.length = 1;

        NSString *charString = [self substringWithRange:range];

        for (NSInteger asciiIdx=0; asciiIdx < ascii.count; asciiIdx++) {

            if ([charString isEqualToString:ascii[asciiIdx]]) {
                unsigned char c = (unsigned char)asciiIdx;
                output[i] = c;
                break;
            }

        }
    }

    // Don't forget string termination
    output[i] = 0;

    return (const char*)&output[0];
}

@end


text:
Q: Use of the jsfiddle tag Should the jsfiddle tag be used when a post just uses jsfiddle to demonstrate code, or should the jsfiddle tag only be used when the question is about jsfiddle?
I think it should not be used just because there is a code example on jsfiddle, but the question should be about jsfiddle in order for the tag to be used.
Either way, I think the jsfiddle tag wiki should be updated to make it clear when the tag should be used.

A: The tag should be used when the question is about jsfiddle.
Tags are about adding value to the question - allowing one to see quickly what subjects the question is about. If jsfiddle is only there to illustrate the question, it shouldn't be tagged with it.

Update:
I have added a clarification to the tag wiki, explaining it should be used when the question is about jsFiddle.


text:
Q: Convert List> to Map> Java8 I have a Object
class Wrapper{
   private SomeObject someObject;
   private String value;
}

class SomeObject{
  private String id;
}

I have function that returns List<List<Wrapper>> I want to convert it to Map<SomeObject,List<Wrapper>>
At the moment I'm using looping and compare to to achieve this. Is there way to achieve this via Java8 streams
wrappers.stream()
            .flatMap(w -> w.stream()) //stream of wrapper
            .collect(Collectors.toMap(<not sure which mapping fucntion to use here>))

A: You can use groupingBy collector along with the flatMap operator to get this done. Here's how it looks.
Map<SomeObject, List<Wrapper>> map = l.stream().flatMap(List::stream)
    .collect(Collectors.groupingBy(Wrapper::getSomeObject));

However, an iterative version would be much readable and faster than streams.
Map<SomeObject, List<Wrapper>> m = new HashMap<>();
for (List<Wrapper> wrappers : l)
    for (Wrapper w : wrappers)
        m.computeIfAbsent(w.someObject, unused -> new ArrayList<Wrapper>()).add(w);


text:
Q: I'm trying to fetch multiple id from mysql database to open different pdfs on specific buttons but it's just open first id's pdf Here is code which i'm using?
<?php
// Database Connection
$conn = new mysqli('localhost', 'root', '', 'thevivitsudb');
//Check for connection error
$select = "SELECT file_loc,prev_file_name, (SELECT id FROM courses_structure WHERE id=pdf_files.sub_id) FROM pdf_files WHERE id IN(SELECT pdf_file_id FROM pdf_files_user WHERE id='320' )";
$result = $conn->query($select);
while($row = $result->fetch_object()){
  $pdf = $row->prev_file_name;
  $path = $row->file_loc;

  $file = $path.$pdf;
}
// Add header to load pdf file
header('Content-type: application/pdf');
header('Content-Disposition: inline; prev_file_name="' .$file. '"');
header('Content-Transfer-Encoding: binary');
header('Accept-Ranges: bytes');
@readfile($file);
?>

HTML Code of Button
View

i'm expecting that on all specific link's it open specific pdfs by their id.


text:
Q: Complex number such that affixes of itself, its squared and its cube form a right triangle. $z,z^2,z^3$ form a right triangle in argand plane $\DeclareMathOperator{\aff}{Aff}$
Here is a funny problem  I stumbled upon recently
I call the affix of a complex number the corresponding point in the argand plane, that is
$$\aff(\mathrm{i})=(0;1)$$
Find all $z \in \mathbf{C}$ such that the affixes of $z,z^2\ \& \ z^3$ form a right triangle.
I decided to Set $A=\aff(z),B=\aff(z^2),C=\aff(z^3)$
I have proven that :

*

*If $z$ is a solution, then $z\neq 0,\  z\neq 1, \ \& \ z\neq-1$

*If the triangle is right angled at A, $z$ must be a non zero imaginary number.

*If the triangle is rigth angled at B, $\aff(z)$ has to lie on the vertical line defined by $x=(-1)$, except for $z=(-1)$.

(I'll post my proof when I get some time to write it in $\mathrm{\LaTeX}$ soon.)
I'm down to the third case : I have proven that if the triangle is right angled at $C$, then :
$$\Re \left(\frac{1+z}{z}\right)=0$$
Thanks to some experimentation, I know that $\aff(z)$ should lie on the circle centered at $(-\frac12;0)$ with radius $\frac12$, with $z$ again respecting the first condition above.
Now,how do I prove this ?
Thanks for the help.
Here is an animation.

A: Partial Solution:
If $z=\cos t+i\sin t,$
$$m_{AB}=\dfrac{\sin2t-\sin t}{\cos 2t-\cos t}=-\cot\dfrac{3t}2\text{ if }\sin\dfrac t2\ne0$$
Similarly,
$$ m_{BC}=-\cot\dfrac{5t}2, m_{CA}=-\cot2t$$
Now we need at exactly one of the products $m_{AB}\cdot m_{BC},m_{BC}\cdot m_{CA},m_{CA}\cdot m_{AB}$  to be $=-1$

A: HINT
Angle between vectors $\vec{KM}, \vec{LM},$ where the points have complex coordinates $z_K, z_L, z_M,$ is equal to
$$\arg{\frac{z_M-z_L}{z_M-z_K}}.$$
In the present exercise we want
$$\arg{\frac{z-z^2}{z-z^3}}=\frac{\pi}{2}+k\pi,\;k\in \mathbb{Z}$$
or
$$\arg{\frac{z^2-z}{z^2-z^3}}=\frac{\pi}{2}+k\pi,\;k\in \mathbb{Z}$$
or
$$\arg{\frac{z^3-z^2}{z^3-z}}=\frac{\pi}{2}+k\pi,\;k\in \mathbb{Z}$$

A: Oh dear,
It turns out I'm too tired to think, I found the following :
let's set $z=a+ib$ as in the question
then :
$$\frac{z+1}{z}=\frac{(a+1)+ib}{a+ib}=\frac{(a+1)+ib)(a-ib)}{a^2+b^2}$$
From which one gets
$$\frac{z+1}{z}=\frac{a+a^2+b^2-ib}{a^2+b^2}=\frac{a+a^2+b^2}{a^2+b^2}-\frac{ib}{a^2+b^2}$$
now, because this is an imaginary number we get
$$C(a,b)=a+a^2+b^2=0$$
which is the equation of an ellipse because it is a polynomial of two variables, of degree two. We see that there is no division, therefore, this is the equation of a circle
Let's rewrite it to see the circle's centre and radius :
$$C(a,b)=a+a^2+(b-0)^2$$
That is with two canonical forms
$$C(a,b)=\left(a+\frac{1}{2}\right)^2+(b-0)^2-\frac14=0$$
But then we get
$$\left(a-\left(-\frac{1}{2}\right)\right)^2+(b-0)^2=\frac14$$
We just need a square after the equal sign to get the radius
$$\left(a-\left(-\frac{1}{2}\right)\right)^2+(b-0)^2=\left(\frac12\right)^2$$
which is the equation of the circle mentioned in the question / OP.
Please note however that $(-1)$ and $0$ both belong to this circle.


text:
Q: Windows 10 Internet randomly disconnecting I recently did a Fresh Install of Windows 10 about a week ago now, all was fine up until last night where my internet started randomly disconnecting every 2 minutes and then it eventually spanned out to every 20 minutes, this went on for the rest of the night.
I tried to see if it was just my computer so I ssh'd to another computer on my network and started pinging google while also doing so on my PC, it took 20 minutes for my PC to drop out for 2 seconds while the other computer kept pinging google fine.
I then tried to install the driver that came with my motherboard which still resulted in the same outcome and also downloaded the newest up to date driver from broadcoms website which still ended up with the same outcome.
My friend said he had the same problem with windows 10 when he freshly Installed it but fixed it by installing Windows 8 and then Upgrading to Windows 10, so I did that this morning at around 10am, its now 9:50 and I my PC disconnected for the first time at 9:30 and then again 10 minutes later, both times were for around 2 minutes.
I have looked everywhere for a solution and it seems everyone that has this problem can't find one, my Power Settings are fine and other devices on my network do not Disconnect, I haven't installed anything recently and if so it would be resolved with the fresh install I did today. This literally started happening randomly.

A: Looks like there's either something wrong with your network card or it's a Windows coding error that occurred during installation of Windows 10. However it's more likely a network card error. Try replacing your network card. Depending on your PC brand and type, network card changing will slightly vary but I found this link quite useful: click here.
The problem may also be with a small error in the installation of Windows. This isn't Microsoft's fault as the error occurs when the installation is quite bumpy or difficult but it would be unlikely that serious errors would occur and they are a common thing. One problem around the error would be a re-installation of the Windows 10 operating system its self. I found a pretty helpful like right here.
Your network service provider can also be to blame too. Try contacting them and alerting them of the problem if it still is not resolved fully by the two above solutions.
There are other things too that include hardware error elsewhere or your system being slightly incompatible with Windows 10 overall but that would mean Windows 10 would hardly work at all then so that is also unlikely. If the problem persists, it may be your network service provider.


text:
Q: What's the difference between "statically linked" and "not a dynamic executable" from Linux ldd? Consider this AMD64 assembly program:
.globl _start
_start:
    xorl %edi, %edi
    movl $60, %eax
    syscall

If I compile that with gcc -nostdlib and run ldd a.out, I get this:
        statically linked

If I instead compile that with gcc -static -nostdlib and run ldd a.out, I get this:
        not a dynamic executable

What's the difference between statically linked and not a dynamic executable? And if my binary was already statically linked, why does adding -static affect anything?

A: There are two separate things here:

*

*Requesting an ELF interpreter (ld.so) or not.
Like #!/bin/sh but for binaries, runs before your _start.
This is the difference between a static vs. dynamic executable.

*The list of dynamically linked libraries for ld.so to load happens to be empty.
This is apparently what ldd calls "statically linked", i.e. that any libraries you might have linked at build time were static libraries.

Other tools like file and readelf give more information and use terminology  that matches what you'd expect.

Your GCC is configured so -pie is the default, and gcc doesn't make a static-pie for the special case of no dynamic libraries.

*

*gcc -nostdlib just makes a PIE that happens not to link to any libraries but is otherwise identical to a normal PIE, specifying an ELF interpreter.
ldd confusingly calls this "statically linked".
file : ELF 64-bit LSB pie executable, x86-64, version 1 (SYSV), dynamically linked, interpreter /lib64/ld-linux-x86-64.so.2 ...

*gcc -nostdlib -static overrides the -pie default and makes a true static executable.
file : ELF 64-bit LSB executable, x86-64, version 1 (SYSV), statically linked ...

*gcc -nostdlib -no-pie also chooses to make a static executable as an optimization for the case where there are no dynamic libraries at all.  Since a non-PIE executable couldn't have been ASLRed anyway, this makes sense.  Byte-for-byte identical to the -static case.

*gcc -nostdlib -static-pie makes an ASLRable executable that doesn't need an ELF interpreter.  GCC doesn't do this by default for gcc -pie -nostdlib, unlike the no-pie case where it chooses to sidestep ld.so when no dynamically-linked libraries are involved.
file : ELF 64-bit LSB pie executable, x86-64, version 1 (SYSV), statically linked ...
-static-pie is obscure, rarely used, and older file doesn't identify it as statically linked.
-nostdlib doesn't imply -no-pie or -static, and -static-pie has to be explicitly specified to get that.
gcc -static-pie invokes ld -static -pie, so ld has to know what that means.  Unlike with the non-PIE case where you don't have to ask for a dynamic executable explicitly, you just get one if you pass ld any .so libraries.  I think that's why you happen to get a static executable from gcc -nostdlib -no-pie - GCC doesn't have to do anything special, it's just ld doing that optimization.
But ld doesn't enable -static implicitly when -pie is specified, even when there are no shared libraries to link.

Details
Examples generated with gcc --version gcc (Arch Linux 9.3.0-1) 9.3.0
ld --version GNU ld (GNU Binutils) 2.34 (also readelf is binutils)
ldd --version ldd (GNU libc) 2.31
file --version file-5.38   - note that static-pie detection has changed in recent patches, with Ubuntu cherry-picking an unreleased patch.  (Thanks @Joseph for the detective work) - this in 2019 detected dynamic = having a PT_INTERP to handle static-pie, but it was reverted to detect based on PT_DYNAMIC so shared libraries count as dynamic.  debian bug #948269.  static-pie is an obscure rarely-used feature.
GCC ends up running ld -pie exit.o with a dynamic linker path specified, and no libraries.  (And a boatload of other options to support possible LTO link-time optimization, but the keys here are -dynamic-linker /lib64/ld-linux-x86-64.so.2 -pie.  collect2 is just a wrapper around ld.)
$ gcc -nostdlib exit.s -v      # output manually line wrapped with \ for readability
...
COLLECT_GCC_OPTIONS='-nostdlib' '-v' '-mtune=generic' '-march=x86-64'
 /usr/lib/gcc/x86_64-pc-linux-gnu/9.3.0/collect2  \
-plugin /usr/lib/gcc/x86_64-pc-linux-gnu/9.3.0/liblto_plugin.so \
-plugin-opt=/usr/lib/gcc/x86_64-pc-linux-gnu/9.3.0/lto-wrapper \
-plugin-opt=-fresolution=/tmp/ccoNx1IR.res \
--build-id --eh-frame-hdr --hash-style=gnu \
-m elf_x86_64 -dynamic-linker /lib64/ld-linux-x86-64.so.2 -pie \
-L/usr/lib/gcc/x86_64-pc-linux-gnu/9.3.0 \
-L/usr/lib/gcc/x86_64-pc-linux-gnu/9.3.0/../../../../lib -L/lib/../lib \
-L/usr/lib/../lib \
-L/usr/lib/gcc/x86_64-pc-linux-gnu/9.3.0/../../.. \
/tmp/cctm2fSS.o

You get a dynamic PIE with no dependencies on other libraries.  Running it still invokes the "ELF interpreter" /lib64/ld-linux-x86-64.so.2 on it which runs before jumping to your _start.  (Although the kernel has already mapped the executable's ELF segments to ASLRed virtual addresses, along with ld.so's text / data / bss).
file and readelf are more descriptive.
PIE non-static executable from gcc -nostdlib
$ gcc -nostdlib exit.s -o exit-default
$ ls -l exit-default
-rwxr-xr-x 1 peter peter 13536 May  2 02:15 exit-default
$ ldd exit-default
        statically linked
$ file exit-default
exit-default: ELF 64-bit LSB pie executable, x86-64, version 1 (SYSV), dynamically linked, interpreter /lib64/ld-linux-x86-64.so.2, BuildID[sha1]=05a4d1bdbc94d6f91cca1c9c26314e1aa227a3a5, not stripped

$ readelf -a exit-default
...
  Type:                              DYN (Shared object file)
  Machine:                           Advanced Micro Devices X86-64
  Version:                           0x1
  Entry point address:               0x1000
...
Program Headers:
  Type           Offset             VirtAddr           PhysAddr
                 FileSiz            MemSiz              Flags  Align
  PHDR           0x0000000000000040 0x0000000000000040 0x0000000000000040
                 0x00000000000001f8 0x00000000000001f8  R      0x8
  INTERP         0x0000000000000238 0x0000000000000238 0x0000000000000238
                 0x000000000000001c 0x000000000000001c  R      0x1
      [Requesting program interpreter: /lib64/ld-linux-x86-64.so.2]
  LOAD           0x0000000000000000 0x0000000000000000 0x0000000000000000
                 0x00000000000002b1 0x00000000000002b1  R      0x1000
  LOAD           0x0000000000001000 0x0000000000001000 0x0000000000001000
                 0x0000000000000009 0x0000000000000009  R E    0x1000
  ...   (the Read+Exec segment to be mapped at virt addr 0x1000 is where your text section was linked.)

If you strace it you can also see the differences:
$ gcc -nostdlib exit.s -o exit-default
$ strace ./exit-default
execve("./exit-default", ["./exit-default"], 0x7ffe1f526040 /* 51 vars */) = 0
brk(NULL)                               = 0x5617eb1e4000
arch_prctl(0x3001 /* ARCH_??? */, 0x7ffcea703380) = -1 EINVAL (Invalid argument)
access("/etc/ld.so.preload", R_OK)      = -1 ENOENT (No such file or directory)
mmap(NULL, 8192, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0) = 0x7f9ff5b3e000
arch_prctl(ARCH_SET_FS, 0x7f9ff5b3ea80) = 0
mprotect(0x5617eabac000, 4096, PROT_READ) = 0
exit(0)                                 = ?
+++ exited with 0 +++

vs. -static and -static-pie the first instruction executed in user-space is your _start (which you can also check with GDB using starti).
$ strace ./exit-static-pie
execve("./exit-static-pie", ["./exit-static-pie"], 0x7ffcdac96dd0 /* 51 vars */) = 0
exit(0)                                 = ?
+++ exited with 0 +++

gcc -nostdlib -static-pie
$ gcc -nostdlib -static-pie exit.s -o exit-static-pie
$ ls -l exit-static-pie
-rwxr-xr-x 1 peter peter 13440 May  2 02:18 exit-static-pie
peter@volta:/tmp$ ldd exit-static-pie
        statically linked
peter@volta:/tmp$ file exit-static-pie
exit-static-pie: ELF 64-bit LSB pie executable, x86-64, version 1 (SYSV), statically linked, BuildID[sha1]=daeb4a8f11bec1bb1aaa13cd48d24b5795af638e, not stripped

$ readelf -a exit-static-pie
...
  Type:                              DYN (Shared object file)
  Machine:                           Advanced Micro Devices X86-64
  Version:                           0x1
  Entry point address:               0x1000
...

Program Headers:
  Type           Offset             VirtAddr           PhysAddr
                 FileSiz            MemSiz              Flags  Align
  LOAD           0x0000000000000000 0x0000000000000000 0x0000000000000000
                 0x0000000000000229 0x0000000000000229  R      0x1000
  LOAD           0x0000000000001000 0x0000000000001000 0x0000000000001000
                 0x0000000000000009 0x0000000000000009  R E    0x1000
  ... (no Interp header, but still a read+exec text segment)

Notice that the addresses are still relative to the image base, leaving ASLR up to the kernel.
Surprisingly, ldd doesn't say that it's not a dynamic executable.  That might be a bug, or a side effect of some implementation detail.

gcc -nostdlib -static traditional non-PIE old-school static executable
$ gcc -nostdlib -static exit.s -o exit-static
$ ls -l exit-static
-rwxr-xr-x 1 peter peter 4744 May  2 02:26 exit-static
peter@volta:/tmp$ ldd exit-static
        not a dynamic executable
peter@volta:/tmp$ file exit-static
exit-static: ELF 64-bit LSB executable, x86-64, version 1 (SYSV), statically linked, BuildID[sha1]=1b03e3d05709b7288fe3006b4696fd0c11fb1cb2, not stripped
peter@volta:/tmp$ readelf -a exit-static
ELF Header:
...
  Type:                              EXEC (Executable file)
  Machine:                           Advanced Micro Devices X86-64
  Version:                           0x1
  Entry point address:               0x401000
...   (Note the absolute entry-point address nailed down at link time)
      (And that the ELF type is EXEC, not DYN)

Program Headers:
  Type           Offset             VirtAddr           PhysAddr
                 FileSiz            MemSiz              Flags  Align
  LOAD           0x0000000000000000 0x0000000000400000 0x0000000000400000
                 0x000000000000010c 0x000000000000010c  R      0x1000
  LOAD           0x0000000000001000 0x0000000000401000 0x0000000000401000
                 0x0000000000000009 0x0000000000000009  R E    0x1000
  NOTE           0x00000000000000e8 0x00000000004000e8 0x00000000004000e8
                 0x0000000000000024 0x0000000000000024  R      0x4

 Section to Segment mapping:
  Segment Sections...
   00     .note.gnu.build-id
   01     .text
   02     .note.gnu.build-id
   ...

Those are all the program headers; unlike pie / static-pie I'm not leaving any out, just other whole parts of the readelf -a output.
Also note the absolute virtual addresses in the program headers that don't give the kernel a choice where in virtual address space to map the file.  This is the difference between EXEC and DYN types of ELF objects.  PIE executables are shared objects with an entry point, allowing us to get ASLR for the main executable.  Actual EXEC executables have a link-time-chosen memory layout.

ldd apparently only reports "not a dynamic executable" when both:

*

*no ELF interpreter (dynamic linker) path

*ELF type = EXEC


text:
Q: get_circuits() of Stem library returns an empty list When I execute controller.get_circuits(), I get an empty list. How could this be?
with stem.control.Controller.from_port(port=9151) as controller:
  controller.authenticate()
  controller.signal(Signal.NEWNYM) # get new tor identity
  circs = controller.get_circuits()

  for circ in controller.get_circuits():
    print(circ.id)
  print(len(circs))
  print(circs[1].id)