text:
Q: Script de dias úteis Estou usando um script que encontrei nesta pergunta do SOen, e para contar os dias úteis desconsiderando sábado e domingo (dá pra fazer só com domingo tbm, alterando $what_day > 5 para $what_day > 6 por exemplo) ele funciona certinho, mas eu queria incluir o calendário oficial de feriados do Brasil.
Este é o script que está funcionando (já pegando os dados do meu formulário):
    <?php
//get current month for example
$beginday = ($_POST ["Tdesl"]);
$lastday  = ($_POST ["Tinsem3"]);

$nr_work_days = getWorkingDays($beginday, $lastday);
echo $nr_work_days;

function getWorkingDays($startDate, $endDate)
{
    $begin = strtotime($startDate);
    $end   = strtotime($endDate);
    if ($begin > $end) {
        echo "startdate is in the future!
";

        return 0;
    } else {
        $no_days  = 0;
        $weekends = 0;
        while ($begin <= $end) {
            $no_days++; // no of days in the given interval
            $what_day = date("N", $begin);
            if ($what_day > 5) { // 6 and 7 are weekend days
                $weekends++;
            };
            $begin += 86400; // +1 day
        };
        $working_days = $no_days - $weekends;

        return $working_days;
    }
}

O HTML:
<form method="post" id="Cform" name="Tform" action="diasuteis2.php">
    Data inicial:
    <input type="date" name="Tinsem3" id="Cinsem" size="6">
    Data final:
    <input type="date" name="Tdesl" id="Cdesl22" size="6">

    <input type="submit" id="enviar">

</form>

Um exemplo de saída correta para:
echo $beginday;
echo "

";
echo $lastday;
echo "

";
echo $nr_work_days;

É:

2014-12-10
2014-12-15
4

(Ele considerou o dia 10, e excluiu os dias 13 e 14 corretamente)
É possível, ou viável, incluir os feriados neste código? Se alguém puder fazer um exemplo (claro que não precisa incluir todos os feriados, apenas mostrar como posso fazer isso) agradeço desde já.

A: Deixo aqui um exemplo para contagem dos feriados. Atenção que isto não foi testado, por isso pode ter algum erro.
function getWorkingDays($startDate, $endDate) {
    $begin = strtotime($startDate);
    $end   = strtotime($endDate);
    if ($begin > $end) {
        echo "startdate is in the future!
";
        return 0;
    }
    else {
        $holidays = array('01/01', '25/12', ...);
        $weekends = 0;
        $no_days = 0;
        $holidayCount = 0;
        while ($begin <= $end) {
            $no_days++; // no of days in the given interval
            if (in_array(date("d/m", $begin), $holidays)) {
                $holidayCount++;
            }
            $what_day = date("N", $begin);
            if ($what_day > 5) { // 6 and 7 are weekend days
                $weekends++;
            };
            $begin += 86400; // +1 day
        };
        $working_days = $no_days - $weekends - $holidayCount;

        return $working_days;
    }
}

A: Gostaria de acrescentar sobre os feriados:
    function dias_feriados($ano = null)
    {
        if ($ano === null)
        {
            $ano = intval(date('Y'));
        }

        $pascoa     = easter_date($ano); // Limite de 1970 ou após 2037 da easter_date PHP consulta http://www.php.net/manual/pt_BR/function.easter-date.php
        $dia_pascoa = date('j', $pascoa);
        $mes_pascoa = date('n', $pascoa);
        $ano_pascoa = date('Y', $pascoa);

        $feriados = array(
            // Tatas Fixas dos feriados Nacionail Basileiras
            mktime(0, 0, 0, 1,  1,   $ano), // Confraternização Universal - Lei nº 662, de 06/04/49
            mktime(0, 0, 0, 4,  21,  $ano), // Tiradentes - Lei nº 662, de 06/04/49
            mktime(0, 0, 0, 5,  1,   $ano), // Dia do Trabalhador - Lei nº 662, de 06/04/49
            mktime(0, 0, 0, 9,  7,   $ano), // Dia da Independência - Lei nº 662, de 06/04/49
            mktime(0, 0, 0, 10,  12, $ano), // N. S. Aparecida - Lei nº 6802, de 30/06/80
            mktime(0, 0, 0, 11,  2,  $ano), // Todos os santos - Lei nº 662, de 06/04/49
            mktime(0, 0, 0, 11, 15,  $ano), // Proclamação da republica - Lei nº 662, de 06/04/49
            mktime(0, 0, 0, 12, 25,  $ano), // Natal - Lei nº 662, de 06/04/49

            // These days have a date depending on easter
            mktime(0, 0, 0, $mes_pascoa, $dia_pascoa - 48,  $ano_pascoa),//2ºferia Carnaval
            mktime(0, 0, 0, $mes_pascoa, $dia_pascoa - 47,  $ano_pascoa),//3ºferia Carnaval
            mktime(0, 0, 0, $mes_pascoa, $dia_pascoa - 2 ,  $ano_pascoa),//6ºfeira Santa
            mktime(0, 0, 0, $mes_pascoa, $dia_pascoa     ,  $ano_pascoa),//Pascoa
            mktime(0, 0, 0, $mes_pascoa, $dia_pascoa + 60,  $ano_pascoa),//Corpus Cirist
        );

        sort($feriados);

        return $feriados;
    }

Você indica o ano e ele gera um ARRAY com os dias dos feriados.
Fora isso ainda há feriados municipais que deveram ser adicionados ao ARRAY.
Particularmente eu coloquei em um banco de dados os feriados municipais, pois na equipe há pessoas trabalhando em várias localidades.
Para mostrar as datas:
            $feriados = dias_feriados();
            $diaf = count($feriados);
            for ($x=0;$x<$diaf;$x++){
                echo '
'.date('Y-m-d',$feriados[$x]).'
';
            }


text:
Q: ion2-calendar issue if `from` date is in the past We use ion2-calendar in the angular/ionic app. Everything was fine. Now, we need to add a calendar to select a birth date.
The from possible date should be starting around 1950+. The issue is that the minimum possible "from" year that I can set is 1970. If I try to set the date 100 years in the past from now, like this:
 from: this.dateService.subDateYears(new Date(), 100),
 to: this.dateService.addDays(new Date(), 45)

the calendar does not work then.
Could you please advise how to solve it? Thanks

redpajama_set_name: RedPajamaStackExchange


text:
Q: Python - Confused by class and instance variable I tried to write a small wrapper script for the unix find-command. Something I messed up with the parameter passing. Could you give me a hint regarding my mistake?
The error message is
Traceback (most recent call last):
  File "frep.py", line 43, in <module>
    inst.prep_shell_commands(self.extension, self.search_string, self.rel_numbers)
NameError: name 'self' is not defined

This is the code:
import os
import subprocess
import string
import sys

class Frep(object):

    extension = ""
    search_string =""
    commands = []
    rel_numbers = ""

    def get_params(self):
        Frep.no_of_params = len(sys.argv)
        if Frep.no_of_params == 4:
            Frep.extension = str(sys.argv[1])
            Frep.search_string = str(sys.argv[2])
            Frep.rel_numbers = str(sys.argv[3])
        else:
            print "Usage:   frep [FILE_EXTENSION] [SEARCH_STRING] [RELEASE_NUMBERS]"
            print "Example: frep sql my_search_string [5-6]"
            print " "
            sys.exit()

    def prep_shell_commands(self, ext, ss, reln):
        print ext
        tmp_folderlist = string.split(subprocess.check_output("find /data/grep_dir -maxdepth 1 -type d -name '["+reln+"]*'", shell=True), '\n')
        #tmp_folderlist = string.split(subprocess.check_output("find /data/grep_dir -maxdepth 1 -type d -name '[6-7]*'", shell=True), '\n')
        for d in tmp_folderlist:
            commands.append("find " + d + " -type f -name '*" + ext +"' -exec grep -il '" + ss +"' {} \;")
        print commands

    def exec_commands(self, c_list):
        for c in c_list:
            os.system(c)

inst = Frep()

inst.prep_shell_commands(self.extension, self.search_string, self.rel_numbers)

exec_commands(self.commands)

A: You invoke an instance member by using the name of the instance of the object
inst.prep_shell_commands(inst.extension, inst.search_string, isnt.rel_numbers)

That being said, if your method is always going to be invoking instance variables, then you should rewrite your prep_shell_commands method so that it takes no parameters.

A: Here's a re-write of your code. This version's not perfect, but it shows how to define a class & how to use a class instance in the way that it's usually done in Python.
FWIW, it's probably better to validate input data before passing it into your class, but I guess it's ok here.
I haven't tested this code, since I don't have the required directories and files, but hopefully it doesn't contain any horrible errors. :)
#!/usr/bin/env python

import os
import subprocess
import sys

class Frep(object):
    def __init__(self, args):
        if len(args) != 3:
            self.usage()

        self.extension = args[0]
        self.search_string = args[1]
        self.rel_numbers = args[2]
        self.commands = []

    def usage(self):
        print "Usage:   frep FILE_EXTENSION SEARCH_STRING RELEASE_NUMBERS"
        print "Example: frep sql my_search_string [5-6]"
        print " "
        sys.exit()

    def prep_shell_commands(self):
        print self.extension
        cmd = "find /data/grep_dir -maxdepth 1 -type d -name '[" + self.rel_numbers + "]*'"
        tmp_folderlist = subprocess.check_output(cmd, shell=True).split('\n')

        for d in tmp_folderlist:
            cmd = "find " + d + " -type f -name '*" + self.extension + "' -exec grep -il '" + self.search_string + "' {} \;"
            self.commands.append(cmd)
        print self.commands

    def exec_commands(self):
        for cmd in self.commands:
            os.system(cmd)

def main():
    inst = Frep(sys.argv[1:])
    inst.prep_shell_commands()
    inst.exec_commands()

if __name__ == '__main__':
    main()

A: In the instance of Frep, where you list the following:
extension = ""
search_string =""
commands = []
rel_numbers = ""

To be able to properly access these variables you'd need to do the following:
class Frep(object):
    def__init__(self):
        self.extension = ""
        self.search_string = ""
        self.commands = []
        self.rel_numbers = ""

Then, when you refer to those variables within your class, you can use self.variablename.
To refer to them outside of the class, you would use Frep.extension.


text:
Q: ScrollRect does not correctly update the position when clamping the normalized position, after removing/deactivating a child element from the content This is an issue that I had to resolve myself after finding no solutions for it.
The issue was that after removing a GameObject element from the ScrollRect's content, it would not clamp its normalized position until the user starts moving it again. This could lead to the ScrollRect showing empty space when it is showing the last elements and has deactivated the last element from the parent.

*

*The normalized position value was not updating until the user interacted with the ScrollRect content.

*Setting the normalized position manually, after deactivating an element, would not work as it was working on old values that have not been updated yet (see above for why).

A: The best solution I have found is to

*

*Force a Canvas update after detecting a child, in the ScrollRect's content, being removed.

*Then Clamping the value, since the normalized position has been updated correctly.

Example code:
        if (isRemoving) {
            Canvas.ForceUpdateCanvases();
            scrollRect.horizontalNormalizedPosition = Mathf.Clamp(scrollRect.horizontalNormalizedPosition, 0f, 1f);
        }

A: Well, better late than never. I have the same problem in my old Unity 5.6x. So, I found that switching between movementType causes scrollrect to update if you wait for few frames. Use:
StartCoroutine(UpdateScrollRect());
IEnumerator UpdateScrollRect()
    {
        yield return new WaitForEndOfFrame();
        yield return new WaitForEndOfFrame();
        ScrolRect.movementType = ScrollRect.MovementType.Elastic;
        ScrolRect.elasticity = 0f;
        yield return new WaitForEndOfFrame();
        yield return new WaitForEndOfFrame();
        ScrolRect.movementType = ScrollRect.MovementType.Clamped;
    }

Try also to play with number of frames skip, so it fits your situation.
Cheers!
-Pavel


text:
Q: Visual Studio 2012 in Windows 10: Cannot find or open the PDB file I have seen this problem fixed for Windows 7 and other versions of Visual Studio, but none of these methods have fixed my problem.
I have installed opencv 2.4.2 with Visual Studio C++ 2012, and I have already changed the property pages to include the Additional Directories for C/C++ -> General, Additional Libraries for Linker->General, and additional dependencies for Linker->Input. I have also added the appropriate paths to the environment variable "Path."
Still, I am getting the following error:
'PlanarHomography.exe' (Win32): Loaded 'C:\opencv-2.4.2\opencv\build\x64\vc12\bin\opencv_calib3d2413.dll'. Cannot find or open the PDB file.
'PlanarHomography.exe' (Win32): Loaded 'C:\opencv-2.4.2\opencv\build\x64\vc12\bin\opencv_core2413.dll'. Cannot find or open the PDB file.
'PlanarHomography.exe' (Win32): Loaded 'C:\opencv-2.4.2\opencv\build\x64\vc12\bin\opencv_features2d2413.dll'. Cannot find or open the PDB file.
'PlanarHomography.exe' (Win32): Loaded 'C:\opencv-2.4.2\opencv\build\x64\vc12\bin\opencv_flann2413.dll'. Cannot find or open the PDB file.
'PlanarHomography.exe' (Win32): Loaded 'C:\opencv-2.4.2\opencv\build\x64\vc12\bin\opencv_imgproc2413.dll'. Cannot find or open the PDB file.
Any assistance on what to do here would be greatly appreciated.

A: I'm used to using Eclipse and had to use Visual Studio for someone else's project. I didn't realize, different .dll files were needed for "release" and "debug" modes. Adding "d" to the end of each file name fixed my problem.
For example: opencv_calib3d2413.dll (for release) should instead be opencv_calib3d2413d.dll (for debug).


text:
Q: How to hide the default fragment actionBar create our own actionBar in android & kotlin I have an android app with bottom navigation containing 3 fragments and all have their own actionBar by default. I want to hide all the default actionBar of three fragments and create my own actionbar with many options. I am using Kotlin.

A: You just need to set the style of the app. Go to values/styles.xml, edit the value of AppTheme as NoActionBar. Then to create your own AppBar in each fragments, just use AppBarLayout in your Xml. For instance:
 <style name="AppTheme" parent="Theme.MaterialComponents.Light.NoActionBar">
       ...
 </style>

A: Heres a quick solution.
You find styles.xml and you change the base application theme to "Theme.AppCompat.NoActionBar" as shown below.
<style name="AppTheme" parent="Theme.AppCompat.NoActionBar">
<!-- Customize your theme here. -->
</style>

and define custom layout of action bar in xml

A: First of all, ActionBar is Activities property, not fragments. If you want a custom action bar follow this link, https://myandroid.site/custom-toolbar-with-style-in-kotlin-design-colorful-toolbar/
or
You can have the default ActionBar in Activity & create your own layout that look like an action bar.
Hide Action Bar(Below code should be inside Activity):
if (supportActionBar != null)
    supportActionBar?.hide()

A: I have solved the problem.
val appBarConfiguration = AppBarConfiguration(setOf( R.id.navigation_home, R.id.navigation_messages, R.id.navigation_profile))
setupActionBarWithNavController(navController, appBarConfiguration)

Just remove the above two lines from the main activity and your problem is solved.


text:
Q: Stopping FOR /F command at first line of output (Windows batch) So, I need to pull the last promote message from our Accurev stream and put it in a Jenkins variable to include in Jenkins email.  The only problem I'm having is with multiple line promote messages.  I really only want the first line of the promote message, but that's not what I'm seeing with my FOR /F command:
FOR /F "tokens=1-25 delims=;" %i in ('accurev.exe hist -s <stream> -t now.1 ^|FIND "#"') DO @echo %i

with multiple line promote message, I get this output:

 # This is a multiple line promote message
 # because my programmers need to include
 # accurate descriptions of the CRs that # they work on.

So, any way to have my for command stop after collecting the first line?

A: try this with GNU grep for Windows:
FOR /F "delims=;" %i in ('accurev.exe hist -s <stream> -t now.1 ^|grep -m1 "#"') DO @echo %i

A: FOR /F "tokens=1-25 delims=;" %i in ('accurev.exe hist -s <stream> -t now.1 ^|FIND "#"') DO @echo %i && goto:eof


text:
Q: Loading Youtube in a modal (possibly with swfobject?) I'm having a lot of problems getting a YouTube video to load in a modal properly on all browsers.  I just found swfobject but can't find any code on implementing it.
Can anyone tell me how to load a YouTube video dynamically using swfobject?  I've also got jQuery running on the site if that makes it more elegant code.

A: I figured it out.  This is the code I used to get it to work in the modal:
var atts = {};
atts.id = "vid";
$.modal('<div class="modal_container" style="background: transparent url(<?php echo $base_path . path_to_theme() ?>/images/bkgd_youtube_modal.png) no-repeat;">

', options);

swfobject.embedSWF('http://www.youtube.com/v/'+this.id+"&hl=en&fs=1&rel=0&color1=0x000000&color2=0x2d2d2d&enablejsapi=1&playerapiid=ytplayer",
"youtube_movie", "460px", "280px", "9", null, null, atts);


text:
Q: given a column with string data create a dataframe with ascii equivalent of each character in the string I am trying to convert a list of strings to its ascii and place each character in columns in a dataframe. I have 30M such strings and I am running into memory issues with the code I'm running.
For example:
strings = ['a','asd',1234,'ewq']
would like to get the following dataframe:
     0      1      2     3
0   97    0.0    0.0   0.0
1   97  115.0  100.0   0.0
2   49   50.0   51.0  52.0
3  101  119.0  113.0   0.0

What I have tried:
pd.DataFrame([[ord(chr) for chr in list(str(rec))] for rec in strings]).fillna(0)
Error:
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/root/anaconda3/lib/python3.7/site-packages/pandas/core/frame.py", line 435, in __init__
    arrays, columns = to_arrays(data, columns, dtype=dtype)
  File "/root/anaconda3/lib/python3.7/site-packages/pandas/core/internals/construction.py", line 404, in to_arrays
    dtype=dtype)
  File "/root/anaconda3/lib/python3.7/site-packages/pandas/core/internals/construction.py", line 434, in _list_to_arrays
    content = list(lib.to_object_array(data).T)
  File "pandas/_libs/lib.pyx", line 2269, in pandas._libs.lib.to_object_array
MemoryError

Not sure if relevant but strings is actually a column from another dataframe with .values.
Also, the longest string is almost 255 characters long. I know 30M x 1000 is a big number. Any way I can get around this issue?

A: Have you tried setting the datatype explicitely to uint8 and then to process the data in chunks?
From your example code, I guess, you are implicitely using float32, which requires 4 times more memory.
E.g. if you write it to a csv file and your strings fit into memory, you could try the following code:
def prepare_list(string, n, default):
    size= len(string)
    res= [ord(char) for char in string[:n]]
    if size < n:
        res+= [default] * (n - size)
    return res

chunk_size= 10000 # number of strings to be processed per step
max_len= 4        # maximum number of columns (=characters per string)
column_names= [str(i+1) for i in range(max_len)] # column names used for the columns
with open('output.csv', 'wt*) as fp:
    while string_list:
        df= pd.DataFrame([prepare_list(s, max_len, 0) for s in string_list[:chunk_size]], dtype='uint8', columns=column_names)
        df.to_csv(fp, header=fp.tell() == 0, index=False)
        string_list= string_list[chunk_size:]

When you read the csv created like this, you need to take care, that you set the type to uint8 again to avoid the same problem and make sure, the file is read without turning the first column into an index. E.g. like this:
pd.read_csv('output.csv', dtype='uint8', index=False)

A: This uses the pandas compressed datatype, but I only figured out how to apply it to the whole dataframe after it is built. NOTE: I assumed alls strings are strings not mixed integers and strings.
import pandas as pd
import numpy as np
strings = ['a','asd','1234','ewq']

# Find padding length
maxlen = max(len(s) for s in strings)

# Use 8 bit integer with pandas sparse data type, compressing zeros
dt = pd.SparseDtype(np.int8, 0)

# Create the sparse dataframe from a pandas Series for each integer ord value, padded with zeros
# NOTE: This compresses the dataframe after creation. I couldn't find the right way to compress
# each series as the dataframe is built

sdf = stringsSeries.apply(lambda s: pd.Series((ord(c) for c in s.ljust(maxlen,chr(0))))).astype(dt)
print(f"Memory used: {sdf.info()}")

# <class 'pandas.core.frame.DataFrame'>
# RangeIndex: 4 entries, 0 to 3
# Data columns (total 4 columns):
# 0    4 non-null Sparse[int8, 0]
# 1    4 non-null Sparse[int8, 0]
# 2    4 non-null Sparse[int8, 0]
# 3    4 non-null Sparse[int8, 0]
# dtypes: Sparse[int8, 0](4)
# memory usage: 135.0 bytes
# Memory used: None

# The original uncompressed size
df = stringsSeries.apply(lambda s: pd.Series((ord(c) for c in s.ljust(maxlen,chr(0)))))
print(f"Memory used: {df.info()}")

# <class 'pandas.core.frame.DataFrame'>
# RangeIndex: 4 entries, 0 to 3
# Data columns (total 4 columns):
# 0    4 non-null int64
# 1    4 non-null int64
# 2    4 non-null int64
# 3    4 non-null int64
# dtypes: int64(4)
# memory usage: 208.0 bytes
# Memory used: None


text:
Q: Firebase cloud messaging with Angular 12 and Firebase v9 I am using angular 12 and firebase v9. I have been trying to implement FCM with Angular and django. I have facing an issue maybe you have too. We can use this post to discuss and come to a solution.
Before you tell me that there are many posts about it, let me tell you I have tried everything that is on the internet. Tutorials are old, methods are depreciated. So we have to start new.
For the start, I have created a service worker called firebase-messaging-sw.js.
here is the code.
import { initializeApp } from "firebase/app";
import { getMessaging } from "firebase/messaging";

const firebaseApp = initializeApp({
apiKey: "***",
authDomain: "***",
databaseURL: "***",
projectId: "***",
storageBucket: "***",
messagingSenderId: "***",
appId: "***",
measurementId: "***"
});
const messaging = getMessaging(firebaseApp);

Then manifest.json
{
"gcm_sender_id": "***"
}

Added both of them in angular.json under assets and manifest.json in index.html, I put the code like:
<link rel="manifest" href="manifest.json">

Then i call the gettoken script in component code is
const messaging = getMessaging();
getToken(messaging, { vapidKey: '***'
}).then((currentToken) => {
              if (currentToken) {

                console.log('hey')
              } else {

                console.log('No registration token available. Request permission to
generate one.');

              }
            }).catch((err) => {
              console.log('An error occurred while retrieving token. ', err);

            });

Now after serving the app from HTTP or either ng serve -ssl
we are getting the above error.
Let's discuss this.
Update: I have added angular/pwa which created it's own service worker and manifest file. Should I add my firebase code it that??
Also on building the angular/pwa app, getting the error
service worker generation failed.
let's take time and solve this issue together.


text:
Q: CSS padding only displays correctly when element is floated I'm having issues with a button not displaying correctly, when the element is floated left or right the button displays fine, however if no float is applied the button doesn't display correctly.
I've prepared the following example to demonstrate:
http://codepen.io/anon/pen/xHvyt
My HTML and CSS are as follows:

Woop, title

content content content

            Find out more

Woop, title

content content content

            Find out more

Woop, title

content content content

            Find out more

CSS:
.section .textbox
{
    width:25%;
    z-index:2;
    padding:2.5%;
    text-align: center;
  background: #4a8237;
}

.section .textbox  h1
{
    font-weight: 800;
    font-size: 275%;
    margin:0;
    color:#FFF;
}

.section .textbox .text p
{
    margin:10% 0;
    color:#FFF;
}

.section .textbox .button
{
    width: 45%;
    text-align: center;
    background: url('http://i.imgur.com/dUYP3sP.png');
    border-radius: 5px;
    display: block;
    color:#FFF;
    white-space: nowrap;
}

.section .textbox .button.left
{
    float:left;
}

.section .textbox .button.right
{
    float:right;
}

.section .textbox .button.middle
{
    margin:0 auto;
}

.section .textbox .button span
{
    display: block;
    min-height: 40px;
    padding:10%;
    margin-bottom:10%;
    background: url('http://i.imgur.com/NvJtuDL.png') no-repeat center bottom;
}

As you can see there are three .section divs. In each the ones where the button is floated left/right it displays properly, however when no float is applied it's almost as is the span is not displaying:block;
Thanks in advance for any help.

A: Changing from "display:block" to "display:inline-block" seems to fix your problem without concerns about the floats.
 .section .textbox .button span
    {
        display: inline-block;
            min-height: 40px;
            padding:10%;
            margin-bottom:10%;
            background: url('http://i.imgur.com/NvJtuDL.png') no-repeat center bottom;
    }


text:
Q: What is the easiest control to use with Child of Eden for Xbox 360? Child of Eden for Xbox 360 can be played with the normal controller or with Kinect.
I like Kinect and always played with it, but I struggle a lot to finish the game: it seems to me that to cope with the speed and precision required you have to be borderline superhuman!
I wonder if my mistake is that I play with kinect and maybe with the normal controller it's easier.... the other alternative is that I'm a really poor player (that is probably the truth! :-)

A: Depends what you mean by easier. It seems to pull the difficulty down slightly when you play Kinect, but that's more than balanced out by how much harder it is to move you arms about than your thumbs.
This game is quite a bit harder than Rez though - the last level's pretty tough with a controller or Kinect. I couldn't beat the last level with Kinect, but I could (just) with the controller.


text:
Q: How can I tell my IDE to compile my CMake project a specific way? I have a CMake (mostly C, with some C++) project whose installation instructions are as follows:
mkdir build
cd build
cmake /*some options*/ ../
make

This works perfectly if I compile from the command-line.
I would like to use an IDE to compile this program so that I may debug it with a graphical debugger. However, when I attempt to compile using the IDE, I get linker errors.
I am unfamiliar with the internal workings of CMake and so am not sure how to achieve the desired behavior. In fact, I'm unsure if this is a CMake question at all; perhaps this is simply a question of IDE configuration. If it helps, the IDE I'm using is JetBrains' CLion.
The error given in the IDE is
The CMake file is
set(CMAKE_CXX_COMPILER "/Library/Developer/CommandLineTools/usr/bin/c++")
set(CMAKE_C_COMPILER "/Library/Developer/CommandLineTools/usr/bin/cc")
project(mpmc)
cmake_minimum_required(VERSION 3.8)
option(MPI "Use MPI to parallelize the calculations (requires MPI)" OFF)
option(CUDA "Use CUDA to offload polarization calculations to a GPU (requires CUDA)" OFF)
option(OPENCL "Use OpenCL to offload polarization calculations to a GPU (requires OpenCL)" OFF)
option(QM_ROTATION "Enable Quantum Mechanics Rigid Rotator calculations (requires LAPACK)" OFF)
option(VDW "Enable Coupled-Dipole Van der Waals (requires LAPACK)" OFF)

configure_file (
"${PROJECT_SOURCE_DIR}/src/include/cmake_config.h.in"
"${PROJECT_BINARY_DIR}/src/include/cmake_config.h"
)

set(CMAKE_BUILD_TYPE Release)

if(CMAKE_COMPILER_IS_GNUCC)
    set(CMAKE_C_FLAGS_DEBUG "${CMAKE_C_FLAGS_DEBUG} -Wall")
    set(CMAKE_C_FLAGS_RELEASE "${CMAKE_C_FLAGS_RELEASE} -Wall")
endif()

set(LIB m)

set(INCLUDE src/include/ src/mersenne/ ${PROJECT_BINARY_DIR}/src/include)

set(SRC
src/mc/mc_moves.c
src/mc/surface_fit_arbitrary.c
src/mc/qshift.c
src/mc/single_point.c
src/mc/mc.c
src/mc/replay.c
src/mc/pimc.c
src/mc/surface.c
src/mc/surf_fit.c
src/mc/fugacity.c
src/mc/cavity.c
src/mc/checkpoint.c
src/histogram/histogram.c
src/energy/lj_buffered_14_7.c
src/energy/bessel.c
src/energy/dreiding.c
src/energy/energy.c
src/energy/polar.c
src/energy/pbc.c
src/energy/disp_expansion.c
src/energy/vdw.c
src/energy/pairs.c
src/energy/bond.c
src/energy/coulombic_gwp.c
src/energy/exp_repulsion.c
src/energy/coulombic.c
src/energy/sg.c
src/energy/lj.c
src/energy/axilrod_teller.cpp
src/mersenne/mt.c
src/mersenne/dSFMT.h
src/mersenne/dSFMT.c
src/mersenne/dSFMT-common.h
src/mersenne/dSFMT-params.h
src/main/quaternion.c
src/main/CArng.c
src/main/memnullcheck.c
src/main/main.c
src/main/cleanup.c
src/main/usefulmath.c
src/io/dxwrite.c
src/io/simulation_box.c
src/io/average.c
src/io/output.c
src/io/check_input.c
src/io/input.c
src/io/mpi.c
src/io/read_pqr.c
src/io/setup_ocl.c
src/polarization/thole_field.c
src/polarization/polar_wolf_lookup.c
src/polarization/thole_polarizability.c
src/polarization/thole_matrix.c
src/polarization/polar_ewald.c
src/polarization/thole_iterative.c
)

if(MPI)
    message("-- MPI Enabled")
    find_package(MPI REQUIRED)
    if(NOT MPI_C_FOUND)
        message(FATAL_ERROR "-- MPI not found! Exiting ...")
    endif()
    set(INCLUDE ${INCLUDE} ${MPI_C_INCLUDE_PATH})
    set(LIB ${LIB} ${MPI_C_LIBRARIES})
else()
    message("-- MPI Disabled")
endif()

if(CUDA)
    message("-- CUDA Enabled")
    find_package(CUDA REQUIRED)
    set(SRC ${SRC} src/polarization_gpu/polar_cuda.cu)
else()
    message("-- CUDA Disabled")
endif()

if(OPENCL)
    message("-- OpenCl Enabled")
    set(CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH} ${CMAKE_SOURCE_DIR}/cmake)
    find_package(OpenCL REQUIRED)
    if(NOT OPENCL_FOUND)
        message(FATAL_ERROR "--OpenCl not found! Exiting ...")
    endif()
    set(SRC ${SRC}
        src/polarization_gpu/polar_ocl.c
        src/io/setup_ocl.c)
    set(INCLUDE ${INCLUDE} ${OpenCL_INCLUDE_DIRS})
    set(LIB ${LIB} ${OpenCL_LIBRARIES})
else()
    message("-- OpenCl Disabled")
endif()

if(QM_ROTATION)
    message("-- QM Rotation Enabled")
    set(SRC ${SRC}
        src/quantum_rotation/rotational_basis.c
        src/quantum_rotation/rotational_eigenspectrum.c
        src/quantum_rotation/rotational_integrate.c
        src/quantum_rotation/rotational_potential.c)
    set(LIB ${LIB} lapack)
else()
    message("-- QM Rotation Disabled")
endif()

if(VDW)
    message("-- CDVDW Enabled")
    if(NOT QM_ROTATION)
        set(LIB ${LIB} lapack)
    endif()
else()
    message("-- CDVDW Disabled")
endif()

include_directories(${INCLUDE})
if(CUDA)
    cuda_add_executable(${PROJECT_NAME} ${SRC})
else()
    add_executable(${PROJECT_NAME} ${SRC})
endif()
target_link_libraries(${PROJECT_NAME} ${LIB})

if(MPI)
    if(MPI_C_COMPILE_FLAGS)
      set_target_properties(${PROJECT_NAME} PROPERTIES
        COMPILE_FLAGS "${MPI_C_COMPILE_FLAGS}")
    endif()

    if(MPI_C_LINK_FLAGS)
      set_target_properties(${PROJECT_NAME} PROPERTIES
        LINK_FLAGS "${MPI_C_LINK_FLAGS}")
    endif()
endif()

And the directory structure is

A: You can point CLion to the build directory from your command line compile. Go to "File -> Settings -> Build, Execution, ... -> Cmake" and point the "generation path" to your "original" build directory. Otherwise CLion generates its own dir in "cmake-build-debug". Even after pointing CLion to the other dir it might still changes cmake variables depending on other parameters like "Debug/Release" Configuration on the same settings tab. Since from you cmake setup we can see that "Release" is the default, just switching that can potentially make the difference, without even switching the build dir.


text:
Q: What is the problem in my code when connecting to a database and outputting it to html and then to a website? I wrote code in golango to connect to the database on the server and output the contents of the tables to the website. I also wrote code for the html output of the table. There are no problems and it connects, but the error "404 page not found" lights up on the web page. What is this error and what is the reason? This is the first time I've seen this
package main

import (
    "database/sql"
    "fmt"
    _ "github.com/go-sql-driver/mysql"
    "html/template"
    _ "log"
    "net/http"
)

type Жанр struct {
    idЖанр         int
     Название_жанра string
}

var database *sql.DB

func home_db(w http.ResponseWriter, r *http.Request) {
     rows, err := database.Query("select * from newbd.Жанр")
     if err != nil {
         panic(err)
     }
     defer rows.Close()

     ganr := []Жанр{}
     for rows.Next() {
         p := Жанр{}
         err = rows.Scan(&p.idЖанр, &p.Название_жанра)
         if err != nil {
             panic(err)
             continue
         }
         ganr = append(ganr, p)
     }
     tmpl, _ := template.ParseFiles("home.html")
     tmpl.Execute(w, ganr)
}

func main() {
    db, err := sql.Open("mysql", "xxxxx:xxxxxx@tcp(xx.xx.xxx.xxx:xx)/xxxxx")
    if err != nil {
        panic(err)
    }
    defer db.Close()
    fmt.Println("OK")
    http.HandleFunc("/dat/", home_db)
    http.ListenAndServe(":8100", nil)
}

HTML
<!DOCTYPE html>

        <meta charset="UTF-8">
        <title>RUMP</title>

                idЖанр
                Название_жанра

            {{range . }}

                {{.idЖанр}}
                {{.Название_жанра}}

            {{.end}}


text:
Q: Develop a reusable Template project in Java So I have some files in java That I need to reuse every time I create a new project, is there a way to create a plug-in or template project where I can include all the files Im gonna reuse and then whenever I need to use em , I have just to call that plug-in or that template project ?

A: *

*Create a project that contains only the needed java classes

*Export that project into jar file

*Import that jar (the same way as you do for any external library) into your new project and they will be included

For example, in your old project (that contains the reused classes), you have a class called MyClass into a package called testPkg. After exporting that old project into a jar file and import it as library in the new project, each time you want to use MyClass you have to call that class using import testPkg.MyClass
PS: make sure to not use the same names of packages into the old and new projects


text:
Q: How to avoid creating several objects when applying casts? At the moment I am using several objects in order get a property from an event that require multiple casts.
I am concerning if there is a better, possibly shorter way how to do this.
System.Windows.RoutedEventArgs eventTrack = (System.Windows.RoutedEventArgs)e;
FluidKit.Controls.ElementFlow fluidItem = (FluidKit.Controls.ElementFlow)eventTrack.OriginalSource;
Client.DataModel.Advertisement adv = (Client.DataModel.Advertisement)fluidItem.ClickedItem;

string test = adv.ShopId.ToString();

A: Well, there isn't much you can do about it - you can try constructs like
Advertisement adv = ((e as RoutedEventArgs).OriginalSource as ElementFlow).ClickedItem as Advertisement;

but this is quite ugly. There is also method with dynamic keyword that is avaliable in .NET 4:
dynamic eventArgs = e;
dynamic adv = e.OriginalSource.ClickedItem;

but this has a disadvantage of performance impact.
I think the way you have it (maybe without those namespaces) is the best for code readability while maintaining low performance impact.

A: You can use multiple casting i the same line:
string adv = ((Client.DataModel.Advertisement)(((FluidKit.Controls.ElementFlow)(((System.Windows.RoutedEventArgs)e).OriginalSource)).ClickedItem)).ShopId.ToString();

Or you can use the dynamic keyword as Migol mentioned


text:
Q: Is session cookie with session_start() automatically available under Selenium WebDriver? what do I have to do to make the PHPSESSID cookie testable?
I have index.php where I set the cookie with session_start (), which gets me in "real life" the session cookie "PHPSESSID".
Now I just want to see that the cookie exists with
$I->amOnPage('/index.php');
$I->seeCookie('PHPSESSID');

but I get
Fail Failed asserting that an array contains 'PHPSESSID'.

Simple tests like see('something', 'h4') work just fine.
acceptance.suite.yml
 actor: AcceptanceTester
 modules:
     enabled:
         - WebDriver:
             url: http://nginx-web/
             browser: chrome
             host: chrome
             window_size: maximize
         - \Helper\Acceptance

I do run this in Docker with the below images, but that should not make any difference:
codeception/codeception:2.3.5 and
selenium/standalone-chrome-debug:3.7.1

Question: Do I have to do something else for the cookie to "come alive"? I am almost thinking I need to use setCookie in Codeception, but that does not seem logical (to manually create the cookie). If I did that, I could actually not test if session_start() works.
Any help is much appreciated!

A: It does have to do with the docker setup .... and other. Our nginx server is running behind a reverse proxy, plus we have checks, if you do not come from our domain, you are not allowed to perform specific actions. For some, not yet known reason, this also somehow interferes with the cookie, even right from the beginning.
Solution:
in your docker-compose set for the selenium image extra_hosts


text:
Q: Issue with area calculation in Google Earth Engine Using this code https://code.earthengine.google.com/36d0af209d34063ff109c57c40d1901e I calculate the area of pixels inside a set of 5km radius Features.
From the code results printed in the console, it is evident that the calculation leads to cases where the sum of area pixels calculated is substantially larger than the area of the feature itself (5^2 * pi), which makes no sense.
Where is the issue?
var getCentroid = function(feature) {
  var centroid = feature.geometry().centroid()
  return ee.Feature(centroid)
}

var table = ee.FeatureCollection("users/giacomofalchetta/UC_cities_global")

var table = table.map(getCentroid)

var bufferBy = function(size) {
  return function(feature) {
    return feature.buffer(size);
  };
};

var table = table.map(bufferBy(5000))

var area = ee.Image.pixelArea().divide(1000000)

var aFeatureCollection = area.reduceRegions({
  collection: table,
  reducer: ee.Reducer.sum(),
  scale: area.projection().nominalScale(),
});

print(aFeatureCollection.reduceColumns({
  reducer: ee.Reducer.max(),
  selectors: ['sum'],
}));

print(ee.Number.expression("(3.14159*5000*5000)/1e6"))

A: var area = ee.Image.pixelArea().divide(1000000)
...
  scale: area.projection().nominalScale(),

The default projection of ee.Image.pixelArea() is EPSG:4326 — WGS 84 longitude and latitude in degrees. Print the nominalScale() and you'll learn that the a degree at the equator is 111319.5 meters. Your 5000-meter-radius buffered point features fit inside a single one of these 111-km pixels — the reason you're getting a plausible value at all is solely because of weighting in the reduction.
If you use a smaller scale for the reduction, you will get a more accurate result.


text:
Q: How do I integrate my food order menu to Uber eat delivery service? API endpoints?
I need information about the get/post/put/del and authorization.
How do the customer order?
After customer paid and he/she choose Uber eat service, does he/she pick from my website or from the Uber eat app?
How does the customer pay? How does the business owner get paid? What kind of payment service can they use?


text:
Q: Is little-endian still faster on Intel processors or it does not matter if I parse big-endian on intel? It used to be in past architectures. Is it still the case? I am reading from the network into byte buffers in Java.

Basically, will read bytes on Intel using big-endian instead of little-endian make a difference in performance? I know intel is little-endian but when you read from a OS byte buffer, you can read in big-endian or little-endian.

A: You don't get to choose. Processors are (with a very small number of exceptions) fixed in their endianness, so when you have data to manipulate, you MUST put it into the proper format for your CPU. It's not a choice, and it's not a performance issue: it's just what must be done.
The only time it comes up much is when serializing data. Many common network protocols were designed with big-endian on-the-wire representations. If you read those bytes straight into memory on an Intel CPU, you have to swap the bytes around to make them little-endian before you can work with them. This isn't a big deal, and again, isn't a choice - the network protocol is what it is, and you don't get a choice about how to put things on the wire if you want other systems to be able to understand your packets.


text:
Q: Parsing JSON to excel with auth key VBA I am trying to post the json of an api with auth key and here is the sample JSON.
I read and researched the topic but I am a newbie with vba and can't seem to determine the problem.
I get the error Run-time error 13 Type mismatch
I only want to post the results name, room, lastupdate, updatedat to excel.
I am sorry in advance but this is the code so far I tried.
Option Explicit

Sub Test()

    Dim sJSONString As String
    Dim vJSON
    Dim sState As String
    Dim aData()
    Dim aHeader()
    Dim vResult
    Dim authKey As String

    authKey = "whatverthekeyis"

    ' Retrieve JSON content
    With CreateObject("MSXML2.XMLHTTP")
        .Open "GET", "whateverthehttp", True
        .SetRequestHeader "Authorization", "Bearer " & authKey
        .Send
        Do Until .readyState = 4: DoEvents: Loop
        sJSONString = .responseText
    End With
    ' Parse JSON sample
    JSON.Parse sJSONString, vJSON, sState
    If sState = "Error" Then MsgBox "Invalid JSON": End
    ' Convert raw JSON to 2d array and output to worksheet #1
    JSON.toArray vJSON("data"), aData, aHeader
    With ThisWorkbook.Sheets(1)
        .Cells.Delete
        .Cells.WrapText = False
        OutputArray .Cells(1, 1), aHeader
        Output2DArray .Cells(2, 1), aData
        .Columns.AutoFit
    End With
    MsgBox "Completed"

End Sub

Sub OutputArray(oDstRng As Range, aCells As Variant)

    With oDstRng
        .Parent.Select
        With .Resize(1, UBound(aCells) - LBound(aCells) + 1)
            .NumberFormat = "@"
            .Value = aCells
        End With
    End With

End Sub

Sub Output2DArray(oDstRng As Range, aCells As Variant)

    With oDstRng
        .Parent.Select
        With .Resize( _
                UBound(aCells, 1) - LBound(aCells, 1) + 1, _
                UBound(aCells, 2) - LBound(aCells, 2) + 1)
            .NumberFormat = "@"
            .Value = aCells
        End With
    End With

End Sub

I have the json.bas,jsonext.bas and script runtime on.
Thanks a lot!
Error is in line
JSON.ToArray vJSON("data"), aData, aHeader


text: Q: BitBucket Git Branches model I don't understand , why i can't see splitted branches in bitbucket (website).So i downloaded SourceTree where everything is ok. But i want to know how make branches in web version like  at second picture (SourceTree)


text:
Q: Ubuntu snap packaging with Qt: fonts missing I have binary and all resolved Qt dependencies packaged in tar.gz. I am using next yaml file for snap:
name: sample_name_lol_1
base: core18
version: '1.0.0'
summary: sample_summary_lol_2
description: |
  sample_desc_lol_3

grade: devel
confinement: devmode

parts:
  sample_name_lol_1:
    plugin: dump
    source: MyApp.tar.gz
    stage-packages: [
      ffmpeg,
      x264,
      x265,
      libopencv-core-dev,
      libopencv-imgproc-dev,
      libopencv-calib3d-dev,
      libblas-dev,
      liblapack-dev,
      libfontconfig1-dev,
      fonts-freefont-ttf,
      ttf-ubuntu-font-family
    ]

apps:
    MyApp:
        command: MyApp
        environment:
          LD_LIBRARY_PATH: $LD_LIBRARY_PATH:$SNAP/usr/lib/x86_64-linux-gnu/blas:$SNAP/usr/lib/x86_64-linux-gnu/lapack

Normal application run (say from regular unpacking tar.gz) would give me information about all fonts available on the system. However snap run (sample_name_lol_1.MyApp) won't see system fonts, only few of them (only 3 to be precise - sans, sans-serif, monospace). I found path after installation, /snap/sample_name_lol_1/x1/usr/share/fonts and /snap/sample_name_lol_1/x1/etc/fonts. Those places are read-only and I can't figure out, what exactly should be done, so Qt application will able to see at lease standard Ubuntu font.

A: I had to work with user configuration folder that snap creates.

*

*Create wrapper and use as main app. Wrapper will call actual application.

*Before starting application, wrapper will copy file from $SNAP/etc/fonts/fonts.conf to $SNAP_USER_DATA/.config/fontconfig/fonts.conf.

*Also application will modify newly copied file using "sed -i" command, where directories were changed to $SNAP location. Example: <dir>/usr/fonts... will become <dir>/snap/your_app/version/...

It doesn't seem like a clean solution, however it's acceptable solution for me by now.
name: sample_name
base: core18
version: '1.0.0'
summary: Sample Summary
description: |
  Sample Desc

grade: devel
confinement: devmode

parts:
  sample_name:
    plugin: dump
    source: sample_name.tar.gz
    stage-packages: [
      ffmpeg,
      x264,
      x265,
      libopencv-core-dev,
      libopencv-imgproc-dev,
      libopencv-calib3d-dev,
      libblas-dev,
      liblapack-dev,
      ttf-ubuntu-font-family
    ]
  fix-fontconfig:
    plugin: nil
    override-build: |
      mkdir $SNAPCRAFT_PART_INSTALL/bin
      echo "mkdir \$SNAP_USER_DATA/.config" >> $SNAPCRAFT_PART_INSTALL/bin/sample-wrapper.sh
      echo "mkdir \$SNAP_USER_DATA/.config/fontconfig" >> $SNAPCRAFT_PART_INSTALL/bin/sample-wrapper.sh
      echo "cp \$SNAP/etc/fonts/fonts.conf \$SNAP_USER_DATA/.config/fontconfig/fonts.conf" >> $SNAPCRAFT_PART_INSTALL/bin/sample-wrapper.sh
      echo "sed -i \"s#<dir>/usr#<dir>\$SNAP/usr#g\" \$SNAP_USER_DATA/.config/fontconfig/fonts.conf" >> $SNAPCRAFT_PART_INSTALL/bin/sample-wrapper.sh
      echo "\$SNAP/sample_name" >> $SNAPCRAFT_PART_INSTALL/bin/sample-wrapper.sh
    after: [sample_name]

apps:
    sample_name:
        command: sh $SNAP/bin/sample-wrapper.sh
        environment:
          LD_LIBRARY_PATH: $LD_LIBRARY_PATH:$SNAP/usr/lib/x86_64-linux-gnu/blas:$SNAP/usr/lib/x86_64-linux-gnu/lapack


text:
Q: Diophantine equation of type $ax^2+bx+cy^2=n$ Is there a recipe for, or are there practical examples of, solving Diophantine equations of type $ax^2+bx+cy^2=n$. How would I prove that a particular equation has no ( Integer ) solutions for $x, y$? $(a, b, c, n)$ are integers not equal to $0$.

A: Legendre famously solved the general quadratic equation
$$
ax^2+bxy+cy^2+dx+ey+f=0
$$
by noting that
\begin{equation*}
4a(b^2-4ac)(ax^2+bxy+cy^2+dx+ey+f) = 0 \tag{$\star$}
\end{equation*}
along with the assumption $a(b^2-4ac) \ne 0$ forces $ax^2+bxy+cy^2+dx+ey+f=0$, while simultaneously implying the Pell equation
\begin{align}
 &\bigl((b^2-4ac)y-2ae+bd\bigr)^2 - (b^2-4ac)(2ax+by+d)^2  \\
  &\hspace{16em}= 4a(ae^2+b^2f+cd^2-bde-4acf). \tag{$\dagger$}
\end{align}
Setting $b=e=0$ and $f=-n$, and then rewriting $d \to b$, we have your equation
$$
ax^2+bx+cy^2=n.
$$
There have also been myriad solutions of special cases in the past couple hundred years. An excellent survey and reference is Dickson's History of the Theory of Numbers, with Volumes II and III of particular interest.


text:
Q: Aggregating binary data into a "score" reduces CI...Does it increase the validity? I have 5 variables that I've used to calculate a score with. Each variable contributes 0-2 points to the score depending on their value.
I'm interested in whether these predictors better can predict the outcome (disease status) by themselves or if a score of all would predict the outcome better.
The score works very well in a regression model and seems to be able to predict disease status with p=0.003 and a satisfactory confidence interval (CI). The 5 binary variables are also significant but with very large CI. Does this mean that the score has a higher validity than the binary variables on their own?
Also if I run a regression model with all 5 predictors, the R-squared is 0.35 and the model P value is 0.01, with only one of the predictors being significant in the model, though. Is this worth noting in the manuscript? I'm not exactly sure what it means other than that the model itself is good at predicting disease status.
DATA: https://gofile.io/?c=t8Htvb

A:
Does this mean that the score has a higher validity than the binary variables on their own?

Precision and validity are not the same thing.  I can estimate something very precisely and have it be invalid.  You'll need to determine what your hypothesis actually is before you select a regression model.  Are you interested in how the composite score affects the outcome, or how each component of the score affects the outcome?  The answer to this question will help inform which model you should select.
That the CIs are "very large" might also mean that the 5 predictors are highly correlated.  I can't say for sure without seeing the data.


text:
Q: Sending survey with apex Im trying to send surveys Apex, as indicated in the documentation, we must pass a String and a ConnectApi.SurveyInvitationEmailInput, but passing these parameters gives me the following error:
Method does not exist or incorrect signature: void sendSurveyInvitationEmail(String, ConnectApi.SurveyInvitationEmailInput) from the type Survey.
I've also tried not to pick up what it returns but it doesn't work this way either. The survey settings are activated in my org. What am I missing?
Documentation: https://developer.salesforce.com/docs/atlas.en-us.apexref.meta/apexref/apex_ConnectAPI_Survey_static_methods.htm#apex_ConnectAPI_Surveys_sendSurveyInvitationEmail_1
Code:
        String surveyId = [SELECT Id FROM Survey WHERE DeveloperName = 'survey_test' LIMIT 1][0].Id;
        ConnectApi.SurveyInvitationEmailOutput surveyOutput = new ConnectApi.SurveyInvitationEmailOutput();
        ConnectApi.SurveyInvitationEmailInput surveyInput = new ConnectApi.SurveyInvitationEmailInput();
        surveyOutput = Survey.sendSurveyInvitationEmail(surveyId, surveyInput);

A: The ApexType is Surveys, not Survey in the ConnectApi namespace. Survey is in namespace Schema and represents the SObject.
surveyOutput = ConnectApi.Surveys.sendSurveyInvitationEmail(surveyId, surveyInput);


text:
Q: Execute a command on Remote Machine in Python I am writing a program in python on Ubuntu, to execute a command ls -l on RaspberryPi, connect with Network.
Can anybody guide me on how do I do that?

A: Sure, there are several ways to do it!
Let's say you've got a Raspberry Pi on a raspberry.lan host and your username is irfan.
subprocess
It's the default Python library that runs commands.
You can make it run ssh and do whatever you need on a remote server.
scrat has it covered in his answer. You definitely should do this if you don't want to use any third-party libraries.
You can also automate the password/passphrase entering using pexpect.
paramiko
paramiko is a third-party library that adds SSH-protocol support, so it can work like an SSH-client.
The example code that would connect to the server, execute and grab the results of the ls -l command would look like that:
import paramiko

client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect('raspberry.lan', username='irfan', password='my_strong_password')

stdin, stdout, stderr = client.exec_command('ls -l')

for line in stdout:
    print line.strip('\n')

client.close()

fabric
You can also achieve it using fabric.
Fabric is a deployment tool which executes various commands on remote servers.
It's often used to run stuff on a remote server, so you could easily put your latest version of the web application, restart a web-server and whatnot with a single command. Actually, you can run the same command on multiple servers, which is awesome!
Though it was made as a deploying and remote management tool, you still can use it to execute basic commands.
# fabfile.py
from fabric.api import *

def list_files():
    with cd('/'):  # change the directory to '/'
        result = run('ls -l')  # run a 'ls -l' command
        # you can do something with the result here,
        # though it will still be displayed in fabric itself.

It's like typing cd / and ls -l in the remote server, so you'll get the list of directories in your root folder.
Then run in the shell:
fab list_files

It will prompt for an server address:
No hosts found. Please specify (single) host string for connection: irfan@raspberry.lan

A quick note: You can also assign a username and a host right in a fab command:
fab list_files -U irfan -H raspberry.lan

Or you could put a host into the env.hosts variable in your fabfile. Here's how to do it.

Then you'll be prompted for a SSH password:
[irfan@raspberry.lan] run: ls -l
[irfan@raspberry.lan] Login password for 'irfan':

And then the command will be ran successfully.
[irfan@raspberry.lan] out: total 84
[irfan@raspberry.lan] out: drwxr-xr-x   2 root root  4096 Feb  9 05:54 bin
[irfan@raspberry.lan] out: drwxr-xr-x   3 root root  4096 Dec 19 08:19 boot
...

A: Simple example from here:
import subprocess
import sys

HOST="www.example.org"
# Ports are handled in ~/.ssh/config since we use OpenSSH
COMMAND="uname -a"

ssh = subprocess.Popen(["ssh", "%s" % HOST, COMMAND],
                       shell=False,
                       stdout=subprocess.PIPE,
                       stderr=subprocess.PIPE)
result = ssh.stdout.readlines()
if result == []:
    error = ssh.stderr.readlines()
    print >>sys.stderr, "ERROR: %s" % error
else:
    print result

It does exactly what you want: connects over ssh, executes command, returns output. No third party library needed.

A: You may use below method with linux/ Unix 's built in ssh command.
   import os
   os.system('ssh username@ip  bash < local_script.sh >> /local/path/output.txt 2>&1')
   os.system('ssh username@ip  python < local_program.py >> /local/path/output.txt 2>&1')

A: Paramiko module can be used to run multiple commands by invoking shell. Here I created class to invoke ssh shell
class ShellHandler:
def __init__(self, host, user, psw):
    logger.debug("Initialising instance of ShellHandler host:{0}".format(host))
    try:
        self.ssh = paramiko.SSHClient()
        self.ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        self.ssh.connect(host, username=user, password=psw, port=22)
        self.channel = self.ssh.invoke_shell()
    except:
        logger.error("Error Creating ssh connection to {0}".format(host))
        logger.error("Exiting ShellHandler")
        return
    self.psw=psw
    self.stdin = self.channel.makefile('wb')
    self.stdout = self.channel.makefile('r')
    self.host=host
    time.sleep(2)

    while not self.channel.recv_ready():
        time.sleep(2)
    self.initialprompt=""
    while self.channel.recv_ready():

        rl, wl, xl = select.select([ self.stdout.channel ], [ ], [ ], 0.0)
        if len(rl) > 0:
            tmp = self.stdout.channel.recv(24)
            self.initialprompt=self.initialprompt+str(tmp.decode())

def __del__(self):
    self.ssh.close()
    logger.info("closed connection to {0}".format(self.host))

def execute(self, cmd):
    cmd = cmd.strip('\n')
    self.stdin.write(cmd + '\n')
    #self.stdin.write(self.psw +'\n')
    self.stdin.flush()
    time.sleep(1)
    while not self.stdout.channel.recv_ready():
        time.sleep(2)
        logger.debug("Waiting for recv_ready")

    output=""
    while self.channel.recv_ready():
        rl, wl, xl = select.select([ self.stdout.channel ], [ ], [ ], 0.0)
        if len(rl) > 0:
            tmp = self.stdout.channel.recv(24)
            output=output+str(tmp.decode())
    return output

If creating different shell each time does not matter to you then you can use method as below.
def run_cmd(self,cmd):
    try:
        cmd=cmd+'\n'
        #self.ssh.settimeout(60)
        stdin,stdout,stderr=self.ssh.exec_command(cmd)
        while not stdout.channel.eof_received:
           time.sleep(3)
           logger.debug("Waiting for eof_received")
        out=""
        while stdout.channel.recv_ready():
            err=stderr.read()
            if err:
                print("Error: ",my_hostname, str(err))
                return False

            out=out+stdout.read()
        if out:
               return out

    except:
        error=sys.exc_info()
        logger.error(error)
        return False


text:
Q: How to get the value of a static field in a generic class (singleton) without knowing the generic type Ok, I try to explain my question a bit better: I have a
class DynamicTypeCreator{...}
and a method in it:
static BuildASingletonClassWithTypeBuiler<T> (T object) {...}
This method not only creates a singleton type
class Singleton01<K> {...}
but also instantiates it, defining the field
static Singleton01<K> instance = new Singleton01<K> (K object)
and another field
static Type typeOfGenericParameter = typeof(K).
(The actual code on https://github.com/TThaan/ExtensionPropertiesForCSharp is different but that should be of no concern.)
However this method does not return the singleton type nor the instance. It's just creating them.
Plenty of times, indeed, only changing the name of the type from Singleton01 to Singleton02, Singleton03 etc and each time with a different T object as parameter.
So when I want to access one of those singletons later I don't know what object it holds and of what type it is. To get the value of any static field in eg "Singleton03" I first use
Type type = AssemblyBuilder.GetType("Singleton03").
Trying to get a value of a static field now does not work yet, it's just null. I seem to be forced to use
Type genericType = type.MakeGenericType(new[] { typeof(T) }).
But for this to work I already need to know the type of my parameter T object.
I want to know if there is a way to get the value of a static field in such a generic type before using .MakeGeneric().

A: I found an answer now.
Since a generic class of one type is actually a different class then "the same class" of another type,
the static field in one of those classes is different from that in the other class. Therefore I can't get the value of one of those fields before using .MakeGeneric() with the fitting type.
The solution is to change the creation of my class, eg like here:
Generic classes and static fields.


text:
Q: What's the meaning of "twice continuously differentiable"?
The picture is from Complex Analysis by Stein.
What's the meaning of "twice continuously differentiable"?

A: It means that the functions $\dfrac{\partial^2u}{\partial x^2}$, $\dfrac{\partial^2u}{\partial x\partial y}$, and $\dfrac{\partial^2u}{\partial y^2}$ exist and are continuous.

A: Twice continuously differentiable means the second derivative exists and is continuous.


text:
Q: Supervisord action if service restart I want to create a file when the service is restarted.
rpm -qa | grep super
 supervisor-3.1.3-0.5.b1.el6.noarch

My config file:
[program:tests]
command=/root/while.sh
directory=/root
user=root
autostart=true
autorestart=true

[eventlistener:tests_ls]
command=touch /tmp/32
events=PROCESS_STATE

My log file error
2016-06-27 10:48:15,794 ERRO pool tests_ls event buffer overflowed, discarding event 8
2016-06-27 10:48:15,794 INFO exited: tests_ls (exit status 0; not expected)
2016-06-27 10:48:16,796 ERRO pool tests_ls event buffer overflowed, discarding event 9
2016-06-27 10:48:16,796 INFO gave up: tests_ls entered FATAL state, too many start retries too quickly
2016-06-27 10:48:39,155 ERRO pool tests_ls event buffer overflowed, discarding event 10
2016-06-27 10:48:39,155 INFO exited: tests (terminated by SIGKILL; not expected)
2016-06-27 10:48:40,157 ERRO pool tests_ls event buffer overflowed, discarding event 11
2016-06-27 10:48:40,160 INFO spawned: 'tests' with pid 26378
2016-06-27 10:48:41,163 ERRO pool tests_ls event buffer overflowed, discarding event 12

supervisorctl
 tests                            RUNNING   pid 26378, uptime 0:09:02
 tests_ls                         FATAL     Exited too quickly (process log may have details)

Where did I go wrong?


text:
Q: Sendgrid import issue in Meteor I'm trying to use sendgrid npm package in Meteor (on the server):
const sendgridMail = require('@sendgrid/mail');

Keep getting this error:
(STDERR) packages\modules.js:961
(STDERR) const {
(STDERR)       ^
(STDERR)
(STDERR) SyntaxError: Unexpected token {
(STDERR)     at Object.exports.runInThisContext (vm.js:53:16)
(STDERR)     at D:\myProject\.meteor\local\build\programs\server\boot.js:331:30
(STDERR)     at Array.forEach (native)
(STDERR)     at Function._.each._.forEach (C:\Users\user1\AppData\Local\.meteor\packages\meteor-tool\1.5.2\mt-os.windows.x86_32\dev_bundle\server-lib\node_modules\underscore\underscore.js:79:11)

Any ideas how to fix it?
Update: package.json includes the following dependencies:
"dependencies": {
    "@sendgrid/client": "^6.1.4",
    "@sendgrid/mail": "^6.1.4",
    "babel-runtime": "^6.20.0",
    "bcrypt": "^1.0.2",
    "body-parser": "^1.17.2",
    "card": "^2.3.0",
    "google-auth-library": "^0.10.0",
    "googleapis": "^21.3.0",
    "meteor-node-stubs": "~0.2.4",
    "moment": "^2.18.1",
    "pnotify": "^3.2.0",
    "shortid": "^2.2.8",
    "simpl-schema": "^0.3.1",
    "stripe": "^4.24.0"
}

A: I use it like this, and find it works fine.
import sendgridModule from 'sendgrid';

let SEND_GRID_API_KEY = '';
try {
  SEND_GRID_API_KEY = Meteor.settings.env.SEND_GRID_API_KEY;
} catch (e) {
  // no-op
}
const sendgrid = sendgridModule(SEND_GRID_API_KEY);

I think using import instead of require is preferred, and it now can be used for conditional imports

A: The problem is that SendGrid SDK v6 requires Node.js version 6 and higher, but the one bundled in Meteor is 4.8.4:
$ meteor node --version
v4.8.4

As stated in this issue, updating Node.js will help, but it's obviously can't be done with Meteor.
I suggest you to use sendgrid npm package, this one works fine with Node.js v4.


text:
Q: Robotframework and Selenium2Library - browser doesn't load page I'm having a problem while I'm trying to open a browser. I'm writing tests in RIDE and when I run the test, the browser opens but doesn't display the page...
The browser only displays a message: "the connection has timed out"
Did anyone face this problem?
Here's the code:
    *** Settings ***
Library           Selenium2Library

*** Variables ***
${Username}       student2
${Password}       Testing1
${SiteUrl}        http://demo.mahara.org
${DashboardTitle}    Dashboard - Mahara
${Delay}          5s

*** Test Cases ***
Test2
    Open Browser to the Login Page
    Enter User Name
    Enter Password
    Click Login
    sleep    $(Delay)
    Assert Dashboard Title
    [Teardown]    Close Browser

*** Keywords ***
Open Browser to the Login Page
    Open Browser    http://demo.mahara.org

Enter User Name
    Input Text    login_login_username    ${Username}

Enter Password
    Input Text    login_login_password    ${Password}

Click Login
    Click Button    login_submit

Assert Dashboard Title
    Title Should Be    ${DashboardTitle}

Btw the firefox version: 31.0
selenium version: 2.53.6
selenium2Library version: 1.7.4
Any solution? Thanks in advance ;)

A: Here's working code:
*** Settings ***
Library           Selenium2Library

*** Variables ***
${Username}       student2
${Password}       Testing1
${SiteUrl}        http://demo.mahara.org
${DashboardTitle}    Dashboard - Mahara
${Delay}          5s
${FF_PROFILE}     C:\\ff_profile

*** Test Cases ***
Test2
    Open Browser to the Login Page
    Enter User Name
    Enter Password
    Click Login
    Sleep    ${Delay}
    Assert Dashboard Title
    [Teardown]    Close Browser

Test3

*** Keywords ***
Open Browser to the Login Page
    Open Browser    http://demo.mahara.org    firefox    ff_profile_dir=${FF_PROFILE}

Enter User Name
    Input Text    login_login_username    ${Username}

Enter Password
    Input Text    login_login_password    ${Password}

Click Login
    Click Button    login_submit

Assert Dashboard Title
    Title Should Be    ${DashboardTitle}


text:
Q: Konqueror randomly showing same search results In Konqueror I use startpage.com as searchengine. Recently I began to notice that no matter what I search for the searchengine is randomly showing the same results page. I clean the cache at every shutdown, I've removed and reinstalled Konqueror and still the same page is shown randomly. I believe it is not an intentional action on the part of startpage.com. Since malware is very unusual on Linux I believe I can rule that out too. So I wonder how do I get rid of the page.
This is the relevant part of the page shown:


text:
Q: Analyze the convergence of the series $\sum_{n=1}^{\infty} \frac{\cos (in)}{2^{n}}$ Analyze the convergence of the series $\sum_{n=1}^{\infty} \frac{\cos (in)}{2^{n}}$.
$a_n=\frac{1}{2^n}, \quad b_n=\cos(in), \quad \lim(a_{n})=0$ but $\lim(b_{n})$ does not exist. So I think the series diverges. How do I prove it formally?

A: Observe that
$$ \frac{\cos(in)}{2^n} = \frac{\cosh(n)}{2^{n}} = \frac{e^{-n} + e^{n}}{2^{n+1}}.$$
Now $\frac{e^{-n}}{2^{n+1}} \to 0$ and $\frac{e^{n}}{2^{n+1}}$ does not converge to 0 (you may check that $f(x) = \frac{e^x}{2^{x+1}}$ has positive derivative for every $x>0$) and hence $\frac{\cos(in)}{2^n}$ does not converge to 0 and the series diverges.

A: Indeed,
$$\frac{e^{i^2n}+e^{-i^2n}}{2^{n+1}}$$ yields the sum of two geometric series of ratios $\dfrac1{2e}$ and $\dfrac e2$, and the second diverges.


text:
Q: ParseObject#pin lock the thread I use ParseObject.pin method in AsyncTaskLoader.loadInBackground and it just lock the thread. Why? how to avoid it?
UPD code example
public class MyLoader extends AsyncTaskLoader<Object>{
    @Override
    public Object loadInBackground() {
        HashMap params = new HashMap();
        try {
            HashMap result = ParseCloud.callFunction("myFunction",params);
            ParseObject object = (ParseObject) result.get("some_field");
            object.fetchIfNeeded();
            object.pin();
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return null;
    }
}

A: According to this issue https://github.com/ParsePlatform/Parse-SDK-Android/issues/61 there is a linear time dependency. so pinning can take a lot of time. It seams like thread locking.


text:
Q: Combobox databinding with multiple sources I recently switched from visual basic 5 to visual basic .NET and I'm trying to learn WPF converting an old program from Windows Forms (written using visual basic 5) to WPF&VB.NET.
In the old program I have a combobox with information loaded from an access database (a simple table with item_id and item_description). Clicking on an item in the combobox causes the id to be saved in a class (which saves its informations in a different table in the database)
Now I'm trying to recreate the same thing in WPF.
I was wondering if it is possibile to have the combobox display the items from the items list binding its itemsource to the items list viewmodel but updating another viewmodel when I change the selected item.
I don't know if it is feasible (and I honestly I tried to find an answer in the web, but looking for "combobox multiple databinding" I end up finding informations that don't help me)

A: Not sure if I really understand what you mean, but you can set an itemsource which will be the  content of the combo box. It is also possible to bind the selected value of the combo box to another property.
<ComboBox ItemSource="ListItems" SelectedValuePath="item_id" SelectedValue={Binding IdSelected} DisplayMemberPath="item_description"/>

In this exemple, ListItems would be the list that contains the items, SelectedValuePAth will be the name of the property that will be returned by the combobox SelectedValue property. SelectedValue binds to a property of some other object that needs this info. DisplayMemberPath is the property that will be shown to the user.
You can set the itemssource at runtime by using CboItem.Itemssource = listItem, which can be pretty any type of collection (List of, dataset, array, etc.)
Hope that helps.


text:
Q: Solve the equation: $1+2^x+4^x+8^x+16^x+32^x=3(1+2^x+4^x)$ I am doing some math repetition and am a bit stuck on this exercise:
Solve the equation: $1+2^x+4^x+8^x+16^x+32^x=3(1+2^x+4^x)$.
Now, this is a geometric sum on both the $LHS$ and $RHS$, which I guess is something that I should use to solve the equation...
Another way is to simply start to eliminate terms:
$$1+2^x+4^x+8^x+16^x+32^x=3+3 \times 2^x+3\times4^x$$
$$-2 -2\times 2^x -2\times4^x+8^x+16^x+32^x = 0$$
$$8^x+16^x+32^x = 2 +2\times 2^x +2\times4^x$$
$$8^x+16^x+32^x = 2(1 + 2^x + 4^x)$$
But I am stuck here...

A: Note that the left side of the equation can be written as
$2^0+2^x+2^{2x}+2^{3x}...2^{5x}$
This is a geometric series, with
a=1, n=6, and $r=2^x$
We use the formula:
$S_n = \frac {a(1-r^n)}{1-r}$
Substitute the values, you get
$S=\frac{(1-2^{6x})}{1-2^x}$
We do the same for the right side
$S=3[\frac{1-2^{3x}}{1-2^x}]$
Equate the terms, and rearrange
$\frac{(1-2^{6x})}{1-2^x}=3[\frac{1-2^{3x}}{1-2^x}]$
$1-2^{6x}=3-3\cdot2^{3x}$
$-2^{6x}+3\cdot2^{3x}-2=0$
And this bit is my fave.
It's just a quadratic!
Because $-2^{6x} = -(2^{3x})^2$
Now you just let $2^{3x}$ = u
$-u^2+3u-2=0$
Solve for u
Then you just sub back $2^{3x}$
And there you have it.
If I have made an error (as I am prone to), notify me and I will withdraw my answer.
Thanks

A: Setting $2^x=a,$
We have $$1+a+a^2+a^3(1+a+a^2)=3(1+a+a^2)$$
$$\iff (1+a+a^2)(a^3-2)=0$$
If $x$ is real $2^x>0\implies1+a+a^2>0$
So, we have $2=(2^x)^3\iff2^{3x-1}=1$
Now if $b^m=1$
either $m=0,b\ne0$
or $b=1$
or $b=-1,m$ is even


text:
Q: How to finalize the scroll class change? class change at li
when li gets into the viewport - there is a class change
enter code here https://jsfiddle.net/2b5Lqfcd/

A: You can add an event listener that listens for scroll and when event happens you can add the class you want to add


text:
Q: How to use LIKE clause/condition in Arcpy.Exists/Delete I would like to delete several raster files in an ArcSDE SQL Server database.  I would like to do so with Arcpy.  How can I succesfully use a LIKE condition to delete all files in my database that have a certain string of characters, such as _.  Meaning that I want to delete all files that contain an underscore.  Using the example from Esri, where would I delete all files that for instance contain roadbuffer.
import arcpy

# Set the current workspace
#
arcpy.env.workspace = "c:/base/data.gdb"

# Check for existence of data before deleting
#
if arcpy.Exists("roadbuffer"):
    arcpy.Delete_management("roadbuffer")

A: Wildcard searching is built into arcpy.ListRasters():
import arcpy

arcpy.env.workspace = "c:/base/data.gdb"

for raster in arcpy.ListRasters("*_*"):
    arcpy.Delete_management(raster)

If you want more advanced wildcarding/filtering, you'll need to use regex.


text:
Q: GraphPlot only working when I evaluate twice I have some code that builds a graph and some vertex coordinates, but when I evaluate it I get a message that the list of coordinates is not valid and the graph is not valid and it shows the output as an unevaluated GraphPlot. Then if I evaluate the unevaluated GraphPlot manually it works fine. I have tried using Evaluate manually, but no luck.
I evaluate this:
GraphPlot[edges, VertexCoordinateRules -> coords]

I get these:

GraphPlot::vpr: Value of option VertexCoordinateRules -> {{1,2,3,4,5,6,7,8,9,10,11}->{1.,1.79586*10^-10},{1,10,3,11,7,6,5,9,8,2,4}->{0.,2.6938*10^-10},{8,9,4,1,2,5,7,3,6,10,11}->{2.,0.}} is not a valid list of coordinate rules. >>
GraphPlot::grph: {{1,2,3,4,5,6,7,8,9,10,11}->{1,10,3,11,7,6,5,9,8,2,4},{1,2,3,4,5,6,7,8,9,10,11}->{8,9,4,1,2,5,7,3,6,10,11},{1,10,3,11,7,6,5,9,8,2,4}->{1,2,3,4,5,6,7,8,9,10,11},{1,10,3,11,7,6,5,9,8,2,4}->{9,8,11,1,10,7,5,3,6,2,4},{8,9,4,1,2,5,7,3,6,10,11}->{3,6,1,8,9,2,7,4,5,10,11},{8,9,4,1,2,5,7,3,6,10,11}->{8,10,4,11,7,5,2,6,3,9,1}} is not a valid graph. >>

GraphPlot[{{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11} -> {1, 10, 3, 11, 7, 6,
     5, 9, 8, 2, 4}, {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11} -> {8, 9, 4,
    1, 2, 5, 7, 3, 6, 10, 11}, {1, 10, 3, 11, 7, 6, 5, 9, 8, 2,
    4} -> {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11}, {1, 10, 3, 11, 7, 6, 5,
     9, 8, 2, 4} -> {9, 8, 11, 1, 10, 7, 5, 3, 6, 2, 4}, {8, 9, 4, 1,
    2, 5, 7, 3, 6, 10, 11} -> {3, 6, 1, 8, 9, 2, 7, 4, 5, 10, 11}, {8,
     9, 4, 1, 2, 5, 7, 3, 6, 10, 11} -> {8, 10, 4, 11, 7, 5, 2, 6, 3,
    9, 1}}, VertexCoordinateRules -> {{1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
     11} -> {1., 1.79586*10^-10}, {1, 10, 3, 11, 7, 6, 5, 9, 8, 2,
     4} -> {0., 2.6938*10^-10}, {8, 9, 4, 1, 2, 5, 7, 3, 6, 10,
     11} -> {2., 0.}}]

Then if I manually evaluate the output it works fine. Here is the full code. I haven't figured out a smallest repro yet.
{op1, op2} = GroupGenerators@MathieuGroupM11[];
elems = {Range[11]};
edges = {};
coords = {};
frames = {};
frames = Reap@
  While[Length@elems < 10,
   AppendTo[elems, Permute[#, op1]]; AppendTo[elems, Permute[#, op2]];
      AppendTo[edges, # -> Permute[#, op1]];
     AppendTo[edges, # -> Permute[#, op2]]; & /@ elems;
   elems = Union[elems]; edges = Union[edges];
   Sow[g = GraphPlot[edges,
      VertexCoordinateRules ->
       If[Length@coords > 0, coords, Automatic]]];
   coords =
    Union[coords,
     Rule @@@
      Transpose@{Cases[g, Tooltip[_, a_] -> a, Infinity],
        Cases[g, (VertexCoordinateRules -> a_) -> a,
          Infinity][[1]]}];]

A: A work-around is transforming vertices to strings:
  {op1, op2} = GroupGenerators@  MathieuGroupM11[];
  elems = {Range[11]};
  edges = {};
  coords = {};
   frames = {};

  frames = Reap[While[Length@elems < 10,
  (AppendTo[elems, Permute[#, op1]];
    AppendTo[elems, Permute[#, op2]];
    AppendTo[edges, # -> Permute[#, op1]];
    AppendTo[edges, # -> Permute[#, op2]]) & /@ elems;
  elems = Union[elems];
  edges =  Union[edges] /. (a_ -> b_) :> (ToString[a] -> ToString[b]);
  Sow[g = GraphPlot[edges,   VertexCoordinateRules ->
     If[Length@coords > 0, coords, Automatic]]];
  coords =   Union[coords, Rule @@@ Transpose@{Cases[g, Tooltip[_, a_] -> a, Infinity],
      Cases[g, (VertexCoordinateRules -> a_) -> a,
        Infinity][[1]]}];]][[2, 1]];
 ListAnimate[frames, Alignment -> Center]

A: GraphPlot (or VertexCoordinateRules) seems to misinterpret a vertex when it is a List.  Start with a different head, such as vertex, and it will be propagated by Permute.  You can format vertex to show like a List (in the Tooltip for instance).
Format[vertex[l___]] ^:= {l};
{op1, op2} = GroupGenerators@MathieuGroupM11[];
elems = {vertex @@ Range[11]};
edges = {};
coords = {};
frames = {};
frames = Reap@
  While[Length@elems < 10,
   AppendTo[elems, Permute[#, op1]];
     AppendTo[elems, Permute[#, op2]];
     AppendTo[edges, # -> Permute[#, op1]];
     AppendTo[edges, # -> Permute[#, op2]]; & /@ elems;
   elems = Union[elems]; edges = Union[edges];
   Sow[g =
     GraphPlot[edges,
      VertexCoordinateRules ->
       If[Length@coords > 0, coords, Automatic]]];
   coords =
    Union[coords,
     Rule @@@
      Transpose@{Cases[g, Tooltip[_, a_] -> a, Infinity],
        Cases[g, (VertexCoordinateRules -> a_) -> a,
          Infinity][[1]]}];]

A: JUst another way to implement same conceot as kguler (using Map at level 2:
elems = {Range[11]};
edges = {};
coords = {};
frames = {};
frames = Reap@
  While[Length@elems < 10,
   AppendTo[elems, Permute[#, op1]]; AppendTo[elems, Permute[#, op2]];
     AppendTo[edges, # -> Permute[#, op1]];
     AppendTo[edges, # -> Permute[#, op2]]; & /@ elems;
   elems = Union[elems]; edges = Map[ToString, Union[edges], {2}];
   Sow[g =
     GraphPlot[edges,
      VertexCoordinateRules ->
       If[Length@coords > 0, coords, Automatic]]];
   coords =
    Union[coords,
     Rule @@@
      Transpose@{Cases[g, Tooltip[_, a_] -> a, Infinity],
        Cases[g, (VertexCoordinateRules -> a_) -> a,
          Infinity][[1]]}];]

yields:

(presuming Reap or reason for Sow) is intended.


text:
Q: Is it possible to use global variable in backbone.js view? Is it possible to use global variable in backbone.js view ?
exmpl:
var TodoView = Backbone.View.extend({

 counter: null ; // is this possible ?

 initialize: function(){

 this.render();

 },

 render: function(){

}

});

A: In addition to what Peter already said, if you are interested in having what amounts to a private variable that is available across all instances of the TodoView you create then you could do something like the following.
(function () {
  var counter = 0; //This can be used now as a private variable inside TodoView

  window.TodoView = Backbone.View.extend({

    initialize: function(){
      this.render();
      counter += 1;
    },

    render: function(){
    }
  });
})();

A: You can easily store variables in at least 3 different scopes:

*

*Regular instance variables unique to each view instance

*

*these can be stored as properties on the view's this object

*Example: this.selectedItem = this.$el.find('.selected');

*Class-level variables shared by all instances of the view

*

*these can be stored on the View class's constructor function

*Example: TodoView.counter = 0; (put that after your entire .extend invocation)

*True global variables (yes, these are bad, but since you asked)

*

*you can leak these by omitting var or just explicitly assign to the window object

*Example: window.appLaunchTime = new Date()

A: try putting it in static scope
var TodoView = Backbone.View.extend({
TodoView.counter++//reference it this way
},{
 counter: null ;})

may serve somewhat like a global variable


text:
Q: Gamemaker using variables from maps I have an object with its own inventory, for which I use a list of maps.
Each item has a name and x and y offsets.
I want to draw each item with its offset on top of my other object, and have them turn along with the original object, so inside the draw function I have this:
draw_sprite_ext(spr_cart2, 0, x, y,1,1,direction, c_white, 1)
for(i = 0; i < ds_list_size(products); i++){
    product = products[| i]
    rad_dir = degtorad(direction)
    x_rot = cos(rad_dir)*(product[? "x"]-x) - sin(rad_dir)*(product[? "y"]-y)
    y_rot = cos(rad_dir)*(product[? "y"]-y) - sin(rad_dir)*(product[? "x"]-x)
    draw_sprite_ext(asset_get_index("spr_"+product[? "product"]), 0, x_rot, y_rot, 1, 1, direction, c_white, 1)
}

However, it doesn't work at all.
I tried logging product[? "x"]-x, and it gave a very large negative number, whereas logging just product[? "x"] did give the expected result.

A: What worked in the end was not directly subtracting from the map
There were also some errors in the rotational logic.
Working code:
draw_sprite_ext(spr_cart2, 0, x, y,1,1,direction, c_white, 1)
for(i = 0; i < ds_list_size(products); i++){
    product = products[| i]
    x_rot = (cos(rad_dir)*(product[? "x"])) - (sin(rad_dir)*(product[? "y"]))
    y_rot = (cos(rad_dir)*(product[? "y"])) + (sin(rad_dir)*(product[? "x"]))
    draw_sprite_ext(asset_get_index("spr_"+product[? "product"]), 0, x-x_rot, y+y_rot, 0.5, 0.5, direction, c_white, 1)
}


text:
Q: creating a shell script to automate csv export in mongo db We have mongo db and in that we have a list of collections which i wanna export to csv using the mongoexport tool. I need to do this often and the names of the collections changes sometimes. So what i wanna do is create a shell script that i can just run and it will iterate over the collections in the mongo db and create csv files. Right now i have a script but its not automated for example i have the following in a script.
 mongoexport -d mydbname -c mycollname.asdno3rnknlasfkn.collection --csv -f field1,field2,field3,field4 -o mycollname.asdno3rnknlasfkn.collection.csv

In this all the elements will remain same except csv filename and the collection name where both are same.
So i wanna create a script which will
 show collections

then loop over the collection names retrieved and replace it in the export tool command.

A: This can easily be done via the shell - don't know if the comments above refer to old versions of the mongo shell...
Example:
echo 'show collections' | mongo dbname --quiet

A: You can not call "show collections" through mongo from the shell.
I suggest you write a small skript/program using your favorite language
fetching the collection names through the driver's API and then execute
mongoexport through your script/program using a system call (system()).

A: #############################################################
Script 1 -- to produce a list of databases in MongoDB server
#############################################################

#!/bin/bash
####################################################################
# PROGRAM:      mongolistdbs.sh
#
# PROGRAMMER:   REDACTED
# PURPOSE:      Program created to list databases in Mongo
#
# CREATED:      02/14/2011
#
# MODIFCATIONS:
###################################################################
#set -x
#supply mongo connection parms: server and port
mongo localhost:12345 --quiet <<!!  2>&1
show dbs
!!

########################################################
Script 2 -- This is the driver that calls script 1
#########################################################
####################################################################
# PROGRAM:      mongodb_backup_driver.sh
#
# PROGRAMMER:   REDACTED
# PURPOSE:      Program created to drive the MongoDB full database
#               backups
# CREATED:      02/14/2011
#
# MODIFCATIONS:
###################################################################

#!/bin/bash

        ################################################
        # backup strategy is individual backup
        # of all databases via loop and db list
        # (dbparm is empty string)
        ###############################################
        echo "Strategy: All via Individual Loop"

        ####################################
        ### here is the call of script 1
        ####################################
        DBs=`./mongolistdbs.sh | cut -f1 | egrep -v ">"`
        for db in $DBs;
        do
                echo  "Driver loop for backup of [ ${db} ]"
                #############################################################
                ### here im calling my backup script (not supplied)
                ### with database as a parameter within a loop
                ### to backup all databases individually
                #############################################################
                ./royall_mongodb_backup.sh ${db}
        done


text:
Q: Changing OpenVPN device name I have multiple VPN server software running on the same server, two of them (tinc and openvpn) are using the same /dev/net/tun devices and spawning a tunX iface.
The later started ones will use tun devices from zero, so they're reusing each other's device and causing a lot of problems and disruption of services.
My question is, is it possible to let OpenVPN to spawn its own tun with other names like tun-X or otun-Y etc?

A: Yes, you can use the dev option to specify which device you want to use. You'll also have to add dev-type to specify tun or tap:
dev ovpn-tcp
dev-type tun

Will use a tun device named ovpn-tcp, giving you:
$ ip link ls ovpn-tcp
7: ovpn-tcp: <POINTOPOINT,MULTICAST,NOARP,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UNKNOWN mode DEFAULT qlen 100
    link/none

This is quite useful—far easier to hang, e.g., iptables rules off of known device names.


text:
Q: Center part title in TOC i would like to center the part title in the table of contents (TOC) of my thesis. Based on an answer of egreg, i was able to at least modify the space between part number and part title in the TOC.
However, I cannot set this length individually for each \part (i try it in the MWE below, but as can be seen in the result, it does not work).
\documentclass[dottedtoc]{scrreprt}
\usepackage[parts]{classicthesis}
%custom space between number and text in toc: https://tex.stackexchange.com/a/140053/38853
\makeatletter
\def\ttl@tocpart{% %magic code, don't ask
  \def\ttl@a{\protect\numberline{\thepart}\@gobble{}}}
\setlength{\cftpartnumwidth}{100px}
\makeatother

\begin{document}
\tableofcontents
\part{P1}
\chapter{Ch1}
\setlength{\cftpartnumwidth}{150px}
\part{P2}
\chapter{Ch2}
\end{document}

Result:

Other solutions are welcome as well!
(I am aware of https://tex.stackexchange.com/a/210676/38853, however, I don't see how to put the part number on the left and the page number on the right, as in the picture)

A: Based on Johannes_B's comments my hacky solution can be completed:
\documentclass[dottedtoc]{scrreprt}
\usepackage[parts]{classicthesis}
%custom space between number and text in toc: http://tex.stackexchange.com/a/140053/38853
\makeatletter
\def\ttl@tocpart{% %magic code, don't ask
  \def\ttl@a{\protect\numberline{\thepart}\@gobble{}}}
\setlength{\cftpartnumwidth}{100px}
\makeatother

\begin{document}
\tableofcontents
\part{P1}
\chapter{Ch1}
\addtocontents{toc}{\protect\setlength{\cftpartnumwidth}{150px}}
\part{P2}
\chapter{Ch2}
\end{document}

yields

Still, more comfortable solutions for centering the title are welcome. :)


text:
Q: Since upgrade to php 5.3 php -i output is in html format Just a minor niggle, but is there a way to get the old plain text formatted output from
php -i

Since v5.3 it seems to output everything in html format which is a mess from the command line.

A: Then you should disable xdebug and set the html_errors parameter in your php.ini to 0. I think this should work.
html_errors=0

Disable HTML stack traces by Xdebug


text:
Q: Firefox quantum, disable search in address field I've been looking everywhere but cannot find a way to disable the search from the Address field in the Firefox Quantom.
No problem adding a search bar, but that doesn't negate the search from the address bar.
I'm currently on 57.0.3.

A: You should be able to disable search in the address bar (aka awesomebar) by:

*

*going to about:config;

*searching for the browser.urlbar.suggest.searches preference;

*setting it to false.

You may notice that there are other browser.urlbar.suggest.* preferences there. You can tweak them to personalize your urlbar suggestion experience.
Update: to disable searching when typing an address (e.g. the URI fails to resolve and it tries to use a search engine) also disable keyword.enabled in the preferences. To prevent the bar from guessing/fixing the typed URI (e.g. typing fred is changed to fred.com) there's another pref, browser.fixup.alternate.enabled. It needs to be set to false to disable URI fixup.


text:
Q: Regular expression split unexpected empty string item I have strings like this example
"BODY: 88% RECYCLED POLYESTER, 12% ELASTANE GUSSET LINING: 91% COTTON, 9% ELASTANE EXCLUSIVE OF DECORATION"

And I want to split them so that a word with a colon starts a new list item, while keeping that colon word
["BODY: 77% RECYCLED POLYESTER, 23% ELASTANE", "MESH: 84% POLYAMIDE, 16% ELASTANE EXCLUSIVE OF DECORATION"]

I came up with
re.split("\s(\w+:.+)", p)

But this returns an empty string at the end and I'm not sure why
['BODY: 77% RECYCLED POLYESTER, 23% ELASTANE', 'MESH: 84% POLYAMIDE, 16% ELASTANE EXCLUSIVE OF DECORATION', '']

A: You can use re.split(r"\s(?=\w+:)", s). I added a lookahead ?= to ensure the split occurs only on the space character that has the \w+: pattern following it.
The original attempt includes the entire pattern in the split group leading to undesirable results (if you include multiple word: groups, you'll see there are bigger problems than just the trailing empty string).
Here's a comparison:
>>> s = "foo: bar bar baz: asdfa sdfasd quux: zzzz"
>>> #                ^                 ^
>>> # we want to split on the highlighted space characters above
>>>
>>> re.split(r"\s(\w+:.+)", s) # incorrect
['foo: bar bar', 'baz: asdfa sdfasd quux: zzzz', '']
>>> re.split(r"\s(?=\w+:)", s) # correct
['foo: bar bar', 'baz: asdfa sdfasd', 'quux: zzzz']

If you want to handle splitting on multiple spaces, you can use r"\s+(?=\w+:)".
Note also raw strings should be used for all regex literals to ensure nothing is inadvertently escaped.


text:
Q: Having trouble with Ubuntu LAMP stack I have installed Ubuntu 16.04 LTS, Apache2, Mysql 14, Php7. I have installed Drupal with a few difficulties. Specifically, I had to install php extensions and tweak the configs to enable those extensions, and finally the installation was successful. However, whenever I try to click on any link, the 404 Not found error page pops up. So technically I can't go anywhere beyond the CMS homepage. I installed another CMS, the same problem, can see the homepage, nothing beyond. Did anyone ever had this kind of issue?
I tried the following three:
changed the CMS folder ownership to www-data:www-data (my CMS folder is drupaltest)
sudo chown -R /var/www/html/drupaltest

in /etc/apache2/apache.conf file, added
<Directory /var/www/html/drupaltest/>
  AllowOverride All
</Directory>

And also:
sudo a2enmod rewrite

A: I feel like you're missing .htaccess file. Usually its a hidden file, so make sure to show all files (including hidden files) and copy it and paste it into your local drupal folder.
Also,make sure you local server has mod_rewrite enabled to support clean URLs, if its not enabled then check this answer: How to enable mod_rewrite in Apache?.
Another suggestion is to turn off Clean URL from settings.php by adding the following code:
$conf['clean_url'] = 0;
if all these above step not working then please explain little more about your problem .


text:
Q: ReverseEngineeringGenerator in Entity Framework Core 2.1 Based on this article by Mr Rowan Miller I want to use EF Core scaffolding system by code.
// Add base services for scaffolding
var serviceCollection = new ServiceCollection()
    .AddScaffolding()
    .AddLogging();

// Add database provider services
var provider = new SqlServerDesignTimeServices();
provider.ConfigureDesignTimeServices(serviceCollection);

var serviceProvider = serviceCollection.BuildServiceProvider();

var generator = serviceProvider.GetService<ReverseEngineeringGenerator>();
var options = new ReverseEngineeringConfiguration
{
    ConnectionString = @"Server=(localdb)\mssqllocaldb;Database=Northwind;Integrated Security=true",
    ProjectPath = @"C:\temp\",
    ProjectRootNamespace = "My.Namespace"
};

generator.GenerateAsync(options).Wait();

But it does not work with latest EF Core 2.1.
Can anyone help me to update the code? (an updated article)

A: Code for 2.1 is available here: https://github.com/ErikEJ/SqlCeToolbox/blob/master/src/GUI/ReverseEngineer20/EFCoreReverseEngineer.cs
var scaffolder = serviceProvider.GetService<IReverseEngineerScaffolder>();
var scaffoldedModel = scaffolder.ScaffoldModel(...
var filePaths = scaffolder.Save(scaffoldedModel,...


text:
Q: what is the use of "remote(client) port" for inbound firewall rule? In firewall settings, local port for inbound rule is pretty obvious: that is the port you want to listen.
However, remote port sounds nonsense: In typical protocol, client uses arbitrary port so restricting remote port will break your service.

image is borrowed from What are differnet between local port and remote port of firewall in Windows 2016 server?
Although the image is windows firewall settings, I guess other firewalls have similar.
Is there any case to restrict client port(remote port) for inbound traffic?

A: There are many software and protocols where clients may request servers from fixed ports.

*

*What comes in my mind is the DNS, where client request (from port 53) a remote server (port 53). So a in-depth defense rule at your server side would be to only allow remote clients from their remote port 53.

*I think that ldap protocol does the same: client is requesting from a fixed and well defined port.

*You may also think of various synchronisations services (like SMB, NFS maybe, and various others..).

*You may also define remote ports range firewalling, in example, to ensure that a client is talking from a remote unprivileged port