Q: Ideas to upgrade Excel Income and Expense tracker Sorry for the overly lengthy explanation below but I thought it'll be helpful in getting your ideas:
A few years ago I helped a friend keep track of the income and expenses of his family run guest house (around 10 rooms). The way it works is that his guest house is managed by staff who provide my fiend with regular updates on income and expenses (eg. rooms occupied, income, types and amounts of expenses, referral sources etc).
I built a quick and simple system in Excel with a user form, which the guest house manager uses to log the information. This info gets saved in the same workbook on another sheet. Since my friend lives in another city, the manager then emails the workbook to him on a monthly basis. My friend has a master copy of the same workbook and every time he receives his monthly update, he copies and pastes (appends) the data into his master copy.
The master workbook also has some dashboards built into it which work off the back of some pivots, formulas or the data directly; and provide my friend with key information like monthly profit figures, expense types, most commonly occupied rooms, avg length of stay etc.
All worked well but now, since the dataset has increased hugely, the workbook has started crashing. He has asked me to fix it, but I think it's time to change the underlying technology which would better suit the purpose. He doesn't want to approach a professional developer as the profits don't justify the costs. I can develop something but I'm not sure which is the best way to do it:
I'm good with SQL and Excel. My VBA knowledge is intermediate and I've just started learning Python. My initial thoughts are:
I could host a webpage on my friend's machine which his manager can remotely access to fill in information which then gets stored in the SQL server - Again, I've only got very limited knowledge around web page development and hosting. There could be an Excel file (or Tableau once I've learnt it) linked to it
and serve as a dashboarding platform. Essentially, instead of storing data in Excel it'll be stored in a SQL database.
If any of you could suggest a better/simpler way of implementing this that'll be greatly appreciated.
Many Thanks


Q: Como mandar un email con php con varios archivos adjuntos? Hola tengo un sistema que envia mails con archivos adjuntos pero solo funciona con un archivo es decir solo manda un archivo
este es mi codigo html
<form id="" class="form" name="sentMessage" action='php/enviar_cv.php' method='post' target='_self' enctype="multipart/form-data" >

                                <input type="text" autocomplete="off" class="form-control" name="nombre" placeholder="Nombre *" id="name" required data-validation-required-message="Please enter your name.">

                                <input type="email" autocomplete="off" class="form-control" name="email" placeholder="Correo Electróncio *" id="email" required data-validation-required-message="Please enter your email address.">

                                <input type="text" autocomplete="off" class="form-control" name="telefono" placeholder="Teléfono (s) *" id="phone" required data-validation-required-message="Please enter your phone no.">

                                <input type="text" autocomplete="off" name="asunto" class="form-control" placeholder="Asunto" id="asunto" >

                        <textarea class="form-control" rows="7" placeholder="Mensaje" name="comentarios" id="message" required data-validation-required-message="Please enter a message."></textarea>

Si deseas asesoria inmediata adjunta tus archivos:
                            <input type='file' name='archivo1' id='archivo1' multiple="multiple"/>

                    <button type="submit" class="btn btn-primary tf-btn color">Enviar</button>

                </form>

y este es mi codigo php:
function form_mail($sPara, $sAsunto, $html, $sDe){
$bHayFicheros = 0;
$sCabeceraTexto = "";
$sAdjuntos = "";
if ($sDe)
    $sCabeceras = "From:".$sDe."\n";
else
    $sCabeceras = "";
$semi_rand = md5(time());
$mime_boundary = "==Multipart_Boundary_x{$semi_rand}x";
$sCabeceras .= "MIME-version: 1.0\n";
$sCabeceras .= "Content-type: multipart/mixed;";
$sCabeceras .= "boundary=\"{$mime_boundary}\"\n";
$sCabeceras .= "Content-transfer-encoding: 7BIT\n";

$body_top = "--{$mime_boundary}\n";
$body_top .= "Content-type: text/html\n";
$body_top .= "Content-transfer-encoding: 7BIT\n";
$body_top .= "Content-description: Mail message body\n\n";
$sTexto = $body_top.$html;

//if ($bHayFicheros)
foreach ($_FILES as $vAdjunto){
    if ($vAdjunto["size"] > 0){
        $sAdjuntos .= "\n\n--{$mime_boundary}\n";
        $sAdjuntos .= "Content-type: ".$vAdjunto["type"].";name=\"".$vAdjunto["name"]."\"\n";;
        $sAdjuntos .= "Content-Transfer-Encoding: BASE64\n";
        $sAdjuntos .= "Content-disposition: attachment;filename=\"".$vAdjunto["name"]."\"\n\n";
        $oFichero = fopen($vAdjunto["tmp_name"], 'r');
        $sContenido = fread($oFichero, filesize($vAdjunto["tmp_name"]));
        $sAdjuntos .= chunk_split(base64_encode($sContenido));
        fclose($oFichero);
    }
}

$sTexto .= $sAdjuntos."\n\n";

return mail($sPara,$sAsunto,$sTexto,$sCabeceras);
 }

if (form_mail("sistemas@mktydesarrolloweb.com", $asunto, $body, "contacto@mcvabogados.com.mx"));}

A: Yo uso la libreria de PHP mailer y uso esta función:
function enviar_correo($destinatarios, $mail_asunto, $mail_contendio, $from, $from_name, $archivos_adjuntos_ruta,$archivos_adjuntos_temp){
$mail= new PHPMailer(); // defaults to using php "mail()"
$mail->CharSet = 'UTF-8';
$body= $mail_contendio;
$mail->IsSMTP(); // telling the protocol to use SMTP
$mail->Host = "tu.host.com"; // SMTP server
$mail->From = $from;
$mail->FromName = $from_name;
$mail->Subject = $mail_asunto;
$mail->MsgHTML($body);
$destinatarios=explode(",", $destinatarios);
if(!empty($destinatarios)){
foreach($destinatarios as $un_destinatario){
$mail->AddAddress($un_destinatario); //destinatarios
}
}else{
return false;
}
if(!empty($archivos_adjuntos_ruta)){
foreach($archivos_adjuntos_ruta as $archivo){
$mail->AddAttachment($archivo); // attachment
}
}
if(!empty($archivos_adjuntos_temp)){
foreach($archivos_adjuntos_temp as $nombrearchivo=>$contenidoArchivo){
$mail->AddStringAttachment($contenidoArchivo,$nombrearch ivo,'base64');
}
}
$mail->Timeout = 20;
if($mail->Send()) {
return array(true);
}else {
return array(false,"Mailer Error: ".$mail->ErrorInfo);
}
}
$archivos_adjuntos_ruta=array($path1,path2);
$archivos_adjuntos_temp=array(utf8_decode($strfile PDF)=>$strContenidoPdf,utf8_decode($strNomArch)=>$ strContenidoXml);
enviar_correo(...,array(),archivos_adjuntos_temp);//los archivos estan en variables temporales
enviar_correo(...,$archivos_adjuntos_ruta,array()) ;//los archivos estan en rutas en disco
enviar_correo(...,$archivos_adjuntos_ruta,archivos _adjuntos_temp);//ambas opciones al mismo tiempo

Lo de llamarla con varios archivos esta al final del código.


Q: novato en c# y en general ¿Que tal? me acabo de registrar en este estupendo foro, y queria saludar y pedir ideas sobre la creacion de un programa de gestion de casas rurales en c#.
Cree la base de datos en MySql(nada del otro mundo), me preguntaba si al realizar una aplicacion con windows forms y realizar un menuStrip, ¿Es mejor que cada item sea un form o como estaria bien implementado?
Estoy abierto a ideas o ejemplos un saludo y gracias de antemano.

A: Depende del diseño de la aplicacion, pero lo comun es que un item de menu abra una nueva ventana.
Esto podrias implementarlo en un diseño MDI, en donde las ventanas abren dentro de un form definido como container.
Introduction to MDI Forms with C#
Entonces los items de menu abres ventanas contenidas en este form.
Sino quieres usar MDI podrias usar un form de base con un Panel y abrir user control dentro.
En este caso el item del menu creara una instancia del user control que agrega como control dentro del Panel
public void menustripAltaProducto_Click(..){

     ucAltaProducto uc = new ucAltaProducto();
     Panel1.Controls.Add(uc);
}

De esta forma no abres ventanas modales sino que usas User Control como form
Uan variante a esto seria usar TabControl, en donde en cada tab abres un user control con la funcionalidad de la pantalla
How to: Add and Remove Tabs with the Windows Forms TabControl
public void menustrip1_Click(..){

     TabPage tab = new TabPage("Alta Producto");

     ucAltaProducto uc = new ucAltaProducto();
     tab.Controls.Add(uc);

     tabControl1.TabPages.Add(tab);
}


Q: python time vs datetime The following comparison does not work, is there any way to get number of seconds passed (w.r.t localtime) since epoch from time module?
(datetime.datetime.now() - datetime.datetime.utcfromtimestamp(0)).total_seconds() - time.mktime(time.localtime()) => 3600.9646549224854

OR
(datetime.datetime.now() - datetime.datetime.utcfromtimestamp(0)).total_seconds() - time.time() => 3599.9999861717224

Thanks

A: datetime.now() returns a local datetime, while datetime.utcfromtimestamp() returns a UTC datetime. So of course you will have the difference of your timezone accounted for in your calculation. In order to avoid that, either always use local time, or always use universal time.
>>> (datetime.datetime.utcnow() - datetime.datetime.utcfromtimestamp(0)).total_seconds() - time.time()
0.0

A: Epoch is in GMT, so the number of seconds that have passed since Epoch is the same no matter what timezone you are in. Hence, the correct answer to your question:

is there any way to get number of seconds passed (w.r.t localtime) since epoch from time module?

is
>>> import time
>>> time.time()
1442482454.94842


Q: How to read a LinkedHashMap written in file? I want to read a particular value from LinkedHashMap written in a .txt file, but is showing "java.io.StreamCorruptedException: invalid stream header: 7B495020"
For writing in LinkedHashMap i tried the method;
public void WriteBasicInfo(String name, String pass) throws IOException, ParseException {
    Map<String, String> m;
        try {
            m = new LinkedHashMap<String, String>();
            m.put("Name", name);
            m.put("Password", pass);

            BufferedWriter bw = new BufferedWriter(new FileWriter(FILE_NAME, false));
            bw.write(m.toString());
            bw.flush();
            bw.close();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

And it successfully writes in file. But when Iam trying to read the above hashmap using this method
public void readBasicInfo() throws IOException, ParseException, InvocationTargetException, ClassNotFoundException
{
        ObjectInputStream is = new ObjectInputStream(new FileInputStream(FILE_NAME));
        Map<String, String> myMap=(LinkedHashMap<String, String>) is.readObject();

        for(Map.Entry<String,String> m :myMap.entrySet()){
                 System.out.println(m.getKey()+" : "+m.getValue());
        //  String val1=m.get("Name");
        }
     ois.close();
    }

it is showing "java.io.StreamCorruptedException: invalid stream header: 7B495020" , and no data is read
I tried to read all the entries written in hashmap, to check whether it is reading or not; but actually I just want read only "name" entry stored in hashmap.

A: You are simply: writing as string, but reading back expecting a binary serialized object!
You know, that is like: you put an egg in a box, and then you expect you can open that box and pour milk from it into a glass! That wont work.
Here:
bw.write(m.toString());

You write the map into that file as raw string. This means that your file now contains human readable strings!
But then you do:
Map<String, String> myMap=(LinkedHashMap<String, String>) is.readObject();

Which expects that the file contains serialized objects.
Long story short, these are your options:

*

*keep writing these strings, but then you need to implement your own parser that reads such text files, and turns them back into objects within maps

*instead of writing raw text strings, use a library such as gson or jackson and serialize your map as JSON string (which requires that all keys/values can be serialized as JSON)

*instead of writing raw text or JSON, use the default Java serialization mechanism and serialize to binary content which requires that all keys/values implement the Serializable interface. See here for a nice tutorial how to do that in detail.

My recommendation: go for option 2, or 3. 2 adds a dependency to a 3rd party library, but I think it is the more "common" practice these days.

A: You need to serialize/deserialize the object, not just reading/writing its toString representation to file.
See: https://javahungry.blogspot.com/2017/11/how-to-serialize-hashmap-in-java-with-example.html


Q: Permission error [winerror 5] access is denied-Selenium chrome webdriver I'm following a tutorial on using selenium and I'm having trouble getting started. Namely, when I try to run the code below, I get the error below. I have seen other users with the same problem, I have tried their solutions, they did not work.
These solutions include:

*

*running pycharm as administrator,

*setting permissions for all

*group/usernames of subprocess.py and service.py

*site-package(and pretty much every file/folder within) to full
access.

from selenium import webdriver
driver = webdriver.Chrome(r"C:\Users\User\AppData\Local\Programs\Python\Python37-32\Lib\site-packages\selenium\webdriver\chrome")
driver.get("http://python.org")

Here is the full error message:

Traceback (most recent call last):   File
"C:\Users\User\AppData\Local\Programs\Python\Python37-32\lib\site-packages\selenium\webdriver\common\service.py",
line 76, in start
stdin=PIPE)   File "C:\Users\User\AppData\Local\Programs\Python\Python37-32\lib\subprocess.py",
line 775, in init
restore_signals, start_new_session)   File "C:\Users\User\AppData\Local\Programs\Python\Python37-32\lib\subprocess.py",
line 1178, in _execute_child
startupinfo) PermissionError: [WinError 5] Access is denied

During handling of the above exception, another exception occurred:

Traceback (most recent call last):   File
"C:/Users/User/PycharmProjects/PythonProject/DataCollection", line 2,
in
driver = webdriver.Chrome(r"C:\Users\User\AppData\Local\Programs\Python\Python37-32\Lib\site-packages\selenium\webdriver\chrome")
File
"C:\Users\User\AppData\Local\Programs\Python\Python37-32\lib\site-packages\selenium\webdriver\chrome\webdriver.py",
line 73, in init
self.service.start()   File "C:\Users\User\AppData\Local\Programs\Python\Python37-32\lib\site-packages\selenium\webdriver\common\service.py",
line 88, in start
os.path.basename(self.path), self.start_error_message) selenium.common.exceptions.WebDriverException: Message: 'chrome'
executable may have wrong permissions. Please see
https://sites.google.com/a/chromium.org/chromedriver/home

A: first, replace all \ with /
and then add the executable filename in the file location:
driver = webdriver.Chrome(r'C:/Users/User/AppData/Local/Programs/Python/Python37-32/Lib/site-packages/selenium/webdriver/chrome/chromedriver.exe')


Q: Is the channel capacity (defined as the maximum of mutual information) always less than 1? The channel capacity is defined to be the maximum achievable rate and is equal to maximum over input distributions of the mutual information between output and input. i.e.
$C=\max_{P} I(X;Y)$
Also the information rate  is defined as
$R=\frac{\log( M)}{n}$
where $M$ is the number of messages and $n$ is the blocklength.
Here is my question: If we have $M$ messages and $n$ as the blocklength, we would need $\log_2(M)$ bits to represents the $M$ messages. To avoid channel error however, we may add redundancy and transmit the messages in $n$ bits for $n>\log_2 (M)$ which results in $R\leq 1$. Consequently $C\leq 1$.
Is there any other ways of coding (not necessarily adding redundancy) such that the capacity is larger than $1$?
I mean, with this definition of rate, I always think of it to be less than 1 but from the mutual information point of view, I don't see a reason that it should be less than 1. Can please someone clarify?

A: For a channel with input alphabet $\cal X$ and output alphabet $\cal Y$, the channel capacity is upper bounded by $\log \min (|\cal X|, |\cal Y|)$.
For example, take a channel with same input and output alphabet which just outputs the input exactly. Then, its capacity is $\log |\cal X|$ which is achieved by an uniform distribution on the inputs (in fact, for any (weakly) symmetric channel, the uniform distribution achieves capacity, but thats another mattter). This can be larger than 1 bit.
A rate R is achievable if there exists a $(\lceil 2^{nR} \rceil,n)$ codes whose maximal error probability goes to zero. A $(M,n)$ code for a channel (i.e. a specification of $p(y|x)$) is a mapping from $\{1,\ldots,M\}$ to $\cal X^n$ (which forms the encoder) and a deterministic mapping from $\cal Y^n \to \{1,\ldots,M\}$ which forms the decoder. The capacity is the supremum of achievable rates. So, in the example I gave above, rates below $\log |X|$ are achievable (e.g. by repeating $n/2$ symbols twice, you get a rate of $\log |\cal X| /2$), but this is not the largest rate possible -- just sending the $n$ symbols as is gives you the full rate of $\log |\cal X|$.


Q: Separate two html buttons and remove the fist button green animation There are two HTML buttons in the code below.

*

*Currently they are stuck together. I need to introduce a gap between them

*When you hover the mouse over the first (top) button, there is a green colour animation would show up around the button. I need to remove that.

Please advise me on how to make the proposed changes.

Escolha o seu tamanho!

            <button class="yp">36</button>
            <button class="no">No</button>
            <button class="tsete">37</button>
            <button class="toito">38</button>
            <button class="tnove">39</button>
            <button class="qzero">40</button>
            <button class="qum">41</button>
            <button class="qdois">42</button>
            <button class="qtres">43</button>

Azul

    <form action="b_657272">
  <button class="button">COMPRAR AGORA</button>


Q: Text mining with PHP I'm doing a project for a college class I'm taking.
I'm using PHP to build a simple web app that classify tweets as "positive" (or happy) and "negative" (or sad) based on a set of dictionaries. The algorithm I'm thinking of right now is Naive Bayes classifier or decision tree.
However, I can't find any PHP library that helps me do some serious language processing. Python has NLTK (http://www.nltk.org). Is there anything like that for PHP?
I'm planning to use WEKA as the back end of the web app (by calling Weka in command line from within PHP), but it doesn't seem that efficient.
Do you have any idea what I should use for this project? Or should I just switch to Python?
Thanks

A: If you're going to be using a Naive Bayes classifier, you don't really need a whole ton of NL processing. All you'll need is an algorithm to stem the words in the tweets and if you want, remove stop words.
Stemming algorithms abound and aren't difficult to code. Removing stop words is just a matter of searching a hash map or something similar. I don't see a justification to switch your development platform to accomodate the NLTK, although it is a very nice tool.

A: I did a very similar project a while ago - only classifying RSS news items instead of twitter - also using PHP for the front-end and WEKA for the back-end. I used PHP/Java Bridge which was relatively simple to use - a couple of lines added to your Java (WEKA) code and it allows your PHP to call its methods. Here's an example of the PHP-side code from their website:
<?php
require_once("http://localhost:8087/JavaBridge/java/Java.inc");

$world = new java("HelloWorld");
echo $world->hello(array("from PHP"));
?>

Then (as someone has already mentioned), you just need to filter out the stop words. Keeping a txt file for this is pretty handy for adding new words (they tend to pile up when you start filtering out irrelevant words and account for typos).
The naive-bayes model has strong independent-feature assumptions, i.e. it doesn't account for words that are commonly paired (such as an idiom or phrase) - just taking each word as an independent occurrence. However, it can outperform some of the more complex methods (such as word-stemming, IIRC) and should be perfect for a college class without making it needlessly complex.

A: You can also use the uClassify API to do something similar to Naive Bayes.  You basically train a classifier as you would with any algorithm (except here you're doing it via the web interface or by sending xml documents to the API).  Then whenever you get a new tweet (or batch of tweets), you call the API to have it classify them.  It's fast and you don't have to worry about tuning it.  Of course, that means you lose the flexibility you get by controlling the classifier yourself, but that also means less work for you if that in itself is not the goal of the class project.

A: Try open calais - http://viewer.opencalais.com/ . It has api, PHP classes and many more. Also, LingPipe for this task - http://alias-i.com/lingpipe/index.html

A: you can check this library https://github.com/Dachande663/PHP-Classifier very straight forward

A: you can also use thrift or gearman to deal with nltk


Q: Second Spinner not receiving the proper info based on the first Spinner's selection I know there are about a million topics on this already, but hear me out.
The title says it all, when i select an item in spinner 1, spinner 2 gets a specific list of choices to pick from (which will then be used to show info). It's essentially a small contacts book.
*UPDATE**
All fixed and working, and an EXTRA special thank you to user FishTruck for helping out(i.e making it work!)
package com.your.package.name;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;

public class Contact extends Activity{

        public Spinner spinner1, spinner2;
        public Button btnSubmit;//not needed yet

        @Override
        public void onCreate(Bundle savedInstanceState){
                super.onCreate(savedInstanceState);

                setContentView(R.layout.contact);
                findViews();
                addItemsOnSpinner1();
                addItemsOnSpinner2(0);
        }

        private void findViews(){
                spinner1 = (Spinner) findViewById(R.id.spinner1);
                spinner2 = (Spinner) findViewById(R.id.spinner2);
        }

        private void addItemsOnSpinner1() {
                List<String> list = new ArrayList<String>();

                list.add("Please Select");
                list.add("Choice 1");
                list.add("choice 2");

                ArrayAdapter<String> name = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, list);

                name.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

                spinner1.setAdapter(name);
                spinner1.setOnItemSelectedListener(new OnItemSelectedListener(){
                        @Override
                        public void onItemSelected(AdapterView<?> arg0, View arg1,int arg2, long arg3) {
                                if(arg2>0)
                                addItemsOnSpinner2(arg2);
                        }
                        @Override
                        public void onNothingSelected(AdapterView<?> arg0) {
                                addItemsOnSpinner2(0);
                        }}
                );
        }

        private void addItemsOnSpinner2(int selectedIndex) {

                int positionTop = selectedIndex;

                if(positionTop==0){
                        List<String> list = new ArrayList<String>();
                        list.add("Please Select");
                        ArrayAdapter<String> name0 = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, list);
                        name0.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                        spinner2.setAdapter(name0);
                }else if(positionTop==1){
                        List<String> list1 = new ArrayList<String>();
                        list1.add("Please Select");
                        list1.add("item 1");
                        list1.add("item 2");
                        ArrayAdapter<String> name1 = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, list1);
                        name1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                        spinner2.setAdapter(name1);
                }else if(positionTop==2){
                        List<String> list2 = new ArrayList<String>();
                        list2.add("Please Select");
                        list2.add("item 3");
                        list2.add("item 4");
                        ArrayAdapter<String> name2 = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, list2);
                        name2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                        spinner2.setAdapter(name2);
                }
        }

}

Hope this helps!

A: You need to call the addItemsOnSpinner2() function when the first spinner item has got selected.
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,
    long arg3) {
addItemsOnSpinner2();}

A: you are setting both spinner at the beginning of the code ( in onCreate). You should populate the second spinner after the spinner1 data is changed

A: yes as the gentlemen before me said.
In order for the second spinner to get the correct index to set the list,
you need to populate it after the first spinner is clicked.
/* wrong answer deleted */
if this is my code i would change addItemsOnSpinner2() into:
private void addItemsOnSpinner2(int selectedIndex){
    int positionTop = selectedIndex;
    //rest is the same
    /* ... */
}

and again insert these into addItemsOnSpinner1():
spinner1.setOnItemSelectedListener(new OnItemSelectedListener(){
        @Override
        public void onItemSelected(AdapterView<?> arg0, View arg1,int arg2, long arg3) {
            if(arg2>0)
            addItemsOnSpinner2(arg2);
        }
        @Override
        public void onNothingSelected(AdapterView<?> arg0) {
            addItemsOnSpinner2(0);
        }}
    );

that is just how i would do it
i think many ways works here though
edit2:oh and edit the addItemsOnSpinner2() in onCreate() into addItemsOnSpinner2(0)
edit3:you need to call addItemsOnSpinner2() in onCreate(), otherwise your spinner is empty!
edit4:sorry guys, i made a huge mistake into thinking onItemClickListener could be applied here, shame on me :((
btw, if you want to keep the index (under situation like change of screen orientation or back to foreground ) , it needs more complicated work
but here is a much simpler method:
1.set a global static variable: int selectedIndex;
2.in onCreate, set selectedIndex to 0 if savedInstanceState is null
3.in onCreate, after savedInstanceState is nullcheckd, call addItemsOnSpinner2(selectedIndex)
4.in spinner1's listener, set selectedIndex to selected index.
not guarranteed to work on every machine though:(


Q: how to make the vim plugin "Project" and "Mini Buffer Explorer" work together? As the title says, I need to make these plugins work together well. The mini buffer explorer just automatically opens after I open the second file(press Enter in project plugin window), then Mini Buffer Explorer opens as the third window on the top of my screen.
But after I switch back to project plugin window and press Enter to open the third file, a fourth window opened! It seems project plugin can't overwrite the second file's window.
Project plugin 1.4.1
Mini Buffer Explorer plugin 6.4.0


Q: Make NUnit not stop at first failure I'm running a NUnit test over a list of numbers.
My code goes something like this:
numbers = GetListOfNumbers()
foreach number in numbers
      Assert.IsTrue(TestNumber(number))

My problem is that NUnit will stop the test on the first number it encounters that doesn't pass the test.
Is there anyway to make NUnit still fail the test if any numbers don't pass, but give me the list of all numbers that don't pass?

A: As a workaround, instead of using an Assert.IsTrue like that, you could try something like:
numbers = GetListOfNumbers()
List<number> fails = numbers.Where(currentNum=>!TestNumber(curentNum))
if (fails.Count > 0)
    Assert.Fail(/*Do whatever with list of fails*/)

A: NUnit 2.5 has data-driven testing; this will do exactly what you need.  It'll iterate over all of your data and generate individual test cases for each number.
Link

A: This can be done in MBUnit using a "RowTest" test method.  I'm not aware of a way of doing this in NUnit, however.


Q: How to stop NSTimer with another NSTimer? Note: I am using swift for this project.
I am currently working on my first project and I am trying to stop (invalidate) an NSTimer if a button was not pressed after a certain amount of time. I have found other ways of stopping my NSTimer but none saying how to stop it after a certain amount of time, with that time being reset if the button actually is pressed. Read everything to understand more clearly.
Here is my code now;
@IBOutlet var Text: UILabel!
var timer: NSTimer!
var countdown: Int = 0

@IBAction func StartGame(sender: AnyObject) {
self.countdown = 20
self.timer = NSTimer.scheduledTimerWithTimeInterval(1.5, target: self, selector: "updateCountdown", userInfo: nil, repeats: true)
}

func updateCountdown() {

    self.countdown--

    if self.countdown == 0 {
        self.timer.invalidate()
        self.timer = nil
    }

    let texts: NSArray = ["Test", "Testing"]
    let range: UInt32 = UInt32(texts.count)
    let randomNumber = Int(arc4random_uniform(range))
    let textstring = texts.objectAtIndex(randomNumber)

    self.ColorText.text = textstring as? String
}

@IBAction func PlayerbuttonPRESSED(sender: AnyObject) {
if Text.text == "Test" {
//Something happens
}
if Text.text == "Testing" {
//Something happens
}

What I am dying to know is how I make something else happen if the button was not pressed before ColorText.text was changed! (If the button was not pressed before changing the text after 1.5 seconds).
Ps. Sorry for the long code, I think it is necessary. :-)

A: There are different ways of doing this. One way, you could set bool value to true when the button is pressed then in updateCountdown check to the boolean.
For example:
func updateCountdown() {

     self.countdown--

    if self.countdown == 0 && YOUR_BUTTON_BOOL {
        self.timer.invalidate()
        self.timer = nil
    }

    let texts: NSArray = ["Test", "Testing"]
    let range: UInt32 = UInt32(texts.count)
    let randomNumber = Int(arc4random_uniform(range))
    let textstring = texts.objectAtIndex(randomNumber)

    self.ColorText.text = textstring as? String
}

However, using NSTimer in this fashion where you have it trigger in a short period of time like 1.5 seconds can become inaccurate. After the timer triggers 20 times the time past will be greater than 30 seconds. If accuracy is important you might be better off setting a second timer for 30 seconds. If the button is pressed it invalidates the 30 second timer if the 30 second timer fires it invalidates the 1.5 second timer.


Q: affine hull, how to understand the statements below? I am new to affine space, I looked through the wikipedia page, and have problem understanding the statements below.

*

*The affine hull of a set of three points not on one line is the plane
going through them.

*The affine hull of a set of four points not in a
plane in $R^3$ is the entire space $R^3$.

Can anyone try to help explain in more detail?

A: I'm not an expert on affine spaces either, but this is how I understand it.
Suppose you have two different points $p_1 = (x_1,\ y_1)$ and $p_2 = (x_2,\ y_2)$. Then you can make lineair combinations $\alpha p_1 + \beta p_2$ of those points. If you restrict the choices for $\alpha$ and $\beta$ to those values for which $\alpha+\beta=1$, then you're making affine combinations. Together they make the line that goes through $p_1$ and $p_2$. You can see this by writing $\beta=1-\alpha$, so that your combination is given by $\alpha p_1 + (1-\alpha)p_2 = p_2 + \alpha(p_1-p_2)$. Starting from $p_2$ you can choose any factor $\alpha$ that multiplies the difference between your two points. This is exactly the line that goes through those points.
The affine hull is the set of all affine combinations of the points in your set. So, if you have only two points this is the line that goes through these points, as explained above. If you have three points, you get two lines: the line through $p_1$ and $p_2$ and through $p_1$ and $p_3$. These two lines (assuming they are different) span a plane that goes through $p_1$, $p_2$ and $p_3$ (you can also use the line through $p_2$ and $p_3$, but it will lead to the same plane).
You can see that two lines span a plan by drawing two lines on a piece of paper. If you imagine your paper is infinitely large, the plane spanned by your lines is the paper on which you drew the lines.
Similarly, with four points you get three lines which (assuming they are different) span a space that goes `through' all four points. This is $\mathbb{R}^3$.


Q: React + GraphQL: dataArray.map is not a function I Just started learning graphQL and Apollo.
Below is the sample client side code using Apollo client.
I am providing data from nodemon express server.
console.log(data) shows the output from the server.
However i was trying to display the query result using the apollo client but i was unbale to do so. I am stuck in this , any help will be appreciated.

import React from "react"
import { Query } from "react-apollo";
import gql from "graphql-tag";

export const ExchangeRates = () => (
    <Query
        query={gql`
      {
        counterparty {
         name
       }
      }
    `}
    >
        {({ loading, error, data }) => {
            if (loading) return
Loading...
;
            if (error) return
Error :(
;

            console.log(data)   // Works fine as expected
            var a= data.map(x=>{
                return x.name
            })

            return
 Data {a}
 // stuck here ..how to display data
        }}

    </Query>
);

The following codes gives an error and says
TypeError: data.map is not a function

However the console.log(data) works fine and the following output:-

A: Your are doing wrong here... your array is inside data.counterparty...
try this
var a= data.counterparty.map(x=>{
                return x.name
            })


Q: Xubuntu 12.04: wrong time; change system language I have recently installed Xubuntu 12.04 on my rather old computer. Most of the things are fine but I have a couple of problems.
During the installation I was asked to choose a language and I chose English. However, now I want to change the language of the system (not merely the keyboard layout) such that all the setting appear in this other language. Can I do that now after the installation?
The other problem is that the time shown up in the right is wrong. It is one hour ahead. The date, however, is correct. My location is also displayed correctly. I have an internet connection and expected that the time should be synchronized but it is not. Any ideas how to fix that?

A: To set the language for menu's and windows, perform the following steps:

*

*Goto XFCE->Settings Manager-> Language Support

*It might ask to install a few things, allow this.

*Press install / remove languages.

*Check the language which you want to use

*Drag your language to the top of the list and press Apply System Wide.

*Done

To set the time correctly, perform the following steps:

*

*Goto XFCE->Settings Manager-> Time and Date

*Press unlock at the bottom of the window

*Under configuration choose "Keep Synchronized with Internet servers"

*Allow it to install NTP support if it is not already installed

*Done


Q: doPostback() not refreshing some elements on page correctly Having the following problem:
I have an HTML button which causes a __doPostBack(button.ClientID,'texthere').
Dim button As HtmlButton
button = CType(Me.btnButton, HtmlButton)
button.Attributes.Add("onclick", "__doPostBack('" & btnButton.ClientID & "', 'btnBBHistory');return false;")

In my page_load I have the following:
Dim control_postback = Request("__EVENTARGUMENT")
    If control_postback = "texthere"
            Page.ClientScript.RegisterStartupScript(Me.GetType(), "Script", "ShowWindow();",
    End If

The ShowWindow(); javascript function is displayed using showModalDialog.
  Dim s As New StringBuilder
        s.Append("<script type=""text/javaScript"">")
        s.Append("function ShowWindow() {" & ControlChars.CrLf)
        '  s.Append("var result = window.showModalDialog('" & url & "','','dialogWidth:1200px;dialogHeight:450px;resizable:yes');" & ControlChars.CrLf)
        s.Append("var result = window.showModalDialog('" & url & "','','dialogWidth:1100px;dialogHeight:500px;resizable:yes;help:no;');" & ControlChars.CrLf)
        s.Append("if (result) { " & ControlChars.CrLf)
        ' s.Append("document.getElementById('" & lblwhatever.ClientID & "').innerHTML=result.fullline;" & ControlChars.CrLf)
        s.Append("if (result.text.length || result.quantity.length) { " & ControlChars.CrLf)
        s.Append("document.getElementById('" & txtwhatever.ClientID & "').value=result.text.concat(result.quantity);" & ControlChars.CrLf)
        s.Append("document.getElementById('" & txtqty.ClientID & "').value=result.quantity;" & ControlChars.CrLf)

        s.Append("__doPostBack()" & ControlChars.CrLf)
        s.Append("}" & ControlChars.CrLf)
        s.Append("}" & ControlChars.CrLf)
        s.Append("return false;" & ControlChars.CrLf)
        s.Append("}" & ControlChars.CrLf)
        s.Append("</script>")
        If Not ClientScript.IsClientScriptBlockRegistered("ShowWindow") Then
            ClientScript.RegisterClientScriptBlock(Me.GetType(), "ShowWindow", s.ToString())
        End If

This all works fine and the dialog box with the generated URL is displayed. However, on the originating webpage (the one where the button is initially clicked to produce this dialog box), there is an image (.djvu format). Whenever my code is run, the originating page is refreshed because of the __doPostBack() but in certain version of IE (IE8 and 9 so far) the image does not reload. Is there a chance that the showModalDialog is preventing any further rendering of the page in the background on these versions of IE or that the doPostBack() is not actually doing a complete postback in some way and the image is breaking?
Thanks for any help you might be able to give

A: Fixed: I needed to use window.open instead of showmodaldialog as when using showmodaldialog, the parent/calling page was (i believe) pausing/halting/breaking execution of the parent page until the child page was closed


Q: VB.NET table.sort with multiple columns I have the following but need to add more columns to filter by. I am getting errors with the syntax I am trying.
Dim ldv1 As System.Data.DataView
ldv1 = tbl1.DefaultView
ldv1.Sort = (tbl1.Columns(0).ColumnName) & " Asc" <-- I want to add to this

I am trying to do something like this but failing:
ldv1.Sort = (tbl1.Columns(0).ColumnName) & " Asc",(tbl1.Columns(1).ColumnName) & " Asc"

OR
ldv1.Sort = (tbl1.Columns(0).ColumnName), (tbl1.Columns(1).ColumnName) & " Asc"

Neither seems to be the correct way. How do I sort by more columns?

A: Add a , inside the string after the first Asc.
ldv1.Sort = tbl1.Columns(0).ColumnName + " Asc, " + tbl1.Columns(1).ColumnName + " Asc"


Q: Temporary captured-variables in lambda functions - C++11 I was trying out something like this to pre-populate a map using a vector-list of strings.
The code is self-explanatory:
Constructor(const vector<string>& names) {
  for_each(names.begin(), names.end(),
                     [this, counter = 1](const String& choice) mutable {
                            nameMapping.emplace(choice, counter++);
                        }
  );
}

Something I didnt really understand is how does counter work?
FYI: counter is no-where declared outside of the lambda function.
But yet, I am able to create a local-variable in class-scope and modify it in a mutable lambda fn?
Can someone please help me understand whats going on.

A: When you set counter = 1 you're declaring a new temporary counter equal to 1. The compiler does the work of determining the type. This temporary object is deduced to type int by default, and lives while the lambda is alive.
By setting mutable you can both modify counter and this
Aside: since it appears that you're inserting into a map/unordered map, you're probably better off with the following:
#include <algorithm> // For transform
#include <iterator>  // For inserter

Constructor(const vector<string>& names) {
    auto const example = [counter = 1](const string& item) mutable {
        return {item, counter++};
    };
    std::transform(names.begin(), names.end(),
                   std::inserter(nameMapping, nameMapping.end()), example);
}

By moving the nameMapping call outside of the lambda, you don't have to confuse yourself with what is in scope and what is not.
Also, you can avoid unnecessary captures, and anything else that might confuse yourself or other readers in the future.

A:
But yet, I am able to create a local-variable in class-scope and modify it in a mutable lambda fn?
Can someone please help me understand whats going on.

It's exactly as you said.
Possibly confusing because there's no type given in this particular kind of declaration. Personally I think that was an awful design decision, but there we go.
Imagine it says auto counter = 1 instead; the auto is done for you. The variable then becomes a "member" of the lambda object, giving it state.
The code's not great, because the lambda isn't guaranteed to be applied to the container elements in order. A simple for loop would arguably be much simpler, clearer and predictable:
Constructor(const vector<string>& names)
{
   int counter = 1;
   for (const string& name : names)
      nameMapping.emplace(name, counter++);
}

There's really no reason to complicate matters just for the sake of using "fancy" standard algorithms.


Q: Postgresql - Postgis - how to filter content? I have imported a shapefile that consists of POINT data.
Here is the query:
SELECT a.name,
       ST_Distance(ST_GeographyFromText(ST_AsText(a.geom)),
                   ST_GeographyFromText(ST_AsText(b.geom)))/1000 AS distance
FROM places a, places b
WHERE b.name='Mumbai';

This query displays distances (in KM) of places from 'Mumbai'.
Giving the output:
                       name                       |     distance
--------------------------------------------------+------------------
 Mumbai                                           |                0
 New Delhi                                        | 1159.26223973831
 Pune                                             |  117.86639722221
 Vittalpuram                                      | 1058.49956760668
 Kadapakkam                                       |  1064.4166204267
 Chellampatty                                     | 1136.24329302432
 Srirampur                                        |  205.27117214342
 Bhorvadi                                         |  213.69790081481
 Vaduj                                            |  227.66082105079
 Pushkar                                          |   853.0369297591
 Orcha                                            |  927.67801469371
 Phillaur                                         | 1369.21450470719
 Goraya                                           |  1381.0316667358
 Phagwara                                         | 1390.76210842565
 Ludhiana                                         | 1358.93226658828
 Mohali                                           | 1361.88704243237
 Morinda                                          | 1362.40782426879
 Kurali                                           | 1368.92321753998
 Rupnagar                                         | 1382.46666378301
 Moga                                             | 1335.85239784081
 Pahalgām                                         | 1689.72733587196
 Ambala                                           | 1327.24107571448
 Doraha                                           | 1351.41408180716
 Entrance of Ranjeet Avenue                       | 1351.43744476875
 Shaheed Jasdev Singh Nagar                       | 1353.19967929777
 Jagbir House                                     | 1357.58692404013
 Rania                                            | 1350.48320804851
 Pawa                                             | 1354.30374843403
 Sreenh                                           | 1347.01369530847
 Kaind                                            | 1345.76155280418
 Dharour                                          | 1352.71636605571
 TIBBA                                            | 1350.96268614694
 NAAT                                             |   1351.965780883
 Harnampura                                       | 1350.90891035291
 Nandpur                                          | 1354.12810806732
 Umadpur                                          | 1350.92919575633
 Dugri                                            | 1350.23846455405
 Dehlon intersection                              | 1341.15103218979
 Alwarpet                                         | 1029.21518660807
 Teynampet                                        | 1028.07582220005
 Gopalapuram                                      | 1028.37800837912
 Nandanam                                         | 1028.41251498301
 Raja Annamalai Puram                             | 1029.83876612634
 Abhiramapuram                                    | 1029.72834342923
 CIT Colony                                       | 1029.16938386861
 Sriperumbudur                                    | 1009.05941189302
 Poonamallee                                      | 1015.86523604896

Now I intend to filter out the results so as to view places where distance <= 500. How can I achieve this?

A: Use your query as a subselect:
SELECT *
FROM (SELECT a.name ...) dummy
WHERE distance < 500.0;


Q: HANA Query: CASE WHEN, without SELECT Statment I want to understand the CASE WHEN Statment in SAP HANA Query.
It is now to write a Value in a Column, only if there is a Value in the Column before.
"$[$3.U_chsBestNr2.0]" is the Column before (i get the value of this Column with this Statement).
CASE WHEN $[$3.U_chsBestNr2.0] <> '' THEN
SELECT T1."Name"
FROM OPOR T0
LEFT JOIN "@CHS_BEL_BELEGTYP" T1 ON T0."U_chsBelTyp" = T1."Code"
WHERE T0."DocEntry" = $[$3.U_chsBestNr2.0] AND T0."DocStatus" = 'O'
END CASE

The Error appear always as follow:
...257 sql error: incorrect syntax near "CASE"..


Q: Django; 2 model/class/tables pass into one template Forgive me if I ask something foolish, I very new to coding industry
I been working on Django project to create dashboards to show case monitoring of an hydroponics greenhouse.
So I create two model;
class tank_system(models.Model):
PH = models.DecimalField(default=7.5,max_digits=3, decimal_places=1)
EC = models.DecimalField(default=13.3,max_digits=3, decimal_places=1)
Winlet = models.DecimalField(default=20.1, max_digits=3, decimal_places=1)
Woutlet = models.DecimalField(default=20.3,max_digits=3, decimal_places=1)
WaterLevel = models.IntegerField(default=500)
TempWater = models.IntegerField(default=25)
tanks = models.IntegerField(default=1)
datetime = models.DateTimeField(default=timezone.now())

class ambient (models.Model):
TempRoom = models.IntegerField(default=25)
CO2 = models.DecimalField(default=20.0, max_digits=3, decimal_places=1)
O2 = models.DecimalField(default=20.0,max_digits=3, decimal_places=1)
Humdity = models.IntegerField(default=25)
Room = models.IntegerField(default=1)
datetime = models.DateTimeField(default=timezone.now())

and I render the data of two model into one single template
here my views;
from django.shortcuts import render, get_object_or_404
from CGI.models import tank_system, ambient

def index(request):
    tank = tank_system.objects.all()
    room = ambient.objects.all()
    return render(request, 'CGI/Pages/DashBoard.html', {'tank': tank},{'room': room})

when I try this I only got data form 1 table
Here my html template;
{% extends "base.html" %}
 {% block content %}
{%load staticfiles%}
 {% load static %}

Camera

Ambinet

                <video id="livestream" width="550" height="350" autoplay></video>
                 <canvas class = "my-4 chartjs-render-monitor" id="live_vid" height="1"></canvas>

                    <picture>

                    </picture>

                    {% for ambient in room %}
                         {% if forloop.first %}
                         {{  ambient.Humdity }}
                         {% endif %}
                         {% endfor %}
                    %

                    <picture>

                    </picture>

                    {% for ambient in room %}
                         {% if forloop.first %}
                         {{  ambient.TempRoom }}
                         {% endif %}
                         {% endfor %}
                    C

                    <picture>

                    </picture>

                    {% for ambient in room %}
                         {% if forloop.first %}
                         {{  ambient.CO2 }}
                         {% endif %}
                         {% endfor %}

Water tank

                        <picture>

                        </picture>

                    {% for tank_system in tank %}
                         {% if forloop.first %}
                         {{ tank_system.PH }}
                         {% endif %}
                         {% endfor %}

                        <picture>

                        </picture>

                    {% for tank_system in tank %}
                         {% if forloop.first %}
                         {{ tank_system.EC }}
                         {% endif %}
                         {% endfor %}
                    %

                        <picture>

                        </picture>

                    {% for tank_system in tank %}
                         {% if forloop.first %}
                         {{ tank_system.TempWater }}
                         {% endif %}
                         {% endfor %}
                    C

                        <picture>

                        </picture>

                    {% for tank_system in tank %}
                         {% if forloop.first %}
                         {{ tank_system.Winlet }}
                         {% endif %}
                         {% endfor %}
                    ml/hr

                        <picture>

                        </picture>

                    {% for tank_system in tank %}
                         {% if forloop.first %}
                         {{ tank_system.Woutlet }}
                         {% endif %}
                         {% endfor %}
                    ml/hr

                        <picture>

                        </picture>

                    {% for tank_system in tank %}
                         {% if forloop.first %}
                         {{ tank_system.tanks }}
                         {% endif %}
                         {% endfor %}
                    L

Water data

Room data

here picture better understanding;

If you could help I, really appreciated

A: You have 4 arguments in your render of which 2 is context. It needs only one dictionary with context or you can make a context dictionary variable and pass it as argument in render.
Try this:
from django.shortcuts import render, get_object_or_404
from CGI.models import tank_system, ambient

def index(request):
    tank = tank_system.objects.all()
    room = ambient.objects.all()
    return render(request, 'CGI/Pages/DashBoard.html', {'tank': tank,'room': room})

OR
from django.shortcuts import render, get_object_or_404
from CGI.models import tank_system, ambient

def index(request):
    tank = tank_system.objects.all()
    room = ambient.objects.all()
    context = {
           'tank': tank,
           'room': room
       }
    return render(request, 'CGI/Pages/DashBoard.html',context)

A: You can pass data using two different ways
def index(request):
    tank = tank_system.objects.all()
    room = ambient.objects.all()
    return render(request, 'CGI/Pages/DashBoard.html', {'tank': tank,'room': room})
                  or
    return render(request, 'CGI/Pages/DashBoard.html', locals())
locals() stands for get all local variable/objects and pass to the html as context

A: In your index method, make changes as:
def index(request):
    tank = tank_system.objects.all()
    room = ambient.objects.all()
    return render(request, 'CGI/Pages/DashBoard.html', {'tank': tank, 'room': room})


Q: Find the locus of points $P$ for which angle bisector of tangents to a standard ellipse is $y = x \tan \theta$.
Find the locus of points $P$ for which angle bisector of tangents to a standard ellipse is $y = x \tan \theta$.

Let $ P = (u, v)$ and ellipse be $E = \dfrac{x^2}{a^2} + \dfrac{y^2}{b^2} - 1$
Then joint tangent equation for the point $P$ is $$J(x,y) = \dfrac{(y-v)^2}{b^2} + \dfrac{(x-u)^2}{a^2} - \dfrac{(uy-vx)^2}{a^2b^2} $$
I have to find $(u,v)$ for which the angle bisectors of line pair $J$ are $ y - x\tan \theta = 0$ and $y + x\cot \theta -v - u \cot \theta = 0$.
Translating $P$ - the centre of $J$ - to origin with $x = X + u$ and $y = Y + v$:
$$J'(X, Y) = J(X+u, Y+u) = X^2 \left (\dfrac1{a^2} - \dfrac{v^2}{a^2b^2}\right)
 + Y^2 \left (\dfrac1{b^2} - \dfrac{u^2}{a^2b^2}\right) + \dfrac{2XYuv}{a^2 b^2}$$
The translated angle bisectors are $Y - X\tan \theta + v - u \tan \theta = 0$ and $Y + X \cot \theta = 0$.
The angle bisectors of $J'$ is given by $$X^2 \dfrac{uv}{a^2b^2} + \left(\dfrac1 {b^2} -\dfrac{u^2}{a^2b^2} -\dfrac{1}{a^2} +\dfrac{v^2}{a^2b^2} \right)XY - \dfrac{uv}{a^2b^2} Y^2 = 0\tag 1$$
or $$(Y + X \cot \theta) (Y - \tan \theta X + v - u \tan \theta) = 0\tag 2$$
Equating corresponding terms of $(1)$ and $(2)$ gives $$\begin{cases}3) : uv = -a^2b^2 \\4) : v = u \tan \theta \\5) : \dfrac1 {b^2} -\dfrac{u^2}{a^2b^2} -\dfrac{1}{a^2} +\dfrac{v^2}{a^2b^2} = \cot \theta - \tan \theta \end{cases}$$
From $(3)$ and $(5)$ I get $u^2 - v^2 -uv(\cot \theta - \tan \theta) = a^2 - b^2$

The answer given is $u^2 - v^2 -2uv\cot \theta = a^2 - b^2$.
Where did I go wrong ?
Is there any alternative way to do this questions, my method is very tedious ?

A: I think there is something wrong in this question, unless I'm missing something. Requesting that the angle bisector of the tangents issued from $P$ is $y=x\tan\theta$ is the same as requesting that the angle bisector passes through $O=(0,0)$, that is through the center of the ellipse (assuming that a "standard ellipse" has its center there).
If $A$ and $B$ are the tangency points and $M$ their midpoint, it is a property of the ellipse that line $PM$ passes through $O$. Hence, to satisfy the request, the bisector of $\angle APB$ must pass through $M$, which entails $PA=PB$. But this condition is satisfied only if $P$ belongs to the axes of the ellipse (unless the ellipse is a circle).
In addition, I don't understand the role of $\theta$: if it is given (as it seems to be), then $P$ must belong to the given line $y=x\tan\theta$, what is the meaning of asking for the locus of $P$?
EDIT.
Your solution is right, but substituting there $\tan\theta=v/u$ (from eq. $(4)$) you get $0=a^2-b^2$. The only way to have a solution is then if $a=b$ (the ellipse is a circle) or if either $\tan\theta$ or $\cot\theta$ doesn't exist ($P$ lies on the coordinate axes).


Q: how to filter join query with Flask and SQLAlchemy Hello I'm trying to query something like this in SQLAlcehmy, Flask and Graphene
select d."name", e."name"
from departments d
join employees e on e.department_id = d.id
where e."name" like '%M%' and d."name" = 'IT'

so, it would return all employee with name contains 'M' in department 'IT'
here's my query in python using sqlalchemy
find_department = graphene.List(Department, name = graphene.String(), employee = graphene.String())
def resolve_find_department(self, info, name, employee):
  like_query = '%{0}%'.format(employee)
  department = (Department.get_query(info)
                          .join(EmployeeModel)
                          .filter(DepartmentModel.name == name)
                          .filter(EmployeeModel.name.ilike(like_query)))

  return department

and in my graphql
{
  findDepartment(name:"IT", employee:"M"){
    name
    employees{
      edges{
        node{
          name
        }
      }
    }
  }
}

and the result is it returns all employee instead of 1 with name contains 'M'
{
  "data": {
    "findDepartment": [
      {
        "name": "IT",
        "employees": {
          "edges": [
            {
              "node": {
                "name": "Chris"
              }
            },
            {
              "node": {
                "name": "Dori"
              }
            },
            {
              "node": {
                "name": "Mario"
              }
            }
          ]
        }
      }
    ]
  }
}

why is that happening? how to show only 1 just like the SQL query returns?
thanks
UPDATE:
the query from SQLAlchemy was fine
SELECT departments.id AS departments_id, departments.name AS departments_name
FROM departments JOIN employees ON departments.id = employees.department_id
WHERE departments.name = 'IT' AND employees.name ILIKE '%M%'

but somehow when it's called using graphql, with query above, it returns all employee instead of the filtered one
how to return only the filtered Employee?

A: I think you need to use an "and_" filter to make sure sqlalchemy returns only rows which fulfil all the requirements (rather than at least one of the filters):
from sqlalchemy import and_
department = (Department.get_query(info)
                      .join(EmployeeModel)
                      .filter(and_(DepartmentModel.name == name, EmployeeModel.name.ilike(like_query)))

not 100% sure if this works with graphene or whatever (i think this is unrelated in this case...). Also check this link: sqlalchemy tutorial
Give it a try!


Q: spring boot rest webservice, how to improve a clean code? i started a project on spring boot using a rest a webservice, when i shared  it between my team they puted some comments :

*

*get method need to be grouped Ex : get/users & get/users/{id} will be get/users/{id}

*remove put method & just use post Ex: post/users/0 add | post/users/{id} update

*make a helper class for Jdbc Template and call it in the repository classes to centralize the code

pls guys help me to solve this i'm so confused, and thank you

A:
get method need to be grouped Ex : get/users & get/users/{id} will be
  get/users/{id}

I do not agree with this. /get/users will be returning List<User> and get/users/{id} will return User that matches with {id}

remove put method & just use post Ex: post/users/0 add |
  post/users/{id} update

Post should be used when you create a new resource. POST is not idempotent. Each time you call a post a new resource will be created.
e.g. Calling POST /Users will create a new User every-time.
PUT on other hands works like upsert. Create if the resource is not present and update/replace if present. Put is idempotent and doesn't change the resource's state even if it's called multiple times.

make a helper class for Jdbc Template and call it in the repository
  classes to centralize the code

Helper classes help to separate the concerns and achieve single responsibility.
However, JdbcTemplate is a ready to use abstraction of JDBC. I don't see any point in creating Helper. You can create a DataAccessObject (DAO) or Repository which has-a JdbcTemplate. Like the two Dao shown below
public class UserDao {
    @Autowired
    private JdbcTemplate jdbcTemplate;

    public User findUserById(String id){}

    public void addUser(User user){}
}

//    -------
public class BooksDao{
    @Autowired
    private JdbcTemplate jdbcTemplate;

    public List<Book> getAllBooksByType(String type){}

    public void Book getBookByName(String name){}
}

Now, your Dao objects can be called from Controller or if you need to modify data before/after DB operation, best is to have a Service layer between Controller and Dao.
Don't bother too much about recommendations or rules. Stick to the basic OOPS concepts. Those are really easy to understand and implement.
Always:

*

*Encapsulate data variables and methods working on those variables together

*Make sure your class has a Single Responsibility

*Write smaller and testable methods (if you can't write tests to cover your method, then something is wrong with your method)

*Always keep the concerns separate

*Make sure your objects are loosely coupled. (You are already using spring so just use the spring's auto-wiring)


Q: How to override routes in ng-admin? I want to change url in ng-admin state. For example, I need to add a trailing / at the URL for getting a list of users. (http://localhost/api/v1/users/ instead of http://localhost/api/v1/users)

A: The Entity and View classes offer a baseUrl() method, so it's probably not very hard. Just follow the directions from the documentation:

*

*https://github.com/marmelab/ng-admin/blob/master/doc/Configuration-reference.md#entity-configuration

*https://github.com/marmelab/ng-admin/blob/master/doc/Configuration-reference.md#entity-configuration

*https://github.com/marmelab/ng-admin/blob/master/doc/API-mapping.md


Q: Are there any multiple desktops software for Vista? (similar to what is included in GNOME and KDE) In GNOME and KDE, (and from what I hear, OS X aswell), you have a feature called multiple desktops. It allows you to have multiple screens of apps running, without having the same number of monitors. Does such a program exist for Vista?
I'd like around four desktops (one for IM, one for programming, one for browsing/email and one for other apps), and at home I usually have one monitor if using my laptop outside of home, or two if I'm using it at home.

A: Virtual Desktop Manager
Features

*

*Full screen desktop/window
manager/preview with full drag and
drop managing

*Desktop switch indicator

*An infinite number of desktops

*Watch the windows move in real time
as you drag them around in the window
manager

*Multiple monitor support

*Window menus

*Tray icons for each desktop

*Per-desktop backgrounds

*Configurable colors, fade speeds,
hotkeys, etc.

*Uses Vista's live thumbnails

*XP support

A: From the Sysinternals guys: Desktops

Desktops allows you to organize your
  applications on up to four virtual
  desktops. Read email on one, browse
  the web on the second, and do work in
  your productivity software on the
  third, without the clutter of the
  windows you’re not using. After you
  configure hotkeys for switching
  desktops, you can create and switch
  desktops either by clicking on the
  tray icon to open a desktop preview
  and switching window, or by using the
  hotkeys.

A: Dexpot creates and manages up to 20 virtual desktops and enables you to work far more efficiently and comfortably with many simultaneously opened windows on Windows 95/98/ME and NT4/2000/XP/2003/Vista/7 (including 64-bit).

Dexpot is freeware.

A: I use the portable version of VirtuaWin. It's not flashy, but it is simple, customizable, and portable.  There are  tons of plug-ins for it.

A: Nvidia graphic drivers include a solution for this called nViews, so if you own a nVidia card...


Q: how to remove a specific factor level to missing value in r? I got a factor data set df that looks like this:
df <- data.frame(attend = c("yes", "no", "no", "iap", "yes", "yes", "iap"),
           sex = c("male", "female", "female", "male", "female", "male", "female"))

df$attend <- as.factor(df$attend)
df$sex <- as.factor(df$sex)

df

attend
sex

yes
male

no
female

no
female

iap
male

yes
female

yes
male

iap
female

I want to remove only the iap level from the attend variable.(I don't want to remove the entire row, what I'm looking for is to remove the level iap, so that it becomes a missing value under variable attend)
I tried the below code to remove it but it occurs an error saying:
Error in UseMethod("droplevels") :
no applicable method for 'droplevels' applied to an object of class "character".
df$attend <- droplevels(levels(df$attend)[4])

Much appreciated it if someone can help.

A: You can change the levels of the variable -
levels(df$attend)[levels(df$attend) == 'iap'] <- NA
df

#  attend    sex
#1    yes   male
#2     no female
#3     no female
#4   <NA>   male
#5    yes female
#6    yes   male
#7   <NA> female

This will also automatically drop the 'iap' as level.
levels(df$attend)
#[1] "no"  "yes"

Here we can also use forcats::fct_recode to turn specific values to NA.
df$attend <- forcats::fct_recode(df$attend, NULL = 'iap')

A: Another base R solution would be using exclude:
df$attend <- factor(df$attend, exclude = "iap")

  attend    sex
1    yes   male
2     no female
3     no female
4   <NA>   male
5    yes female
6    yes   male
7   <NA> female


Q: Compare X with Y (structures) I was reading this question - "Is this sentence grammatically correct? (compare the social life in x neighborhoods with those in y neighborhoods)" and thought about a few different structures to this one.
Well, the OP there asks whether is it okay to use "those" to substitute the objects.
I would like to ask whether we can also use "ones" instead of "those" to substitute objects:

*

*I want to compare the batch of apples from Abkhazia to ones from Kazakhstan.

*I want to compare the batch of apples from Abkhazia to those from Kazakhstan.

Does using "ones" instead of "those" make anything change? When is it more suitable to use "ones" and when "those"?
I would also like to know if we can (and whether it is correct to) use both words "those ones":

*

*I want to compare the batch of apples from Abkhazia to those ones from Kazakhstan.

Should there also be a definite article before "ones"?

A: If those is to refer to “social life” then why plural pronoun? I would go for “that”.
Therefore, we can have; “ compare social life in X neighborhoods with the one in Y neighborhoods”.
Yes, use article, because the noun has been already introduced and both the speaker and listeners about what they are talking about.
Please wait for more answers to make sure that mine is correct.

A: There is a difference between those and ones.  Those points to a specific group, whereas ones does not point at anything.  With ones individuals could be selected at random or arbitrarily from the group.  ones is indefinite.
With those the group pointed at could be a previously mentioned specific subgroup or if there is no such mention, the  group in its entirety.

I like white wines. Those from Germany are my favorites.

That is, I like any and all German white wines.

I like white wines. Ones from Germany are my favorites.

Unspecified white wines from Germany are my favorite wines. Although one might infer that the statement above means that I like all German wines, that is not what it says. There is no determiner. Had it said "The ones from Germany" the reference would be to all types of German white wine. Without a determiner, it could be all or it could be one type or it could be wines from a particular vineyard or region.   The rejoinder to the statement above could be "Which ones?"

I like good white wines, especially German Spaetlese.  Those are my favorites.

Of the wines I like, a subgroup of German whites, the Spaetlese, are the wines I like the best.


Q: string-splitting and arrays In this program for storing high scores I want the user to input a player's name and high score in a single line, for example "eric 87".
After the user enters the last player's name and score, it should then list all at once the scores that were entered. I don't know how to do this when splitting strings like "eric 97". Thanks very much for any help!
const int MAX = 20;
static void Main()
{
    string[ ] player = new string[MAX];
    int index = 0;

    Console.WriteLine("High Scores ");
    Console.WriteLine("Enter each player's name followed by his or her high score.");
    Console.WriteLine("Press enter without input when finished.");

    do {
        Console.Write("Player name and score: ", index + 1);
        string playerScore = Console.ReadLine();
        if (playerScore == "")
            break;
        string[] splitStrings = playerScore.Split();
        string n = splitStrings[0];
        string m = splitStrings[1];

    } while (index < MAX);

    Console.WriteLine("The scores of the player are: ");
    Console.WriteLine("player \t Score \t");

  //  Console.WriteLine(name + " \t" + score);
    // scores would appear here like:
    // george 67
    // wendy 93
    // jared 14

A: Looking at your code you didn't put your player array to use.
However, I would suggest a more object oriented approach.
public class PlayerScoreModel
{
    public int Score{get;set;}

    public string Name {get;set;}
}

Store the player and scores in a List<PlayerScoreModel>.
And when the last user and score has been entered.. simply iterate through the list.
 do {
        Console.Write("Player name and score: ", index + 1);
        string playerScore = Console.ReadLine();
        if (playerScore == "")
            break;
        string[] splitStrings = playerScore.Split();
        PlayerScoreModel playerScoreModel = new PlayerScoreModel() ;

        playerScoreModel.Name = splitStrings[0];
        playerScoreModel.Score = int.Parse(splitStrings[1]);
        playerScoreModels.Add(playerScoreModel) ;

    } while (somecondition);

   foreach(var playerScoreModel in playerScoreModels)
   {
      Console.WriteLine(playerScoreModel.Name +" " playerScoreModel.Score) ;
    }

Provide error checking as necessary.


Q: No login sound in Kubuntu 16.10 Hi I am new to Kubuntu 16.10 and I have no startup or shutdown sound. I have looked everywhere in system settings and see no setting for either a startup  login or shutdown sound. Can someone tell me where to go to get this? Preferably step by step Konsole commands that I can use to get both sounds working? Thank you in advance for your help with this.

A: KDE Notifications
KDE System Settings > Notifications
Event source: Plasma Workspace
Enable the 'Play a sound' at the Login/Logout

Launch the 'Event Notifications and Actions' from terminal:
kcmshell5 kcmnotify


Q: TypeError: super() takes at least 1 argument (0 given) With this code: https://github.com/SmBe19/praw-OAuth2Util
It's receiving this error:
Traceback (most recent call last):
  File "update_sidebar.py", line 6, in <module>
    o = OAuth2Util.OAuth2Util(r)
  File "/usr/lib/python2.7/site-packages/OAuth2Util/OAuth2Util.py", line 162, in __init__
    self.refresh()
  File "/usr/lib/python2.7/site-packages/OAuth2Util/OAuth2Util.py", line 364, in refresh
    self._get_new_access_information()
  File "/usr/lib/python2.7/site-packages/OAuth2Util/OAuth2Util.py", line 254, in _get_new_access_information
    self._start_webserver(url)
  File "/usr/lib/python2.7/site-packages/OAuth2Util/OAuth2Util.py", line 229, in _start_webserver
    self.server = OAuth2UtilServer(server_address, OAuth2UtilRequestHandler, authorize_url)
  File "/usr/lib/python2.7/site-packages/OAuth2Util/OAuth2Util.py", line 58, in __init__
    super().__init__(server_adress, handler_class, bind_and_activate)
TypeError: super() takes at least 1 argument (0 given)

By doing:
import praw
import OAuth2Util

user_agent = "sidebar helper"
r = praw.Reddit(user_agent=user_agent)
o = OAuth2Util.OAuth2Util(r)

Is the code missing something?

A: According to @Ryan, your problem is that you are running it in Python 2 instead of Python 3. Running it in Python 3 should fix it.


Q: CSS responsive design using em for the layout I have to design a (responsive) website, using only HTML5, CSS3, elastic design, and em as unit measurement. I dont know how to apply em on the width and height properties to make the margins of the main wrapper (i.e. div #page) equal on all sides in relation to the actual screen size.
I have tried the width and height properties with different em-values, but that leads to the margins not being equal. I have tried to find some sort of conversion between em and %, but since em is based on font size it's always the percentage of the font size. I have also tried to instead apply the position property to other containers and elements inside #page.

#page {
    position: relative;
    width: 90%;
    height: 90%;
    top: 1em;
    right: 1em;
    bottom: 1em;
    left: 1em;
}

I want to be able to only use em as measurement unit and have the margins of #page equal in relation to the actual screen size, but the width either becomes longer than the screen size, or the right margin is not equal to the other margins.
Here is a link to JSFiddle with my entire code:
https://jsfiddle.net/binaryglot/8dkn96g0/

A: you can just using margin:0em auto for making the div page stay on the center. But unfortunately you can't make teh height on the center. Here the fiddle for making width and stay on center.
#page {
  position: relative;
  width: 90%;
  height: 90%;
  top: 1em;
  margin:0em auto;
  bottom: 1em;
}

JSfiddle
You can adjust the height using padding--but you can't make it responsive for the height... so far i know.

A:     #page {
    position: fixed;
    width: 90%;
    height: 90%;
    top: 1em;
    right: 1em;
    bottom: 1em;
    left: 1em;
    margin: auto;
    }

Using combination of fixed position and auto margin did the trick. Hope this helps!


Q: Extract some part from filename as variable I have read some threads about extracting some parts from filename, but still cannot solve my problem.
There are some files named aa - bb.txt, cc - dd.txt, ee - ff.txt, etc.
And the last line in every file is like this:
somewordbbaa

for aa - bb.txt and for cc - dd.txt is:
somewordddcc

Then in ee - ff.txt is:
somewordffee

I want to write a shell script to delete the bbaa, ddcc, ffee in last line of the respective file. I have tried following:
#!/bin/bash
for file in *.txt
do
  artist=`echo $file | awk -F'[ .]' '{print $1}'`
  name=`echo $file | awk -F'[ .]' '{print $3}'`
  echo $artist >> artist
  echo $name >> name
  sed -i "s/$name$artist//" $file
done

And after I ran it,it threw this
sed: can't read aa: No such file or directory
sed: can't read -: No such file or directory
sed: can't read bb.txt: No such file or directory
sed: can't read cc: No such file or directory
sed: can't read -: No such file or directory
sed: can't read dd.txt: No such file or directory
sed: can't read ee: No such file or directory
sed: can't read -: No such file or directory
sed: can't read ff.txt: No such file or directory

I also tried this
#!/bin/bash
ls *.txt | sed 's/\.txt//' > full_name
cut -f1 -d" " full_name > artist
cut -f3 -d" " full_name > name

for file in `ls -1 *.txt`, item1 in artist, item2 in name #Is this right?
do
  tail -n -1 $file | sed 's/$item2$item1//' > $file.last #just the last line
done

It just showed this and had no reaction until pressing Ctrl+c
tail: cannot open `aa' for reading: No such file or directory

I think bash puts the blank of the filename as the separator, reads the $file as aa, -, bb.txt.
Can anyone give me some advice?

A: Because your files have a space in the name, try your original script but change this line:
sed -i "s/$name$artist//" $file
to this:
sed -i "s/$name$artist//" "$file"


Q: ¿como refrescar los eventos de fullcalendar? estoy creando una aplicacion con laravel y fullcalendar y quiero que al darle a un boton cree un evento nuevo y lo dej ver de inmediato, ya pude hacer que lo cree sin problemas, la cuestion es que no se actualiza hasta que recargue la pagina. este es mi codigo :
$('#guardar').click(function(){
     $.ajax({
     url:"/calendar/crear",
     type:"POST",
      data:$("#formulario_guardar").serialize(),
   }).done(function(uno){
     $('#exampleModal').modal('hide');
    $("#calendar").fullCalendar( 'refetchEvents' );
   });

no se actualiza, si alguien sabe porque le agradezco mucho la informacion.

A: Debes utilizar render de fullcalendar
Algo así:
$("#TuCalendario").fullCalendar('render');

Espero te ayude, Saludos!

A: $('#calendar').fullCalendar('renderEvent', {
     title: 'Sin Atencion',
     start: start,
     end: end,
     backgroundColor:'red',
     color: 'red',
     TextColor: 'black',
     borderColor: 'red'
 });
despues del modal hide coloca ese codigo con los datos de tu evento


Q: What technique is used to create a div limited by the page fold? Skipping the discussion about the importance of the fold in web design, I'd like to know which technique is used to limit a specific section (could be a div, for example) exactly on the browser fold considering a responsive design. Some websites even use both the mouse scroll and the a button to slide to the section below.
Ex.: Next
My point is not the slide itself, but how each section renders exactly on the fold regardless of the monitor resolution.

A: With:
window.innerHeight

You can know the height of the browser window and style your elements accordingly.
I am assuming that by fold you mean what you see without scrolling.
If you need a more backwards compatible (<I.E9) height and you can use jquery:
$( window ).height();

A: You might try using the css unit of measurement vh. Say you have a div that you only want to take up half the screen (viewport) you would do something like this:
div{
    height: 50vh;
}

vh stands for "Viewport Height" and is used like a percentage. So to have the div always take up 100% of the view-able area (viewport), regardless of the screen size or resolution you would do this: div { height: 100vh; }

A: I would use document.documentElement.clientHeight and document.documentElement.clientWidth which are essentially the width and height of the html element:
$('div').css({'height':document.documentElement.clientHeight+'px',
              'width':document.documentElement.clientWidth+'px'});

http://jsfiddle.net/L1wsLc2c/1/
You would have to re-execute this code every time the window is resized to keep the bottom of the box flush with the page fold.


Q: Finitely many Supreme Primes? A challenge on codegolf.stackexchange is to find the highest "supreme" prime: https://codegolf.stackexchange.com/questions/35441/find-the-largest-prime-whose-length-sum-and-product-is-prime
A supreme prime has the following properties:

*

*the number itself is prime

*the number of digits is prime

*the sum of digits is prime

*the product of digits is prime

Are there finitely many "supreme" primes? Are there infinitely many? Currently the highest one found is ~$10^{72227}$

A: This is not an answer, just a bit too long to be a comment. I didn't write the code for finding supreme primes, but I think it is simple.
All supreme primes $x$ are of the form:
$$x = \sum_{k=0}^n 10^k + 10^w\times(p-1) = \frac{10^{n+1} - 1}{9} + 10^w\times(p-1) \tag{1}$$
where $p$ is a prime number, and $0\le w \le n$. Therefore you only need to explore varying three parameters: $n,w,p$. Moreover, the search can be restricted so that $n + p$ (digit sum) and $n + 1$ (number of digits) are prime numbers (see comments). Defining $q = n +1$, we have to search pairs of prime numbers $p,q$ such that $p + q - 1$ is also a prime number (see comments). Having found such a pair, search for a $w$ in the range $0\le w\le q - 1$ such that $x$ in (1) is prime.
Just to clarify (there was some confusion in the comments), note that an $x$ of the form (1) may not be a supreme prime; indeed we still need to know that $x$ itself is prime.

A: Heuristically, a random $n$-digit number has probability approximately  $c/n$ of being prime, where $c$ is a positive constant.  Since $p$ is $3$ or $5$ or $7$ and there are $n$ possible locations for it, there are $3n$  $n$-digit candidates.  So the expected number of primes of this form among the $n$-digit candidates should be approximately constant.  This would indicate that there should be infinitely many supreme primes.  Of course it is not a proof.  It would be very surprising if this could be proven.

A: Only some extended hints:
The numbers are necessarily of the form $N=\frac{10^n-1}9+a10^k$ with $0\le k<n$ and $a+1$ prime (i.e. $a\in\{1,2,4,6\}$) to meet the product criterion. Of course, $n$ must be prime to meet the length criterion. Next, the digit sum is $n+a$, which rules out $a=1$ except for small cases.
If $a=2$ we must have $n\equiv -1\pmod 6$. Then $N\equiv n-k \pmod 3$, so we need $k\not\equiv -1\pmod 3 $. Also , $\frac{10^n-1}9\equiv 2\pmod 7$, ${}\equiv 9\pmod {13}$, ${}\equiv 11\pmod{37}$, which rules out another fraction $\frac 17$, $\frac 1{13}$, $\frac1{37}$, respectively, of possible $k$ values.
Similarly, if $a=4$ we must have $n\equiv 1\pmod 6$. Then $N\equiv n+k\pmod 3$, so we need $k\not\equiv -1\pmod 3$ again. The argumentation with the primes $7,13,37$ dividing $111111$ applies as well in a similar way.
More generally, for any (small) prime $p>5$ we can obtain restrictions for $n,k\pmod{p-1}$. This makes it easy to construct $N$ which has no small prime divisors (and of course fulfills the sum, product, and length criterion). There's still a long way to go to make $N$ prime, of course.
Heuristically, the chance of $N$ being prime is $\sim \frac1n$; and since we have $\sim n$ choices for $k$, we'd expect a certain more or less constant amount of supreme primes per $n$ ...


Q: Como permitir execução de javascript em linha? (extensão google) Olá, eu estava montando uma extensão que recebia urls em um formulário e adicionava novos campos quando um botão fosse pressionado. Executando como html normal o código funciona, mas quando eu executo como extensão ele retorna esse erro:
Refused to execute inline event handler because it violates the
following Content Security Policy directive: "script-src 'self' blob:
filesystem: chrome-extension-resource:". Either the 'unsafe-inline'
keyword, a hash ('sha256-...'), or a nonce ('nonce-...') is required
to enable inline execution.

HTML usado:
<form id="formulario">
  <input type="url" class="campo" placeholder="endereço..." />

</form>

JAVASCRIPT usado:
var sis_interface = {
  novocampo : function() {
    document.getElementById("formulario").innerHTML += '<input type="url" class="campo" placeholder="endereço..." />';
  }
}

Agradeço desde já a ajuda.

A: Resposta obtida do link How to fix chrome-extension inline JavaScript invocation error? (resposta no SO em inglês).


Q: how to use @keyframes moving animation from current position to a fixed in CSS3? This css3 code , move a item from current position to 100px lower.
@keyframes movingtocenter
{
from {top:0%;}
to {top:100px;}
}

But i want move my object to CENTER of page.
I have many object on the one page in different locations.
and i want to use this keyframes to move all of them to right-center,in the same position. and can't do this!
anyway to do this?

A: You need to make sure that the parent div covers the entire screen.  You can do this with the following css:
.wrapper {
    position: fixed;
    width: 100%;
    min-height: 100%;
}

Then you just need to specify the animation on the appropriate div, give it an absolute position and tell it where to go using keyframes.
.wrapper div {
    position: absolute;
    -webkit-animation: myfirst 5s; /* Chrome, Safari, Opera */
    animation: myfirst 5s;
}

.wrapper div.el1{
    right: 200px;
}

.wrapper div.el2 {
    right: 500px;
}
/* Chrome, Safari, Opera */
@-webkit-keyframes myfirst {
    0%   {top:0;}
    100% {top: 50%; right: 0;}
}

/* Standard syntax */
@keyframes myfirst {
    0%   {top:0;}
    100% {top:50%; right: 0;}
}

Fiddle

A: You missed one property in your element:
position:absolute;

See this: jsFiddle

Note:  Only Some Positioning Styles accept top, left, bottom, etc. properties. See documentation for details.


Q: How can you determine the hostname associated with an IP on the network? How can you determine the hostname associated with an IP on the network? (without configuring a reverse DNS)
This was something that I thought was impossible.  However I've been using Fing on my mobile.  It is capable of finding every device on my network (presumably using an arp-scan) and listing them with a hostname.
For example, this app is capable of finding freshly installed Debian Linux devices plugged into a home router, with no apparent reverse DNS.
As far as I know neither ping, nor Neighbor Discovery, nor arp include a hostname.  So how can fing be getting this for a freshly installed Linux PC?  What other protocol on a Linux machine would give out the machine's configured hostname?

A: The zeroconf protocol suite (Wikipedia) could provide this information.
The best known implementations are AllJoyn (Windows and others), Bonjour (Apple), Avahi (UNIX/Linux).
Example showing a list of everything on a LAN (in this case not very much):
avahi-browse --all --terminate
+  ens18 IPv6 Canon MG6650                                  _privet._tcp         local
+  ens18 IPv4 Canon MG6650                                  _privet._tcp         local
+  ens18 IPv6 Canon MG6650                                  Internet Printer     local
+  ens18 IPv4 Canon MG6650                                  Internet Printer     local
+  ens18 IPv6 Canon MG6650                                  UNIX Printer         local
+  ens18 IPv4 Canon MG6650                                  UNIX Printer         local
+  ens18 IPv6 Canon MG6650                                  _scanner._tcp        local
+  ens18 IPv4 Canon MG6650                                  _scanner._tcp        local
+  ens18 IPv6 Canon MG6650                                  _canon-bjnp1._tcp    local
+  ens18 IPv4 Canon MG6650                                  _canon-bjnp1._tcp    local
+  ens18 IPv6 Canon MG6650                                  Web Site             local
+  ens18 IPv4 Canon MG6650                                  Web Site             local
+  ens18 IPv6 SERVER                                        _device-info._tcp    local
+  ens18 IPv4 SERVER                                        _device-info._tcp    local
+  ens18 IPv6 SERVER                                        Microsoft Windows Network local
+  ens18 IPv4 SERVER                                        Microsoft Windows Network local

More specifically, you can use avahi-resolve-address to resolve an address to a name.
Example
avahi-resolve-address 192.168.1.254
192.168.1.254 router.roaima...

A: In Linux you may use dig or  host. Example:
dig -x 192.0.2.1

host 192.0.2.1

In windows you may use ping -a like so:
ping -a 192.0.2.1


Q: How to import actionscript 3 flash game into flash builder? I'm newbie in this area, and I would like to have an android app that can play my AcionScript game. My actonscript game consist of external sound and image.
How do I import my ActionScript file into flash builder?
Should I import my codes or my SWF file alone is enough?
Where should I import my external files?
Thank you in advance!

A: There are numerous options, such as:
Flash Pro
If your game has already been created in Flash Pro, you could simply target AIR for Android from Flash Pro's publish settings:

ADT Command Line Packager
Likewise, you could simply use the ADT command line packager to build your SWF to an Android distributable.
Flash Builder
Otherwise from Flash Builder, you can create a new ActionScript mobile project:

Select Android, or other target platforms:

Place code and packages relative to the src/ folder, same as you would relative to your FLA:

Your entire Flash app could be published as a SWC, then instantiated from Flash Builder, or individual assets may be exported as SWCs:

Likewise you can programmatically embed SWF assets in ActionScript classes using the embed metadata tag:
[Embed(source="asset.swf", symbol="symbol")]
private var SymbolClass:Class;

var symbol:MovieClip = new SymbolClass();


Q: Inconsistent Jackson deserialization of String as LocalDateTime I am deserializing a nested collection in JOOQ via Jackson.
The error I am encountering is like this,
Caused by: com.fasterxml.jackson.databind.exc.InvalidDefinitionException: Cannot construct instance of `java.time.LocalDateTime` (no Creators, like default constructor, exist): no String-argument constructor/factory method to deserialize from String value ('2020-12-18T11:29:03.290833') at [Source: (String)"{"wrapped_ts" : "2020-12-18T11:29:03.290833"}"; line: 1, column: 21] (through reference chain: blah.blah.WrappedTimestamp["wrapped_ts"])
This is inconsistent with behavior earlier in the deserialization process. A MRE would be,
=== Function using JOOQ ===
.select(
    TOP.ts,
    field(
        select(
            jsonArrayAgg(
                jsonObject(
                    LOWER.lowerTs
                )
            )
        )
        .from(LOWER).join(TOP).on(TOP.ID.eq(LOWER.TOP_ID))
    ).`as`("lowerLevels"),
    field(
        select(
            jsonObject(
                WRAPPED.FIRST,
                WRAPPED.SECOND
            )
        )
        .from(WRAPPED)
        .where(TOP.ID.eq(WRAPPED.TOP_ID))
    ).`as`("wrapped")
.from(TOP)
.where(condition)
.fetchInto(TopLevel::class.java)

=== Underlying data classes ===
@JsonNaming(PropertyNamingStrategy.SnakeCaseStrategy::class)
data class TopLevel(
    ts: LocalDateTime?,
    lowerLevels: List<LowerLevel> = emptyList(),
    wrapped: WrappedTimestamp?
)

@JsonNaming(PropertyNamingStrategy.SnakeCaseStrategy::class)
data class LowerLevel(
    lowerTs: LocalDateTime?,
)

@JsonNaming(PropertyNamingStrategy.SnakeCaseStrategy::class)
data class WrappedTimestamp(
    first: LocalDateTime?,
    second: LocalDateTime?,
) {
    constructor() : this(
        null
}

There are three different levels of timestamps. ts and lowerTs both deserialize fine, wrappedTs throws the error above. If it's unclear, my Jackson ObjectMapper does have the JavaTimeModule registered.
In the course of debugging I have created new deserialization targets at the level of WrappedTimestamp that function with no issue. I have also commented out the wrapped section of the select in JOOQ and it also works.
What could be accounting for this inconsistent behavior?


Q: How to get a list of all tables that have datatables applied? I need a list of all tables that have jQuery DataTables applied. I searched the docs and the API but I could not find an array or something like that that holds the tables.

A: You're looking for $.fn.dataTable.tables() - DataTables's static function.

It can be useful to be able to get a list of the existing DataTables
  on a page, particularly in situations where the table has scrolling
  enabled and needs to have its column widths adjusted when it is made
  visible. This method provides that ability.


Q: Limits of parallelization regarding the core number I'm developing a parallel algorithm on a Intel i5-core machine, which has two cores, four threads.
n defines the size of the matrix, on which I perform my calculations on. As you can see from the table below there is almost 50% reduction from 1 thread to 2 threads utilization, but almost no difference between 2 threads and 4 threads. The numbers denote the seconds passed

My compiler is mingw-gcc on windows platform. My parallelization tool is openmp. I'm defining number of threads by omp_set_num_threads(numThreads);in the beginning of the parallel routine.
I have no means to test the algorithm on a "real" 8 core machine. On my i5 machine, At 1 thread, task manager shows 25% of the total cpu power is used. At 2 threads, it's 50%, and at 4 threads, it's 96-99% as expected.
So what might be the reason for that situation? Why doesn't the computation time get halved?
The parallel code segment is to be found below:
    #pragma omp parallel for schedule(guided) shared(L,A) \
    private(i)
    for (i=k+1;i<row;i++){
        double dummy = 0;
        for (int nn=0;nn<k;nn++){
            dummy += L[i][nn]*L[k][nn];
            L[i][k] = (A[i][k] - dummy)/L[k][k];
        }
    }

A: Well, your machine has 2 cores and 4 threads.
You only have 2 cores, so you won't get 4x speedup from 1 - 4 threads.
Secondly, as you scale to more threads, you will likely start hitting resource contention such as maxing out your memory bandwidth.


Q: CSS html declarations with spaces If there is a simple google search for this question, I apologise now, but I'm unsure of which keywords I'm looking to use. I'm decent with CSS but I think I'm yet to utilise the full power of the language and also completely eradicate code redundancy.
I've come across this code (any similar snippets many other times):
<p class="comment smallertext center-align">

What CSS would this be referring to?
In terms of the comment, smallertext and center-align all being spaced.
Thank you in advance for any replies and guidance!

A: It means that element has all of the following classes: comment, smallertext and center-align. In HTML, spaces separate multiple class names in a single attribute.
In CSS, you can target this element using one or more of .comment, .smallertext or .center-align, either separately or together. Having three separate rules and a single element that has all three classes, all three rules will apply:
.comment {}
.smallertext {}
.center-align {}

You can also combine them together, if necessary, to apply styles specific to elements having all three classes:
.comment.smallertext.center-align {}

A: The code shown in the example links to 3 different css class selectors:
.comment {
}

.smallertext {
}

.center-align {
}

So instead of making lots of non-reusable css selectors, you split them up into lots of small ones that provide 1 functionality that will most likely be used for lots of different parts of your websites. In that example you have one for comments, one for smaller text and one for center aligning text.

A: It's a way of defining multiple classes to a single element. In this case it would match classes comment, smallertext and center-align.

A: Try this short explanation... Multiple classes can make it easier to add special effects to elements without having to create a whole new style for that element.


Q: How do I make an uploaded image permanent on a view controller in Swift? I am writing code to allow a user to upload an image on a view controller. The image can be uploaded successfully, but once you navigate away from the view controller and then come back to it, the image they uploaded is gone. How would I make the image a global variable so that when the user returns to the view controller, the image is still present? I am using imagePickerController to select the image for upload. This is my code


Q: MYSQL union order in first statement I have this query:
(SELECT * FROM items WHERE duration = 5 ORDER BY date DESC)
UNION
(SELECT * FROM items WHERE duration = 10)

The problem is the "ORDER BY" in the first query is not working.

A: Try this :
 select * from (
    SELECT * FROM items WHERE duration = 5
    UNION
    SELECT * FROM items WHERE duration = 10
    ) odrer by date DESC

A: When you use UNION OR UNION ALL order by not allowed in each select statement. You have to apply order by in outer select statement.

A: Order the UNION result by duration first, then date desc.
select *
from
(
    SELECT * FROM items WHERE duration = 5
    UNION
    SELECT * FROM items WHERE duration = 10
)
order by duration, date DESC

However, there's no need for a UNION (see e4c5's answer).

A: If I understood you from the comments, you want something like this?
SELECT s.* FROM (
    SELECT i.*,1 as ord_col FROM items i WHERE duration = 5
    UNION
    SELECT it.*,2 FROM items it WHERE duration = 10) s
ORDER BY CASE WHEN s.ord_col = 5 THEN s.date
                                 ELSE '1000-01-01'
         END DESC

Although this query is inefficient , you can do it with one select :
SELECT i.* FROM items i WHERE i.duration IN(5,10)
ORDER BY CASE WHEN s.ord_col = 5 THEN s.date
                                 ELSE '1000-01-01'
         END DESC

If its not dynamic, and 5 will be ordered before 10 and these are constant values , you can simply add the duration column to the query , ORDER BY duration,date although this will also order the second query be date, just after the first one.

A: I think you don't even need to UNION at all and you can refactor your query this way:
SELECT *
FROM items
WHERE duration IN (5, 10)
ORDER BY CASE
        WHEN duration = 5 THEN 1
        WHEN duration = 10 THEN 2
        ELSE NULL
    END
    , CASE
        WHEN duration = 5 THEN [date]
        ELSE NULL
    END DESC;

This query will sort based on your duration first (the ones with 5 will come first, with 10 second) and then as a second order option it will sort ones with duration = 5 by date in descending order.
Of course this could be more elegant, but meets OPs A/C and does the job.


Q: Javascript : Problem while passing parameter to a function I am passing a parameter to a javascript function from jsp.
  <a href="javascript:void(0)" title="Update"
   onclick="fnUpdate(<s:property value='roleTypeUid'/>);">

Now the roleTypeUid is a String with space in between (eg. System Admin) . So it is not working . If I replace the attribute with a no-space string , it gets passed fine.
Am I missing something ?

A: Try like this:
<a href="javascript:void(0)"
   title="Update"
   onclick="fnUpdate('<s:property value='roleTypeUid'/>');">

A: The called function within onclick has to be a string, you can't reference variables directly in it.
onclick="fnUpdate(\"<s:property value='roleTypeUid'/>\");"

That string is evalled onclick and thus becomes a function. That's why it may be better to add handlers unobtrusive


Q: $match aggregation is giving me None (in terms of Python) If ISO date is not present in query it will give null output $match  aggregation is giving me None (in terms of Python) even though I have verified it multiple time entries are present in DB .
In Python pymongo is not recognizing the ISO while I write inside the cursor = {}
making ISO as string and concatenating it with the time also doesn't work it gives the empty list .
same case with all operator gte or lte .
db.cityhistory.find({"updateTime": ISODate("2018-04-20T13:27:39.021+0000"), "countries.city": {"$exists": true}}, {"countries.city": 1})


Q: Nano (pico) editor window resize I am still not sure what I have done but I was testing some button combinations when I was in nano editor and all of a sudden the contents of the window started not to adjust themselves when I resized the terminal window and everything becomes a huge mess. It is an ssh connection to an ubuntu machine and version is GNU nano 2.2.2. Below is an example of what happens when I resize from fullscreen to something smaller. This happens only for nano editor. Everything else works fine. Anyone has an idea ?