text:
Q: Calling a Stored Procedure Using Oracle SQL Developer I am not able to set the server output to ON, while running the Java code. But I am able to connect to Oracle SQL database.
Getting below error:

****java.lang.NullPointerException DB Connected successfully java.sql.SQLSyntaxErrorException: ORA-00922: missing or invalid
  option****

Please suggest me a solution.
Code:
ResultSet rs= DS_DB.getResultSet("set serveroutput on");
DS_DB.connectDatabase();

String command = "{call sfmd.getNativeIdsForXID('EDDAC')}";
CallableStatement cstmt = connection.prepareCall(command);
cstmt.execute();
System.out.println("Cstmt :"+command);'

Thanks

A: It's a little unclear what your trying to do here.
If your looking for the result set, Oracle doesn't return result sets, you need to define one of your parameters as an output parameter of type SYS_REFCURSOR.
String command = "{call sfmd.getNativeIdsForXID(?,?)}";
CallableStatement cstmt = connection.prepareCall(command);
cstmt.registerOutParameter(1, ORACLE_CURSOR_TYPE);
cstmt.setObject(2, 'EDDAC');
cstmt.execute();

ResultSet rs = (ResultSet) cstmt.getObject(1);

In your Stored Procedure, define the output parameter
CREATE OR REPLACE PROCEDURE "getNativeIdsForXID" (
    NativeIdsCursor OUT SYS_REFCURSOR,
    P_XID VARCHAR(20)) IS

  open NativeIdsCursor for
  SELECT ID from SomeTable where XID = P_XID;

END "getNativeIdsForXID";

You can also get output if you use the dbms_output package in your stored procedure.
Here's a couple of utilities to do that.  You enable the dbms output, then execute your procedure like you normally would, then you can print the output afterward.
    public static void enableDBMSOutput(DBConnection conn, int buffer_size) {

        try {

            String SQLString = null;

            if (buffer_size > 0)
                SQLString = "sys.dbms_output.enable(?)";
            else
                //SQLString = "{call sys.dbms_output.enable(buffer_size => NULL) }"; // Unlimited
                SQLString = "sys.dbms_output.enable(buffer_size => NULL)"; // Unlimited

            CallableStatement stmt = conn.getCallableStatement(true, SQLString);

            if (buffer_size > 0)
                stmt.setInt(1,buffer_size);

            stmt.execute();

            System.out.println("DBMS_OUTPUT has been Enabled!");

        } catch (SQLException e) {
            System.out.println("Problem occurred enabling dbms_output: " + e.toString());
        }
    }

    public static void disableDBMSOutput(DBConnection conn) {

        try {

            String SQLString = "sys.dbms_output.disable()";

            CallableStatement stmt = conn.getCallableStatement(true, SQLString);

            stmt.execute();

            System.out.println("DBMS_OUTPUT has been Disabled!");

        } catch (SQLException e) {
            System.out.println("Problem occurred disabling dbms_output: " + e.toString());
        }
    }

    public static void printDBMSOutput(DBConnection conn) {

        try {
            String SQLString = "sys.dbms_output.get_line(?,?)";

            CallableStatement stmt = conn.getCallableStatement(true, SQLString);

            stmt.registerOutParameter(1,java.sql.Types.VARCHAR);
            stmt.registerOutParameter(2,java.sql.Types.NUMERIC);

            int status = 0;
            String output = null;

            do {
                stmt.execute();
                output = stmt.getString(1);
                status = stmt.getInt(2);

                if (null != output)
                    System.out.println("dbms_output: " + output);

            } while (status == 0);

        } catch (Exception e) {
            System.out.println("Problem occurred during print_dbms_output: " + e.toString());
        }
    }

    public static String [] getDBMSOutput(DBConnection conn) {

        try {
            String SQLString = "{call sys.dbms_output.get_line(?,?)}";

            CallableStatement stmt = conn.getCallableStatement(true, SQLString);

            stmt.registerOutParameter(1,java.sql.Types.VARCHAR);
            stmt.registerOutParameter(2,java.sql.Types.NUMERIC);

            int status = 0;
            String output = null;
            ArrayList <String> dbmsOutput = new ArrayList<String>();
            do {
                stmt.execute();
                output = stmt.getString(1);
                status = stmt.getInt(2);

                if (null != output)
                    dbmsOutput.add(output);

            } while (status == 0);

            return (String [])dbmsOutput.toArray();

        } catch (Exception e) {
            System.out.println("Problem occurred during print_dbms_output: " + e.toString());
            return null;
        }
    }
}

public CallableStatement getCallableStatement(boolean isProcedure, String sqlString){
    try {
        if (isProcedure) {
            String query = "{ call " + sqlString + " }";

            return dbConn.prepareCall(query);
        } else
            return dbConn.prepareCall(sqlString);

    } catch (SQLException e) {
        e.printStackTrace();
        return null;
    }
}

A: set serveroutput on is a SQL*plus command and not available in JDBC driver. JDBC driver is not dbms_output aware. Tom Kyte's site has a nice explanation and possible solution. https://asktom.oracle.com/pls/asktom/f?p=100:11:0::::P11_QUESTION_ID:45027262935845


text:
Q: Hive float data type with unix timestamp I am using hive external table with float data type (by Mistake) to store Unix epoch timestsamp.
When I issue where clause on hive external table it returns some odd results. As an example.
select event_time from tbl_name where event_time=1478649561 limit 10

Output :

1478649600

Could anyone help me to understand what's wrong in this ?

A: This is not so much a Hive issue as it is a general issue of floating-point precision.  You are seeing the effect of 1478649561 (an integral type) being approximated in floating-point representation to fit into the 32-bit Java float type.
To see this in a simpler form, outside the context of Hive, here is a sample Scala REPL session that converts 1478649561 to a Java Float and prints the result.
scala> printf("%f", new java.lang.Float(1478649561))
1478649600.000000

As you can see, this was approximated to 1478649600.  There is no way to avoid this if the data is stored as a 32-bit floating point number.
I highly suggest storing the data in an integral type or the DATE type to avoid this problem.  The Apache Hive documentation on Hive Data Types discusses the different data types in detail.  If you're interested in digging into the full details of floating-point precision, the Wikipedia Floating point article is a decent starting point.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Get PropertyType.Name in reflection from Nullable type I  want use reflection for get properties type.
this is my code
var properties = type.GetProperties();
foreach (var propertyInfo in properties)
{
     model.ModelProperties.Add(
                               new KeyValuePair<Type, string>
                                               (propertyInfo.PropertyType.Name,
                                                propertyInfo.Name)
                              );
}

this code propertyInfo.PropertyType.Name is ok but if my property type is Nullable i get this Nullable'1 string and if write FullName if get this stirng System.Nullable1[[System.DateTime, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]

A: Change your code to look for nullable type, in that case take PropertyType as the first generic argument:
var propertyType = propertyInfo.PropertyType;

if (propertyType.IsGenericType &&
        propertyType.GetGenericTypeDefinition() == typeof(Nullable<>))
    {
      propertyType = propertyType.GetGenericArguments()[0];
    }

model.ModelProperties.Add(new KeyValuePair<Type, string>
                        (propertyType.Name,propertyInfo.Name));

A: This is an old question, but I ran into this as well.  I like @Igoy's answer, but it doesn't work if the type is an array of a nullable type.  This is my extension method to handle any combination of nullable/generic and array.  Hopefully it will be useful to someone with the same question.
public static string GetDisplayName(this Type t)
{
    if(t.IsGenericType && t.GetGenericTypeDefinition() == typeof(Nullable<>))
        return string.Format("{0}?", GetDisplayName(t.GetGenericArguments()[0]));
    if(t.IsGenericType)
        return string.Format("{0}<{1}>",
                             t.Name.Remove(t.Name.IndexOf('`')),
                             string.Join(",",t.GetGenericArguments().Select(at => at.GetDisplayName())));
    if(t.IsArray)
        return string.Format("{0}[{1}]",
                             GetDisplayName(t.GetElementType()),
                             new string(',', t.GetArrayRank()-1));
    return t.Name;
}

This will handle cases as complicated as this:
typeof(Dictionary<int[,,],bool?[][]>).GetDisplayName()

Returns:
Dictionary<Int32[,,],Boolean?[][]>


text:
Q: $E=mc^2$: Why does the speed of light constant affect the Energy or Mass of an object? So this is really just for fun. I often talk to my friend who studied some Physics degree (or similar) and he simply cannot accept the possibility it could be wrong in any way. To the point where he gets angry if I try to challenge it.
but if E=mc2, to me this implies that the speed of light itself is somehow controlling the amount of matter an object has. It seems mindboggling to me that it's a coincidence in nature, like what does the speed of light have to do with massive something is.
Also , is it 100% proven that in ALL circumstances/scenarios mass and energy values are directly linked, or have there been exceptions.
Finally (and off topic) that double slit test seems to me as prove that we don't understand even electrons behaviour fully (the conclusion that it will behave differently when it is being observed to when not observed doesn't sit well with me LOL!)
I'd love to hear any facts, opinions or discussion here. And of course would love to learn more and understand why this formula (and in fact the double slit thing) is so widely accepted by all experts.
(EDIT: THANKS FOR ALL COMMENTS AND ANSWERS)

A: The constant $c$ is largely arbitrary, mostly due to human definitions of things like the meter and the second (though we defined the speed of light to be an exact value in the 1980s, and the meter & second are now derived from it). In many cases, physicists use units in which $c=1$, so then you have that
$$E=m$$
which should indicate that $c$ isn't controlling anything here, it's really just a value used to convert a mass-quantity into an energy-quantity.
You may want to look at other related questions and answers on the subject:

*

*What is the role of the speed of light in mass-energy equivalency?

*How does rest mass become energy?

*Einstein's mass energy equivalence

*How does matter transform into energy and vice versa?
And probably many others.

A: When dealing with anything to do with the speed of light, I find it helpful to think of c not as a speed, but as a universal speed limit. So you can think of e=mc^2 because e=m(c+1)^2 is just impossible. C is just the highest number possible in the world of speed and therefore energy.   It's just a way of thinking, but I hope it helps the understanding.

A: I like your question, you are taking from a different point of view. The equation is just a mathematical consequence of the postulates of Special Relativity, you can find it's derivation in University Physics by Young.
Actually the same result was found by Dirac through the postulates of Quantum Mechanics and again it was a mathematical consequence but he got a plus and minus sign in his equation.
Your thinking is very keen and sharp but not needed in physics, Physics is about being humble to it and it's laws.
 Hope it helps

A: I like the E =mc^2 part of the question because I asked this in my school and my teacher was extremely pleased with me. So I will now try to answer the question.
Honestly though the double slit experiment has nothing to with it. Everyone should have a look at the single electron diffraction video. For example https://youtu.be/jvO0P5-SMxk.  And I mean EVERYONE. The electron has simply a probability for falling at any point on the screen. Initially there are a few random pounts but as the numbers increase the inteference becomes obvious. There is no doubt whatsoever. Why nature behaves in this absurd ( to human minds) way  is simply unknown.  But it does and like Feynman I am delighted with it.
Now for the E=mc^2 issue.  The speed of light is " not controlling the amount of matter an object has ". That formula determines how much energy is created when a mass m is converted into energy. This for example is happening in the sun. Once again experiments confirm it with no scope for any doubt
The formula itself emerges because Einstein asked a question. Light propagates as a wave. But Maxwell's equations don't change if the source is moving. So the velocity shouldn't change with the velocity of the source. This was subsequently directly verified. One of the consequences of this is the formula.
And before you ask, this is true in quantum mechanics too. But it becomes necessary to do a lot of maths.
NOTE FOR SERIOUS PHYSICISTS.
I found through experience that this approach works better when explaining to non physicists rather than start a mathematical derivation from Michelson Morley experiment.
I have written a monograph "experimenting with the quantum world" published by vigyan prasar for such an audience. It can be down loaded  from archives.org


text:
Q: TSlint lists Problems in VSCode for Git Diff files My Problem
When I compare two versions of a file with VS Code and the built-in Git features TSLint does not ignore the revisions but marks the errors. Since the diff files are located in AppData\Local\Temp on Windows the path checking fails and other things as well.
However, most annoying is not the red line in the file view but that they are listed in the Problem Panel and I get like 20+ problems just because opening one file revision and they won't go away until I reopen VS Code, so they add up during time.
That makes the panel useless for me, since I see lots of pseudo-problems, I won't notice an actual problem.
What I tried
I tried in my settings.json
"tslint.exclude": ["**/AppData/**"]

but that didn't work out.
Any suggestions would be much appreciated.

A: Well, it appears that this is an issue with the GitLens extension which will be fixed with the upcoming version:

this issue has been fixed in the GitLens 9 release which will be coming very soon.
~ eamodio

(Source: https://github.com/eamodio/vscode-gitlens/issues/430#issuecomment-440731347)


text:
Q: Converting string into Date() in JavaScript How do I convert this timestamp from php into a javascript Date() object?
This is how I grab the time:
$timestart = time();
and I parse this to a javascript function and I want to convert it into a JavaScript date object.
help, all this date stuff confuses me quite a bit.
thanks,

A: If val contains your PHP value which is

the current time measured in the number of seconds since the Unix Epoch

then you just need this:
var timestart = new Date(val * 1000);

JavaScript uses the same base time as UNIX systems (midnight on 01/01/1970) but measured in milliseconds rather than seconds.

A: Solution here :
Convert a Unix timestamp to time in JavaScript

A: Substring the parts of the timestamp you need to create the Date. Then initialise like so,
var d = new Date(year, month, date);

This is a cross browser implementation.


text:
Q: What's the limit of Zatanna's magic? Is there a limit to Zatanna's magic? It seems that the sentence spoken by Zatanna in reverse pronounce order will come to true. This implies that Zatanna is extremely powerful, or, nearly omnipotent.
However, obviously, Zatanna didn't solve all the problems in DC universe by saying "no more villains". What's the limit of Zatanna's magic? For example, if Zatanna said "move the Mars out of the solar system", will it be realized?

A: I don't think there is a concrete answer to this question. Any limits she does have is largely dependent on the writer, and likely to change from writer to writer.
The only limit I've ever seen stated is in Young Justice where she states she's less powerful than Doctor Fate, but has more flexibility with her spells since Fate is an agent of pure order and she's human, which allows her to have some spell effects that Fate does not.
Her main limit is that she must speak the words of her spell, so anything that can silence her will render her spell-casting useless.


text:
Q: Difference in version of setuptools with virtualenv Here's my Windows setup

*

*c:\Python27 : installed via official msi

*setuptools : installed via python setup.py install (from: setuptools-1.1.5.tar.gz)

*pip               : installed via python get-pip.py             (from get-pip.py)

*virtualenv : installed via python setup.py install (from : virtualenv-1.10.1.tar.gz)

*Create virtualenv using : virtualenv --no-site-packages myenv
Now, setuptools shows a different version in the following 2 cases :

*

*Open a shell & run pip list:
pip (1.4.1)setuptools (1.1.5)virtualenv (1.10.1)

*activate virtualenv & run pip list
pip (1.4.1)
setuptools (0.9.8)
Why is setuptool showing version 0.9.8 in virtualenv although I installed version 1.1.5 as shown in the global path?
Update:
I tried @Rod's suggestion and it worked. But my setup broke. I wish the caveat was mentioned in the answer. I'm adding this here so that others don't end up wasting hours like I did. If I use the option --no-setuptools while creating virtualenv, after activating virtualenv, pip installs the packages globally.
My project had some dependencies that were installed via pip install. They stopped working (i.e. MySQLdb adapter). When I created another virtualenv without the --no-setuptools option, it started working.

A:
Why is setuptool showing version 0.9.8 in virtualenv although I
  installed version 1.1.5 as shown in the global path?

The different setuptools version seen is due to virtualenv bundling a version of setuptools within its archive (version 1.10.1 is bundled with setuptools 0.9.8). The local setuptools is installed from the archive to avoid accessing the network.
Having a different version of setuptools in your virtualenv should not be a problem.
Changing the version
If you must change the version, currently there is no way to force downloading another version setuptools other than unpacking the tar file and replacing the setuptools archive, in virtualenv-1.10.1\virtualenv_support with a newer version.
Eventually you will be able to specify a directory containing another version of setuptools to use, with the --extra-search-dir option, but the feature currently does not work.
Note: Virtualenv will install its own version of setuptools if you do not specify --no-setuptools when you create your virtualenv. Obviously, using the option --no-setuptools will not install setuptools nor pip. It will most likely break the encapsulation provided by virtualenv (as the OP noted).


text:
Q: Función retorna un válido del arreglo menos Tengo que pasar datos de libros (stLibroLista) desde un Árbol hacia un Arreglo de Listas.
La función agregar sirve para cuando no se encuentre cierto autor en el ADL: se lo agrega y se lo da de alta. Funciones auxiliares como crearNodoLista, buscarPosEnArreglo, etc. funcionan correctamente.
El problema llega al usar arbolToADL, que, en caso de que yo cargara 3 autores y 3 libros en el árbol, debería pasar 3 autores y 1 libro por celda (en su respectiva lista), devolviéndome 3 válidos. Pero me retorna 2, y no logro encontrar el error.
int agregar(celda A[], char nombrePersona[], int v)
{
    strcpy(A[v].nombrePersona, nombrePersona);
    A[v].listaLibros = inicLista();
    v++;
    return v;
}

int alta(celda A[], char nombrePersona[], stLibroLista libro, int v)
{
    nodoListaLibro*aux = crearNodoLista(libro);
    int pos = buscarPosEnArreglo(A, nombrePersona, v);

    if(pos == -1)
    {
        v = agregar(A,nombrePersona,v);
        pos = v-1;
    }

    A[pos].listaLibros = insertarNodoEnLista(A[pos].listaLibros,aux);
    return v;
}

int arbolToADL (nodoArbol*arbol, celda A[], int dim)
{
    int v = 0;
    stLibroLista datos;
    char nombrePersona[20];

    if(arbol)
    {
        strcpy(nombrePersona, arbol->dato.nombrePersona);
        strcpy(datos.nombreLibro, arbol->dato.nombreLibro);
        strcpy(datos.genero, arbol->dato.genero);
        datos.cantPaginas = arbol->dato.cantPaginas;
        datos.puntaje = arbol->dato.puntaje;

        v = arbolToADL(arbol->izq, A, dim);
        v = arbolToADL(arbol->der, A, dim);
        v = alta(A, nombrePersona, datos, v);
    }

    return v;
}

Código completo: aquí


text:
Q: How can we embed GoodData platform dashboard onto GoodDataUI On the Official GoodData website some code is given for the integration, but I am unable to understand how to use it.
Link for the Dashboard integration code
In my case QuantitativeAnalysis is the dashboard I created in GoodData platform and now I want to view that dashboard in GoodData UI.
Picture of my code for embedding dashboard


text:
Q: Writing unit tests for various os/system level checks I have a few functions for performing actions in python, and I am debating whether or not it makes sense to write unit tests for these.
There is one function that resolves a host using the socket module. I don't think it makes sense to write a test for the socket module itself, but seems like it may make sense to write a functional test to see if DNS is working.
I have another function that opens a file and puts the contents into a list.
Does anyone have any guidance or links on performing unit tests/functional tests for items like this? Most of what I have read pertains to application level testing only.
Thank you in advance.

A: First of all, if you don't have tests at all, better start with high-level end-to-end functional tests and end with unit tests gathering coverage statistics on every new test you write.
While writing a test to a function which uses system or network libraries, you usually want to isolate your test, to make it independent and straight as much as possible by mocking out system and network calls (see Mock library).
By using mock library you can and should test how does your application/function respond to situations where there is a socket or system error.
Also see:

*

*python unittest howto

*How to Mock an HTTP request in a unit testing scenario in Python

*An Introduction to Mocking in Python
Hope that helps.


text:
Q: How to make floating menu which stays in place until you scroll over it I want to make a menu that is fixed. But I want it only to be fixed if i've scrolled past it.
Actually I want it just like the "how to .." menu on the question ask part of stackoverflow. https://stackoverflow.com/questions/ask
I thought you need jquery to do such things, but i really don't know much about jquery.
I use this code for the menu and i want that to  float. So the whole sidebar div needs to float.:

Sites

first li

second li

third li

Sites

first li

second li

third li

I know how I can let it float to the top of the page, but i want it to float in a wrapper.
I hope you guys can help me.
EDIT
now i have the floating menu with this code:

But there is a really annoying bounce effect when I scroll down. Is there a way to remove that effect?

A: In short: You'll bind to the scroll event of the window and check whether the current scrollTop (distance in pixel from the top of the page to the pixel currently at the top of your viewport) is larger than the distance from the top of the page to the top of your  sidebar.
If this is given you'll set the difference as marginTop to make the sidebar stay in the visible area.
See at http://css-tricks.com/scrollfollow-sidebar/ for an example and further information.


text:
Q: Oracle Table millions of row, pull and save into file I have oracle table that holds more than 30 million records, I need to pull all that data into file and store it.. Can anyone suggest me what will be easiest way to do that and what kind of file do I have to use to store all that data. If there is a way I can put data into multiple files that will work too.. You can tell me manual or programatical method. Thank you

A: Starting with Oracle 10g you can create a new table with ORGANIZATION EXTERNAL and INSERT records from the original table into it. See this example from the Oracle 10gR2 documentation.

A: One of the easiest formats to store data in is comma seperated value (.csv). You can define your delimiter to be any character (comma is a default) as long as you know the delimiter when you are parsing it.  (For instance, the ~ character would be a good decision).  Usually this format can easily be opened in a spreadsheet program like Excel.  It can also be easily parsed to be re-inserted into a database of your choosing.
To export from oracle, you can do something like:
spool backup.csv;
select column1||','||column2||','|| ... from table;
spool off;

After exporting, here is a resource for working with csv files in perl:
http://perlmeme.org/tutorials/parsing_csv.html
Apache commons has a great library for java:
http://commons.apache.org/sandbox/csv/apidocs/org/apache/commons/csv/CSVParser.html

A: Ask Tom has an answer http://asktom.oracle.com/pls/asktom/f?p=100:11:0::::p11_question_id:88212348059
Also, you could do it in SQL*Plus by doing a select with spool on (from a shell script)
sqlplus /nolog <<EOF
conn /as sysdba
set pagesize 0 heading off feedback off verify off echo off trimspool on
spool test.log
select 'dsmc inc "'||file_name||'">>hot_WISDOM_$BCKNAME.log' from dba_data_files
 where rownum<5;
spool off;
exit
EOF

More info on the spool stuff at http://asktom.oracle.com/pls/asktom/f?p=100:11:0::::P11_QUESTION_ID:25323432223677
That page is where I found that snippet above.
You will want to replace the connection details with your username / pw.


text:
Q: Virtualising a VERY legacy app Looking for a bit of help on this one. I have a customer who has a VERY old MS DOS application that is written in some 3GL language of unknown origin. The original software vendor went out of business back in 1996 or so and no support.
I need to virtualise this application as they neither want nor have the money for a more modern solution.
Virtualising the machine is easy enough. However this app spits out HP PCL codes for printing and will only work with HP Laserjets.
To make the system work I need to be able to print to non PCL printers (ie a Samsung laser printer) and potentially, print to PDF.
Any ideas on how to do this are greatly appreciated as this is really a job stopper. Is there some sort of shim available or am I barking up the wrong tree?

A: I would suggest using printers that support HP's PCL codes or HP PCL emulation. It's easier to change a printer/device than rewrite a legacy application.
I work with warehousing/production unattended printing from a legacy application. I have to validate the printing solutions, so it makes sense to have a limited number of devices you need to support.
For the PDF issue, in the past, I've needed to use a commercial PCL-to-PDF add-on. With Linux, we've been able to handle this with open-source software.

A: You are trying to solve the wrong problem.
You need to go looking for printers that have built in PCL support without the need for a windows driver.
The easiest way to test is to attempt using the HP4 or 5 or 6 PCL driver and either you'll get a nice looking test page or scrambled eggs.


text:
Q: Arch Linux Install Scripts on MacBook Pro Retina I've spent many hours trying to configure arch linux on my macbook pro. I get stuck at "Loading initial ram state" when I reboot after install.
Here is the script(s), I've created chronicling my steps. Is there anything obviously wrong that I am doing?
Thanks ahead of time.
cgdisk /dev/sda #(setup partitions as below, sda1-3 not shown)
#partitions: (sda4 == 128MB Hfs+, sda5 == 256MB Linux (boot), sda6 == 30GB Linux (root), sda7 == 70GB #Linux Home)
#first script

mkfs.ext2 /dev/sda5
mkfs.ext4 /dev/sda6
mkfs.ext4 /dev/sda7
mount /dev/sda6 /mnt
mkdir /mnt/boot && mount /dev/sda5 /mnt/boot
mkdir /mnt/home && mount /dev/sda7 /mnt/home
pacstrap /mnt base base-devel
genfstab -p /mnt >> /mnt/etc/fstab

arch-chroot /mnt /bin/bash

#second script
#install wifi (dmesg | grep firmware still says no firmware tho...)
pacman -S wget b43-fwcutter
wget https://aur.archlinux.org/packages/b4/b43-firmware/b43-firmware.tar.gz
tar -zxf b43-firmware.tar.gz
cd b43-firmware
makepkg -si --asroot #kosher?
rmmod b43 && modprobe b43
echo arch > /etc/hostname
ln -s /usr/share/zoneinfo/US/Central /etc/localtime
hwclock --systohc --utc
useradd -m -g users -G wheel -s /bin/bash dmj && passwd dmj
sudo pacman -S sudo
nano /etc/sudoers #comment out wheel portion
sudo nano /etc/locale.gen #pick locale
locale-gen
echo LANG=en_US.UTF-8 > /etc/locale.conf
export LANG=en_US.UTF-8
mkinitcpio -p linux #someone said i need "ahci" in modules?
#make boot loader, copy to usb
pacman -S grub-efi-x86_64
grub-mkconfig -o boot/grub/grub.cfg
grub-mkstandalone -o boot.efi -d usr/lib/grub/x86_64-efi -O x86_64-efi -C xz boot/grub/grub.cfg
mkdir /mnt/usbdisk && mount /dev/sdc1 /mnt/usbdisk
cp boot.efi /mnt/usbdisk/
umount /mnt/usbdisk/
sudo pacman -S dialog wpa_supplicant iw

exit
umount /mnt/home
umount /mnt/root
umount /mnt/
sudo reboot


text:
Q: Oracle Query to Find Records If Count >= 2 and unique in column +----------+---------+------------+-----------+
| MEMRECNO | RECSTAT | IDSRCRECNO | IDNUMBER  |
+----------+---------+------------+-----------+
|   556787 | D       |          5 | 956645789 |
|   123456 | A       |          5 | 956645789 |
|   546578 | A       |          5 | 462454322 |
|   262441 | A       |          4 | 462454322 |
|   657855 | D       |          3 | 462454322 |
|   746877 | A       |          5 | 654988844 |
|   989455 | A       |          2 | 654988844 |
|   444863 | A       |          1 | 654988844 |
+----------+---------+------------+-----------+

I am attempting to write a query to select records where two or more sources (IDSRCRECNO) have same IDNUMBER. I have started the query with something along the lines of:
WHERE idnumber IN (SELECT idnumber from table GROUP by idnumber HAVING count(idnumber) >= 2
Expected Results:

MEMRECNO 546578 and 262441 included in results. This is because both records are active, the IDNUMBER's are identical and the IDSRCRECNO is different.
MEMRECNO 556787 and 123456 would not be included because even though the IDNUMBERS match, one of the records/recstat is Deleted (D).
Memrecno 262441 and 657855 would not be included because even though the IDNUMBERS match and IDSRCRECNO is different, one of the records/recstat is Deleted (D).
Memrecno 262441 and 657855 would not be included because even though the IDNUMBERS match and IDSRCRECNO is different, one of the records/recstat is Deleted (D).
Memrecno 746877, 989455, 444863 would be included because all three records are active, IDSRCRECNO is different and IDNUMBERs match.
Thanks in advance!

A: Is that what are you looking for?
I just added a WHERE clause to your inner query:
SELECT idnumber
WHERE recstat <> 'D'
FROM table GROUP by idnumber
HAVING count(idnumber) >= 2

A: I would do this like:
with data as (
    select 556787 memrecno, 'D' recstat, 5 idsrcrecno, 956645789 idnumber from dual union all
    select 123456 memrecno, 'A' recstat, 5 idsrcrecno, 956645789 idnumber from dual union all
    select 546578 memrecno, 'A' recstat, 5 idsrcrecno, 462454322 idnumber from dual union all
    select 262441 memrecno, 'A' recstat, 4 idsrcrecno, 462454322 idnumber from dual union all
    select 657855 memrecno, 'D' recstat, 3 idsrcrecno, 462454322 idnumber from dual union all
    select 746877 memrecno, 'A' recstat, 5 idsrcrecno, 654988844 idnumber from dual union all
    select 989455 memrecno, 'A' recstat, 2 idsrcrecno, 654988844 idnumber from dual union all
    select 444863 memrecno, 'A' recstat, 1 idsrcrecno, 654988844 idnumber from dual
)
select *
from (
    select memrecno, recstat, idsrcrecno, idnumber, count(distinct idsrcrecno) over (partition by idnumber) rec_cnt
    from data
    where recstat = 'A'
)
where rec_cnt > 1;

Which returns:
  MEMRECNO RECSTAT IDSRCRECNO   IDNUMBER    REC_CNT
---------- ------- ---------- ---------- ----------
    262441 A                4  462454322          2
    546578 A                5  462454322          2
    444863 A                1  654988844          3
    989455 A                2  654988844          3
    746877 A                5  654988844          3

This assumes you only want to see Active records.  The query would have to be changed if for example MEMRECNO = 444863 was not Active, but you still wanted it to show up (since there would still be 2 records with the same IDNUMBER and different IDSRCRECNO).  Just comment if that is what you are looking for and I will update this accordingly.

A: You can also achieve this without a sort, using a query that would likely use a hash semijoin for large data quantities:
select *
from   my_table t1
where  recstat = 'A' and
       exists (
         select null
         from   my_table t2
         where  t2.IDNUMBER =  t1.IDNUMBER and
                t2.MEMRECNO != t1.MEMRECNO and
                t2.RECSTAT  =  'A')

A: I think your WHERE clause should be
WHERE idnumber in ( SELECT idnumber
                    FROM ( SELECT count(*), idnumber
                           FROM  table
                           GROUP by idnumber
                           HAVING count(*) >= 2
                         ) temp
                  )


text:
Q: Why would you write your own Random Number Generator? I've read a lot of guides on how to write your own random number generator, so I'm interested in the reasons why you would write your own since most languages already provide functions for generating random numbers:
Like C++
    srand(time(NULL));
    rand();

C#
    Random rand = new Random();
    rand.Next(100);

and Java
    Random rand = new Random();
    rand.nextInt(0, 100);

I'm mainly looking for advantages to using your own.

A: If you've done your research and found out that the default generator is horrible (as is the case in C or Excel, or with IBM's infamous randu), you might be motivated to download or implement a better generator.  However, unless you have a very deep understanding of probability, statistics, and numerical methods, you should under no circumstances try to create your own. Even such luminaries as John von Neumann have screwed up royally on this.
Another reason might be to get cross-platform reproducibility of results.

A: Never, ever, roll-your-own cryptography or random number generation unless you are very comfortable with the higher math involved. Here's a short test: if you understand probability distributions, linear feedback shift registers, the incomplete gamma function, and the Chinese remainder theorem, you might be qualified to roll your own.
Otherwise, use a generator provided by someone who does understand these things. The one built into your language might not be. So look for add-on libraries with good reputations.

A: One of the possible reasons is right in your question..:

most languages already provide functions

They do but they are more often than not incompatible.
I had to write one once because the (lightweight) encryption I wrote was using a different language (Powerscript) than the decryption (VB) and their Random generators were not compatible.

A: Sometimes, even though you want a sequence of random numbers, you might want the same exact sequence of random numbers (for debugging or other purposes).
In a portable program, designed to be run on different systems with different libraries, and possibly different random number generators, accomplishing the goal stated above might not be possible.
If you instead implement your own, you would have control over this, and could make it behave the same on a multitude of systems, rather than relying on the provided implementation.
Also, as mentioned in a comment, a provided implementation may be bugged somehow.

A: Stock random number generators are usually pseudo-random number generators in most languages.
A pseudo-random number generator starts with some state, and uses it to produce an unpredictable sequence of seemingly uniform numbers.
There are many different pseudo-random number generators that have been researched.  They have different advantages and disadvantages -- some are more random, some have longer periods, some are cryptographically strong and difficult to work out the seed from previous samples, some are fast, etc.
The one picked for a given language is going to be some compromise of the above features.  In some cases, the one picked will be known to be a poor one, but for legacy reasons is left alone as the "stock" random number generator (rand() is an example of a poor random number generator).  If you need different features than your given language random number generator picked as important, writing your own (or finding one) is about the only way to get it.
In some languages, the random number generator (or the distribution generator) is under specified, or subject to change between revisions of the language.  If you need stability of your random number generator (say, you are using it to procedurally generate a game universe from a small seed -- see the classic game star control 2), writing it yourself may be required, even if it is a clone of the standard one on your system.
If you need your random number generator to be stable from one language to another, each language is going to have made different choices.
In C++11, the old rand() was mostly deprecated, and a new library with 3 engines, 10 predefined generators, 3 engine adapters, 21 distributions, and 1 non-pseudo random number generator (random_device) was added.  The distributions are under-specified, while the generators are not: if you need cross-compiler compatibility of results from a given seed state, you would need to write your own distributions.
Even in C++11 with that embarrassment of riches, the exact trade offs you want might not be available.  So you'd have to write your own.
Note that C++11's set of generators was mostly written prior to C++11 being in existence.  It was written because rand() was considered useless, and people wrote libraries with their own random number generators.  Best practices where gathered, and formalized in that version of C++.  So another reason to learn how to write them is that your language of choice will need to be improved, and programmers are the ones who need to do it.
For an in-depth discussion of pseudo-random number generator properties, wikipedia has an acceptable place to start.  Here it mentions that Java's JCG is a low quality one.

A: The generators you list are all PRNGs. These particular PRNGs are not suitable for gaming, scientific, or cryptographic applications.


text:
Q: How to initialize multidimensional associative array with empty values I want to create and initialize a multidimensional array with known possible keys for the second dimension but no values.
This array will store event_ids (populated dynamically) and for each event_id an array having exactly four different counts (also filled dynamically).
Structure I want to create
Array
(
    [0] => Array  =================> This index will be the event_id
        (
            [invitation_not_sent_count] =>
            [no_response_yet_count] =>
            [will_not_attend_count] =>
            [will_attend_count] =>
        )
)

What I did so far?
$DataArray = array();
$DataArray[] = array('invitation_not_sent_count' => '',
                                        'no_response_yet_count' => '',
                                        'will_not_attend_count' => '',
                                        'will_attend_count' => '');

And inside the loop I am populating data dynamically like:
$DataArray[$result->getId()]['no_response_yet_count'] = $NRCount;

What I get is:
Array
(
[0] => Array
    (
        [invitation_not_sent_count] =>
        [no_response_yet_count] =>
        [will_not_attend_count] =>
        [will_attend_count] =>
    )

[18569] => Array
    (
        [no_response_yet_count] => 2
    )

[18571] => Array
    (
        [no_response_yet_count] => 1
    )

)
What I want is that if a value is not available in the iteration, its entry should be empty as defined at initialization time. So if all other counts are empty in the data except no_response_yet_count, the array should be:
Expected Output
Array
(
[18569] => Array
    (
        [invitation_not_sent_count] =>
        [no_response_yet_count] => 2
        [will_not_attend_count] =>
        [will_attend_count] =>
    )

[18571] => Array
    (
        [invitation_not_sent_count] =>
        [no_response_yet_count] => 1
        [will_not_attend_count] =>
        [will_attend_count] =>
    )

)

A: I usually resort to a mapping function at that point:
function pre_map(&$row) {
    $row = array
    (
        'invitation_not_sent_count' => '',
        'no_response_yet_count' => '',
        'will_not_attend_count' => '',
        'will_attend_count' => ''
    );
}

Then in the while/for loops:
{
    $id = $result->getId();
    if (!isset($DataArray[$id])) { pre_map($DataArray[$id]); }
    $DataArray[$id]['no_response_yet_count'] = $NRCount;
}

The if (!isset($DataArray[$id])) is to make sure it doesn't wipe out the same index row, in case you happen to re-loop on the same ID. Thus, it will only map it once, then never again in the loop.
There are some other one-line shortcuts like maybe even using array_map(), but I was showing the long version, for full flexibility just in case.


text:
Q: pandas to_csv argument float_format to a percentage I am trying to output a pandas dataframe but I want it to output the floats as a percentage. I've done a fair amount of searching on this, and I can make them display as floats in the output exactly like I want using
pd.options.display.float_format = '{:,.2%}'.format

but what I want is to do the exact same thing except when I export to a .csv using the .to_csv method.
Sample code:
df2 = pd.DataFrame(data = {'Index': ['One', 'Two'], 'col1': [.1, .2], 'col2': [.3, .4], 'col3': [1, 7]})
df2.set_index('Index')

df:
    col1    col2    col3
Index
One 0.1     0.3     1
Two 0.2     0.4     7

col1 and col2 are float64 and col3 is an integer
I want to use the following (or something like it of course):
dfs.to_csv("filelocation and name.csv", float_format = '{:.2%}'.format)

to output to a .csv that would look like:
    col1    col2    col3
Index
One 10%     30%     1
Two 20%     40%     7

Any help would be greatly appreciated. I've hit errors from "TypeError: unsupported format string passed to numpy.ndarray._ _ format _ _" to "KeyError: '%'" and a few in between.

A: You have access to float_format to format the output in the csv file, but that is just a string, that means you can format the columns, but not operate on them. For example
with open('foo.csv', 'w') as f:
    df2.to_csv(f, index = False, header = True, float_format = '%.2f%%')

will create this output
Index,col1,col2,col3
One,0.10%,0.30%,1
Two,0.20%,0.40%,7

If you want to change the values I suggest you to update the dataframe before outputting
df2 = pandas.DataFrame(data = {'Index': ['One', 'Two'], 'col1': [.1, .2], 'col2': [.3, .4], 'col3': [1, 7]})
df2.set_index('Index')

df2['col1'] *= 100
df2['col2'] *= 100

with open('foo.csv', 'w') as f:
    df2.to_csv(f, index = False, header = True, float_format = '%.2f%%')


text:
Q: Clicking Qt SoftwareInputPanel should restore focus to Target Dialog/Widget I've created a Qt software input panel (SIP) following the example here and it works very well. Unfortunately clicking the SIP does not restore focus to either widget when both dialogs lose focus. To summarize, when I:

*

*click outside the SIP and target dialog/window, understandably, both widgets lose focus (even although both are configured to be on top of other dialogs)

*subsequently click on the SIP neither widget gains focus.

We find this behaviour a bit odd and suspect so will our users. Is there a way to restore focus to the target dialog by clicking on the SIP, when both widgets lose focus?

A: Solved. Use QApplication::setActiveWindow() like so:
void KeyboardPanel::buttonClicked( QWidget *widget )
{
    if( m_lostFocus )
    {
        QWidget* parentWidget = m_lastFocusedWidget->parentWidget();
        if( parentWidget ) QApplication::setActiveWindow( parentWidget );
    }
}


text:
Q: what is the difference between node and jspm and can node and jspm used together in a project I am new to web development using node and jspm.
Please explain the difference between node and jspm and how they can be combined used in a project.
Do we need to copy all our node dependency or node module folder to the production server?

A: JSPM is the command line tool, that works in Node. Usin JSPM you can:

*

*Configure your SystemJS config file to load all dependecies one-by-one in development

*Build all dependecies into single minified js bundle for production.

So, you do not need to copy node_modules into production, just run jspm bundle command and copy it's output to production only.


text:
Q: From an execution perspective is an interpreter the same as the JVM / or the .net Framework I've recently started two introductory level courses - one using Python, the other Java.
I've read the answers to this Question but still have difficulty understanding how each ends up with machine code and what the main differences between the two models are:

*

*Is an interpreter doing the same job as something like the JVM, just without the
byte-code?

*For python is the interpreter taking the high-level code
and translating it into machine code?

*The Java virtual machine needs to be installed on a machine for a java program to run on it - is it similar for python - if the interpreter is installed on the target machine then the python program will run?

*Is the JVM (& .net framework) effectively byte-code interpreters?

A: Various comments have pointed out several ambiguities in the question and nuances to the answer, but the simple answer is no.
The JVM and .NET Framework are Just-In-Time Compilers. They are still compilers, and do all of the work of a compiler. They take an intermediate language (bytecode), optimize it, and convert it into machine code. The only difference between jitters and traditional compilers is when they do the compilation.
Interpreters, at least in their traditional definition, never compile code. Rather, they use code that is already compiled in order to execute the instructions they are given. This makes them faster to start up (since they don't need to compile anything) but generally slower to run, since there is overhead associated with each instruction.
If you wrote some code that did the following with a bunch of "switch" or "if" statements:

*

*Read every line of a file

*For every line that says "A", write "hello" to the screen

*For every line that says "B", write "world" to the screen

*For every other line, write "error" to the screen

Then this would be a (very crude) interpreter. It would not be a compiler of any kind, because all of the parts that actually run on the machine are in your program. It's doing parsing, but skipping the compile and link steps and going directly to execution based on a look-up table.
Another way to think of it - and I caution that this is purely an analogy for beginners and not a perfectly accurate technical description - is that interpreters essentially work on a line-by-line basis, whereas jitters will compile large chunks of the bytecode or possibly even the entire bytecode at the same time.
It's also often possible to precompile bytecode without a jitter (like Microsoft's NGen), since bytecode is typically very similar (but not identical) to the machine code. Interpreted code usually remains in a high-level language all the way to execution.

A: There is a technical point of view:

*

*a compiler is a processus which transforms a view of a program into another view, lowering the level of abstraction

*a interpreter is a processus which execute a program, possibly first transforming the source in another view, but that one will not have a significantly lower level of abstraction.
There is a user point of view:

*

*a compiler just transfor the program, it won't be executed there until another step

*an interpreter will execute the program.
There is some confusion lying in the difference between the two.
A interpreter as a user see it sometimes use compilation techniques.  Upfront, compiling the source program in a intermediate representation which is of a significantly lower level of abstraction than the source before interpreting it, maybe even going down to machine level (load and go compiler).  Sometimes detecting heavily used code and compiling just that part or applying special optimization (just in time compilation).
Compilers don't have to go to machine language.  C is a popular target for experimental languages.  Another popular choice is a more or less machine like intermediate code which has to be interpreted after by a virtual machine, sometimes exposing the byte code as such, sometimes bundling the virtual machine with the byte code in one executable (it was the way one of the most popular and widespread Pascal implementation worked).
The virtual machine is itself an interpreter, but may apply compilation techniques as written above.
Compilers sometimes generate a more or less machine like description and delegates the true machine code generations to the linker.  That generation may also be done at installation time (AS/400, and successors whose name I can't remember in the ?Series soup, is the longest during system I know which is using that method).

Now your questions:

*

*Is an interpreter doing the same job as something like the JVM, just without the byte-code?

Sometimes yes, sometimes it is the bundling of the java compiler and the JVM.

*

*For python is the interpreter taking the high-level code and translating it into machine code?

There are several Python interpreters and systems.  I don't think the most popular one goes down to machine code.

*

*The Java virtual machine needs to be installed on a machine for a java program to run on it - is it similar for python - if the interpreter is installed on the target machine then the python program will run?

The most popular Python implementation is an interpreter which need to be installed.

*

*Is the JVM (& .net framework) effectively byte-code interpreters?

Yes, what I called "user level interpreters", they may apply true compilation techniques to offer better performance.

A: The distinction between interpreted code and compiled code used to be more clear when I was first learning.
The first programming language that I learned was an early version of Microsoft BASIC which was text and it was interpreted by an interpreter.
Then, when I went to college, I learned to program in Pascal and C which are both compiled languages that compile down to machine code and don't need anything like a virtual machine to run.
Also, in college, I learned Unix shell-scripting which is text and is interpreted.
The distintion used to be more clear.
I think of Java and Python as both being compiled and interpreted.  I see Python as being the right tool for the job when you want to be able to change something without having to recompile.
Java is good because you when you compile it, more of the bugs are found at compile-time.
I believe that both Python and Java are both compiled and interpreted.  I see Java as being "more compiled" because more bugs are found at compile-time.


text:
Q: Infer the key type of the array object I have the next example
type C = [
    {name: 'a'},
    {name: 'b'},
    {name: 'c'},
]

And I want to infer a new type SomeType based on the type C described above like this
const a: SomeType<C> = {
    a: () => {},
    b: () => {},
    c: () => {},
}

And so that there is a check of all keys. The following example must be invalid
const a: SomeType<C> = {
    a: () => {},
    b: () => {},
    // Error. "c" is not defined
}

I have tried to solve my problem like in the playground, but my solution doesn't check presence all keys

A: You need a mapped type to map from the array type to your desire type:
type SomeType<T extends Array<{ name: string }>> = {
  [P in T[number]['name']]: () => void
}

Playground Link

A: Here's one approach:
type SomeType<T extends { [k: number]: { name: string } }> =
    Record<T[number]['name'], () => void>;

It accepts T constrained to a type with a numeric index signature (such as an array) whose elements have a name property of type string.
And it evaluates to a type whose keys are those string-assignable name properties (using T[number]['name'], a series of indexed access types), and whose value types are a function (I chose () => void but you might have a more specific type you care about).  This uses the Record<K, V> utility type to represent an object type with keys of type  K and values of types V.
Let's try it out:
const ports: SomeType<C> = { // error, missing b and c
    a: () => { },
}

const ports2: SomeType<C> = {
    unknownkey: () => { }, // error, unknown key in object literal
                           // (note, only errors for object literal)
}

const ports3: SomeType<C> = { // okay
    a: () => { },
    c: () => { },
    b: () => { },
}

Looks good!
Playground link to code


text:
Q: CodeIgniter 3.0 app on a subdomain I have a problem with CodeIgniter 3, I have a project on a subdomain, the big problem that occurs to me is that after loguearme page freezes into an infinite loop.
mipagina.dominio.com.mx page is in the file paths to set the default controller $ route ['default_controller'] = 'user / login'; if I get access, but after loving me or giving access logear page stays in a loop.
For example, logeo after me must send mipagina.dominio.com.mx/admin/index, but not that reason the URL gives me mipagina.dominio.com.mx/?admin/index and hence does not pass, it stays in the loop.
(Sorry not English, used a translator).

A: (Posted on behalf of the OP).
The problem was fixed, the problem was a code line in the file Config.php is this line $config['enable_query_strings'] = TRUE; and was $config['enable_query_strings'] = FALSE;.


text:
Q: How to fix android error "method openFileInput in class Context cannot be applied to given types;2 Within my MainActivity.java I am trying to open a file according to the code given here. But when running the code
public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        final Button button = (Button) findViewById(R.id.btn1);
        button.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                Toast.makeText(getBaseContext(), "YOUR TEXT HERE", Toast.LENGTH_LONG).show();
                // Perform action on click

                FileInputStream fis = getBaseContext().openFileInput("hello.txt", Context.MODE_PRIVATE);
                InputStreamReader isr = new InputStreamReader(fis);
                BufferedReader bufferedReader = new BufferedReader(isr);
                StringBuilder sb = new StringBuilder();
                String line;
                while ((line = bufferedReader.readLine()) != null) {
                    sb.append(line);
                }
            }
        });

    }
}

I get the following error:
Error:(27, 55) error: method openFileInput in class Context cannot be applied to given types;
required: String
found: String,int
reason: actual and formal argument lists differ in length

I am not even able to understand what the error means. What 'argument list' is the message referring to?

A: As mentioned by @MuhammadKashifArif:
Instead of this
FileInputStream fis = getBaseContext().openFileInput("hello.txt",Context.MODE_PRIVATE);

use this
FileInputStream fis = openFileInput("hello.txt", MODE_PRIVATE);

It doesn't matter.
Context is context, and getBase context is still the same context as everything else, calling getBaseContext doesn't change the type of context compared to using this in an activity. There is no difference between accessing MODE_PRIVATE statically and using import static
I am not sure when exactly this changed (and I am not going to look through every version of android to check either), but it is openFileOutput that takes two arguments, a String an an Integer.
openFileInput now only takes one argument. So:
FileInputStream fis = /*Some context here if you are outside an activity.*/openFileInput("hello.txt");

And to load:
FileOutputStream fos = /*some context if outside activity.*/openFileOutput("hello.txt", Context.MODE_PRIVATE);

And I would once again like to clear up the fact that it doesn't make a difference whether or not you call getBaseContext, getApplicationContext, or call this/SomeActivity.this inside an activity. The context class itself doesn't change, the fields are the same. And writing MODE_PRIVATE without Context. in front of it is called a static import. The only difference between Context.MODE_PRIVATE and the static import MODE_PRIVATE is only you don't have to type those characters. The method doesn't exist no matter how you call it

As for the compile error, it basically says you are supplying more arguments than the method requires. You should also see a red warning over the call to the method as well, but what you see is the compile error as you tried to compile the build while there is a call to an unknown method.

A: As @LunarWatcher said the openFileInput takes 1 parameter.So,
Instead of this
FileInputStream fis = getBaseContext().openFileInput("hello.txt",Context.MODE_PRIVATE);

use this
FileInputStream fis = openFileInput("hello.txt");


text:
Q: REST and JSON - converting string to JSON array using jackson I'm new to JSON and REST. I'm working with Testing a rest API that returns strings like these:
[{
    "Supervisor_UniqueName": "adavis",
    "Active": "true",
    "DefaultCurrency_UniqueName": "USD",
    "arches_type": "x-zensar/primary",
    "Groups": "",
    "TimeZoneID": "US/Pacific-New",
    "UniqueName": "!!pl-10958-611879240",
    "EmailAddress": "!!pl-10958-611879240@devmail.zensar.com",
    "LocaleID_UniqueName": "en_US",
    "Name": "!!pl-10958-611879240"
}, {
    "Supervisor_UniqueName": "adavis",
    "Active": "true",
    "DefaultCurrency_UniqueName": "USD",
    "arches_type": "x-zensar/primary",
    "Groups": "",
    "TimeZoneID": "US/Pacific-New",
    "UniqueName": "!!pl-10958-789764779",
    "EmailAddress": "!!pl-10958-789764779@devmail.zensar.com",
    "LocaleID_UniqueName": "en_US",
    "Name": "!!pl-10958-789764779"
}, {
    "Supervisor_UniqueName": "adavis",
    "Active": "true",
    "DefaultCurrency_UniqueName": "USD",
    "arches_type": "x-zensar/primary",
    "Groups": "Report User",
    "TimeZoneID": "US/Pacific-New",
    "UniqueName": "105838945",
    "EmailAddress": "105838945@devmail.zensar.com",
    "LocaleID_UniqueName": "en_US",
    "Name": "105838945"
}, {
    "Supervisor_UniqueName": "adavis",
    "Active": "true",
    "DefaultCurrency_UniqueName": "USD",
    "arches_type": "x-zensar/primary",
    "Groups": "Report User, Report Manager, Report Administrator",
    "TimeZoneID": "US/Pacific-New",
    "UniqueName": "112352755",
    "EmailAddress": "112352755@devmail.zensar.com",
    "LocaleID_UniqueName": "en_US",
    "Name": "112352755"
}]

I invoke rest API as below:
final ResponseEntity<String> responseEntity = restTemplate.getForEntity(resourceUrl , String.class);

where restTemplate is of type  RestTemplate
I want to convert them into a JSON array, access each Json Object and get the Field and Values for each.
Is it possible to do it using jackson ?

A: You could use Jackson.
This is (part of) your JSON:
[
   {
      "Supervisor_UniqueName":"adavis",
      "Active":"true",
      "DefaultCurrency_UniqueName":"USD",
      "arches_type":"x-zensar/primary",
      "Groups":"",
      "TimeZoneID":"US/Pacific-New",
      "UniqueName":"!!pl-10958-611879240",
      "EmailAddress":"!!pl-10958-611879240@devmail.zensar.com",
      "LocaleID_UniqueName":"en_US",
      "Name":"!!pl-10958-611879240"
   },
   {
      "Supervisor_UniqueName":"adavis",
      "Active":"true",
      "DefaultCurrency_UniqueName":"USD",
      "arches_type":"x-zensar/primary",
      "Groups":"",
      "TimeZoneID":"US/Pacific-New",
      "UniqueName":"!!pl-10958-789764779",
      "EmailAddress":"!!pl-10958-789764779@devmail.zensar.com",
      "LocaleID_UniqueName":"en_US",
      "Name":"!!pl-10958-789764779"
   }
]

Just to give you an idea:
public MyClass {

  @JsonProperty("Supervisor_UniqueName")
  private String superVisorUniqueName;

  @JsonProperty("Active")
  private String active;

  // etc

  // getters and setters
}

Map JSON to your MyClass:
ObjectMapper mapper = new ObjectMapper();
List<MyClass> obj = mapper.readValue(json, new TypeReference<List<MyClass>>() {});


text:
Q: Can not copy data of HTML tags to JavaScript For some reasons I am trying to change functionality of submit button. I am facing problem in copying data from HTML tags to JS. The alert generated by following code prints "Undefined" not the data inside tag.
<html>
  <body>
    <input class="inputtext" id="email" name="email" type="text"></div>
    <input value="Submit" name="v4l" id="login" class="inputsubmit" type="button" onclick="myFunction();return false">

    <script>
      function myFunction() {
        var TestVar =document.getElementsByClassName('login').value;
        alert(TestVar);
      }
    </script>
  </body>
</html>

I know it can be done by form but I need it this way.

A: getElementsByClassName
          ^

See that s? Elements is plural. getElementsByClassName returns a NodeList (which is like an Array).
You have to either pick an index from it (foo[0]) or loop over it to get the values.

That said, you don't actually have any elements that are a member of the login class, so it is going to return a Node List of zero length.
You do have an element with id="login", so maybe you should use getElementById instead.

There doesn't seem much point in reading the value from an element that you've hard coded the value for. You might actually want to be using document.getElementById('email')

A: try
var TestVar = document.getElementById('email').value
alert(TestVar);

this will get value of text field


text:
Q: ng-model to a multiple select in angulardart I am trying to use ng-model with a multiple select in angulardart. The select is dynamically populated with option by django-autocomplete-light. Once I have added a few options, my (list) model is still empty.
Any point I could look at?
Here is a minimal example.
Template:

      <input
        type="text"
        name="car-autocomplete"
        id="id_car-autocomplete" value=""
        class="autocomplete"
        data-autocomplete-choice-selector="[data-value]"
        data-autocomplete-minimum-characters="1"
        data-autocomplete-url="/autocomplete/CarAutocomplete/"
        placeholder="car's name" autocomplete="off">

      <select style="display: none" class="value-select"
        name="cars" id="id_expert" multiple="multiple"
        ng-model="myctrl.cars"></select>

Controller:
@NgController(
    selector: '[a-selector]',
    publishAs: 'myctrl')
class MyController {
    List<String> cars;
}

Edit: according to Günter's answer, I wrote this directive:
  @NgDirective(selector: 'select[multiple]')
  class MultipleSelectDirective {
    SelectElement _selectElement;
    Compiler _compiler;
    Injector _injector;
    DirectiveMap _directiveMap;

    MultipleSelectDirective(Element this._selectElement, this._injector, this._compiler, this._directiveMap) {
      _selectElement.addEventListener('DOMNodeInserted',
          (_) => _compiler(_selectElement.childNodes, _directiveMap)(_injector, _selectElement.childNodes));
      _selectElement.addEventListener('DOMNodeRemoved',
          (_) => _compiler(_selectElement.childNodes, _directiveMap)(_injector, _selectElement.childNodes));
    }
  }

A: I haven't used this myself yet but the Angular.js API doc seems to use it differently.
ng-model holds the selected value and ng-options="myctrl.cars" assigns the items.
I would expect Angular.dart to work similar.
This worked for me:

  <select multiple="multiple" ng-model='myctrl.selected'>
    <option ng-repeat='c in myctrl.cars'>{{f}}</option>
  </select>

You need to add a field to the controller where you can assign the selected items (I used myctrl.selected) which receives a List<String>.
EDIT
When the HTML is modified you have to compile it to make Angular process the new elements and directives.
static dom.NodeValidator validator;
dom.Element _element;
Compiler _compiler;
Injector _injector;
DirectiveMap _directiveMap;
MyController(this._element, this._injector, this._compiler, this._directiveMap) {

_compiler(_element.childNodes, _directiveMap)(_injector, _element.childNodes);

I think a better way would be to try to get the values from JavaScript to Dart and add them to you controller and let ng-repeat insert them.

A: I ended doing it by inspecting the DOM from Dart each time it is updated:
@NgDirective(selector: 'select[multiple][ng-model]')
class MultipleSelectDirective {
  SelectElement _selectElement;
  NgModel ngModel;
  Scope scope;

  MultipleSelectDirective(Element this._selectElement, this.ngModel, this.scope) {
    _selectElement.addEventListener('DOMNodeInserted',
        (_) => _setValue());
    _selectElement.addEventListener('DOMNodeRemoved',
        (_) => _setValue());
  }

  void _setValue() {
    List<OptionElement> options = _selectElement.selectedOptions;
    List val = [];
    options.forEach((o) => val.add(o.value));
    ngModel.viewValue = val;
  }
}


text:
Q: Receiving an "Only size-1 arrays can be converted to Python scalars" I am receiving an only size-1 arrays can be converted to Python scalars error. I am assuming it is either dl or gl in the last portion of the code. I see that some people who face this error is due to confusion with numpy and python variables. I am trying to back track to figure out what is needed to be change to fix this error but am stumped. I indicated where this error is with >>> . Could anyone give any advise on this error? Thank you!
gen_inp=tf.placeholder(tf.float32,shape=[None,noise_dim])
disc_inp=tf.placeholder(tf.float32,shape=[None,img_dim])

batch_size=128
num_steps=80000
learning_rate=2e-4
display_step=20

def weight_init(shape):
    return tf.random_normal(shape=shape,stddev=1. / tf.sqrt(shape[0] / 2.))

W={"w1" : tf.Variable(weight_init([noise_dim,gen_dim])),
  "w2": tf.Variable(weight_init([gen_dim,img_dim])),
  "w3": tf.Variable(weight_init([img_dim,disc_dim])),
  "w4": tf.Variable(weight_init([disc_dim,1]))}
b={"b1":tf.Variable(tf.zeros([gen_dim])),
  "b2":tf.Variable(tf.zeros([img_dim])),
  "b3":tf.Variable(tf.zeros([disc_dim])),
  "b4":tf.Variable(tf.zeros([1]))}

def gen_fun(x):
    h1=tf.matmul(x,W["w1"])
    h1=tf.add(h1,b["b1"])
    h1=tf.nn.relu(h1)

    h1=tf.matmul(h1,W["w2"])
    h1=tf.add(h1,b["b2"])
    h1=tf.nn.sigmoid(h1)

    return h1
def disc_fun(x):
    h2=tf.matmul(x,W["w3"])
    h2=tf.add(h2,b["b3"])
    h2=tf.nn.relu(h2)

    h2=tf.matmul(h2,W["w4"])
    h2=tf.add(h2,b["b4"])
    h2=tf.nn.sigmoid(h2)

gen_out=gen_fun(gen_inp)
disc_real_out=disc_fun(disc_inp)
disc_fake_out=disc_fun(gen_out)
optin_gen=tf.train.AdamOptimizer(learning_rate=learning_rate)
optin_disc=tf.train.AdamOptimizer(learning_rate=learning_rate)

>>> cost_gen=-tf.reduce_mean(tf.log(disc_fake_out))

cost_disc=-tf.reduce_mean(tf.log(disc_real_out))+tf.log(1. -disc_fake_out)
vars_gen = [W['w1'],W['w2'],b['b1'],b['b2']]
vars_disc= [W['w3'],W['w4'],b['b3'],b['b4']]
training_gen=optim_gen.minimize(cost_gen,var_list=vars_gen)
training_disc=optim_gen.minimize(cost_disc,var_list=vars_disc)

init = tf.global_variables_initializer()
with tf.Session() as sess:

    sess.run(init)

    for step in range(1, num_steps+1):
        batch_x, _ = df.train.next_batch(batch_size)

        noise_temp = np.random.uniform(-1., 1., size=[batch_size, noise_dim])

        feed_dict = {disc_inp: batch_x, gen_inp: noise_temp}
        _, _, gl, dl = sess.run([training_gen, training_disc, cost_gen, cost_disc],
                               feed_dict=feed_dict)
        if step % 2000 == 0 or step == 1:
       >>>     print('Step %i: Generator Loss: %f, Discriminator Loss: %f' % (step, gl, dl))
            print("finished!")

    n = 6
    canvas = np.empty((28 * n, 28 * n))

    for i in range(n):
        z= np.random.uniform(-1., 1., size=[n, noise_dim])

        g= sess.run(gen_out, feed_dict={gen_inp: z})

        g= -1 * (g - 1)
        for j in range (n):
            canvas[i * 28:(i + 1) * 28, j * 28:(j +1) * 28] = g[j].reshape([28, 28])

    plot.figure(figsize=(n, n))
    plt.imshow(canvas, origin="upper", cmap="gray")
    plot.show()


text:
Q: Best way to configure AsyncTask for use in autocomplete search I am calling an AsyncTask in the onQueryTextChange method of a SearchView and displaying  the results in a list. The searching works, but occasionally tends to hang for a second if the user types quickly in the searchview. I want to further optimize this approach. Since its an autocomplete Search, as the user starting typing, several AsyncTasks gets queued for execution. But I am only interested in the very last searchrequest.
Currently, I am doing something like this
if (myAsyncTask != null)
    myAsyncTask.cancel(true);

   myAsyncTask = new MyAsyncTask(context,URL);

Is there a better way to do this? I would like to do something like this, if possible
myAsyncTask.executeOnExecutor(new OptimizedExectionerService);

The OptimizedExectionerService class should cancel all pending and runnning tasks in the pool and ONLY process the last request that was made.

A: Use a handler with a reasonable delay (to handle typing into an edittext).
private static final int SEARCH_DELAY = 500;
private Handler mHandler = new Handler();
private SearchRunnable executeSearch = new SearchRunnable();

private queueSearch(String term) {
    // Remove any previous searches
    mHandler.removeCallbacks(executeSearch);

    // Set the search term for the runnable
    executeSearch.setSearchTerm(term);

    // Schedule the search in half a second
    mHandler.postDelayed(executeSearch, SEARCH_DELAY);
}

private class SearchRunnable implements Runnable {
    String searchTerm = null;

    public void setSearchTerm(String term) {
        searchTerm = term;
    }

    @Override
    public void run() {
         //Execute Search here
         new MyAsyncTask(context, searchTerm);
    }
};


text:
Q: Factorisation of a polynomial in $\left(R\left[x\right],+,\cdot\right)$, $\left(Z\left[x\right],+,\cdot\right)$, ... I am given the following question:
"Given a random polynomial in $Z\left[x\right]$. We factorise this polynomial in the polynomial rings $\left(R\left[x\right],+,\cdot\right)$, $\left(Z\left[x\right],+,\cdot\right)$ and $\left(Z_3\left[x\right],+,\cdot\right)$ and find respectively $a$ , $b$ and $c$ factors. What is the general relation between $a$, $b$ and $c$?"
The only thing I could think of is $a \geq b \geq c$. Am I missing something?

A: No, the number of factors does not behave like this. Consider some "random" example, like
$f(x)=x^2+x+1$. Clearly this has no integer root, so that the factorisation of $f$ over $\mathbb{Z}$ gives $b=1$ factor. The same is true over $\mathbb{R}$. But $x^2+x+1=(x+2)^2$ over $\mathbb{Z}/3$, i.e., $c=2$.

A: There are the following ring homomorphisms. The inclusion
$$
f:\Bbb{Z}[x]\to\Bbb{R}[x],
$$
and the homomorphism
$$
p:\Bbb{Z}[x]\to\Bbb{Z}_3[x]
$$
that reduces all the coefficients modulo three.
Because the homomorphic image of a product is the product of images, we might initially think that the existence of a factorization in $\Bbb{Z}[x]$  implies the existence of a factorization in either of the other rings. And, more generally, think that this implies the inequalities $a\ge b$ and $c\ge b$.
This actually holds in a limited sense with the following special cavets forcing a reformulation. A homomorphism of rings may map a non-unit to a unit. Thus a proper factor may become non-proper. Here this can happen with both these homomorphisms. Both $f$ and $p$ map the product $4(x+1)$ of two non-units of $\Bbb{Z}[x]$ to an irreducible in their target rings, because $f(4)$ and $p(4)$ are both units.
To exclude this possibility we can restrict ourselves to monic polynomials in $\Bbb{Z}[x]$. This implies that there will be no constante factors.
The other caveat only affects $p$. The other homomorphism $f$ is injective, and thus takes distinct factors to distinct factors. For its part $p$ fails in that score. For example $p(x+1)=x+1=p(x+4)$. Therefore we need to be careful in counting the factors of polynomials like $(x+1)(x+4)\in\Bbb{Z}[x]$. It has two non-trivial factors in $\Bbb{Z}[x]$ but only one in $\Bbb{Z}_3[x]$ because that factor has multiplicity two there.
Conclusion. If we restrict ourselves to monic polynomials $f\in\Bbb{Z}[x]$ then $a\ge b$. If we further restrict ourselves to polynomials $f$ such that $p(f)$ has no multiple factors, then also $c\ge b$.
The inequality $c\ge b$ also holds (for monic polynomials) if we for example count only irreducible factors, and those with multiplicities.


text:
Q: Input file double pointers in C
I am getting some problems in my code and I can not fix it.  Can anybody catch the flaw in mycode? I wanna get city distance from input files and copy the city names in map without repetition.My problem is segmentation fault. the input file consist of several lines two cities names and distance between them and i try to get the cities name and copied them to the double pointer named as map. P.S sorry for poor english
city1[0]  = (char*)malloc(sizeof(char)*10);
city2[0]  = (char*)malloc(sizeof(char)*10);
map[0] = (char*)malloc(sizeof(char)*10);
map[1] = (char*) malloc(sizeof(char)*10);
map[2] = (char*) malloc(sizeof(char));
map[2] = NULL;
fscanf(data, "%s %s %d", city1[0], city2[0], &distance);
strcpy(map[0],city1[0]);
strcpy(map[1],city2[0]);
j=2,i=1;
while(fscanf(data, "%s %s %d",city1[i],city2[i], &distance)!=EOF){
    city1[i+1] = (char*)malloc(sizeof(char) *10);
    city2[i+1] = (char*)malloc(sizeof(char)*10);
    if(checker(map,city1[i])==1){
        map = realloc(map, sizeof(char*)*(j));
        map[j] = (char*) malloc(sizeof(char));
        strcpy(map[j], city1[i]);
        map[j+1] = (char*) malloc(sizeof(char));
        map[j+1] != NULL;
        j++;
    }
    if(checker(map,city2[i])==1){
        map = realloc(map, sizeof(char*)*(j));
        map[j] = (char*) malloc(sizeof(char));
        map[j+1] = (char*) malloc(sizeof(char));
        strcpy(map[j], city2[i]);
        map[j+1] = NULL;   j++;
    }
}

A: Show the definitions of the variables that you are using.
I think you have some misunderstanding regarding the use of malloc() to dynamically allocate space for strings. You are allocating space for single characters, using many calls to malloc(). This seems very confused.
Also please try to be more clear regarding what your code is supposed to do.


text:
Q: Not using reusable cell in UITableView with CollectionView in each cell I have a UITableView and in its prototype cell have a UICollectionView.
MainViewController is delegate for UITableView and
MyTableViewCell class is delegate for UICollectionView.
On updating each TableViewCell contents I call cell.reloadData() to make the collectionView inside the cell reloads its contents.
When I use reusable cells, as each cell appears, it has contents of the last cell disappeared!. Then it loads the correct contents from a URL.
I'll have 5 to 10 UITableViewCells at most. So I decided not to use reusable cells for UITableView.
I changed the cell creation line in tableView method to this:
let cell = MyTableViewCell(style: .default, reuseIdentifier:nil)

Then I got an error in MyTableViewCell class (which is delegate for UICollectionView), in this function:
override func layoutSubviews() {
    myCollectionView.dataSource = self
}

EXC_BAD_INSTRUCTION CODE(code=EXC_I386_INVOP, subcode=0x0)
fatal error: unexpectedly found nil while unwrapping an Optional value

MyTableViewCell.swift
import UIKit
import Kingfisher
import Alamofire

class MyTableViewCell: UITableViewCell, UICollectionViewDataSource {

    struct const {
        struct api_url {
            static let category_index = "http://example.com/api/get_category_index/";
            static let category_posts = "http://example.com/api/get_category_posts/?category_id=";
        }
    }

    @IBOutlet weak var categoryCollectionView: UICollectionView!

    var category : IKCategory?
    var posts : [IKPost] = []

    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code

        if category != nil {
            self.updateData()
        }
    }

    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)

        // Configure the view for the selected state
    }

    override func layoutSubviews() {
            categoryCollectionView.dataSource = self
    }

    func updateData() {
        if let id = category?.id! {
            let url = const.api_url.category_posts + "\(id)"
            Alamofire.request(url).responseObject { (response: DataResponse<IKPostResponse>) in
                if let postResponse = response.result.value {
                    if let posts = postResponse.posts {
                        self.posts = posts
                        self.categoryCollectionView.reloadData()
                    }
                }
            }
        }
    }

    internal func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "postCell", for: indexPath as IndexPath) as! MyCollectionViewCell

        let post = self.posts[indexPath.item]
        cell.postThumb.kf.setImage(with: URL(string: post.thumbnail!))
        cell.postTitle.text = post.title

        return cell
    }

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        //You would get something like "model.count" here. It would depend on your data source
        return self.posts.count
    }

    func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
        return 1
    }

}

MainViewController.swift
import UIKit
import Alamofire

class MainViewController: UITableViewController {

    struct const {
        struct api_url {
            static let category_index = "http://example.com/api/get_category_index/";
            static let category_posts = "http://example.com/api/get_category_posts/?category_id=";
        }
    }

    var categories : [IKCategory] = []

    override func viewDidLoad() {
        super.viewDidLoad()

        self.updateData()
    }

    func updateData() {
        Alamofire.request(const.api_url.category_index).responseObject { (response: DataResponse<IKCategoryResponse>) in
            if let categoryResponse = response.result.value {
                if let categories = categoryResponse.categories {
                    self.categories = categories
                    self.tableView.reloadData()
                }
            }
        }
    }

    // MARK: - Table view data source

    override func numberOfSections(in tableView: UITableView) -> Int {
        return self.categories.count
    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 1
    }

    override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
        return self.categories[section].title
    }

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
//        let cell = tableView.dequeueReusableCell(withIdentifier: "CollectionHolderTableViewCell") as! MyTableViewCell
        let cell = MyTableViewCell(style: .default, reuseIdentifier:nil)

        cell.category = self.categories[indexPath.section]
        cell.updateData()

        return cell
    }

}

MyCollectionViewCell.swift
import UIKit

class MyCollectionViewCell: UICollectionViewCell {

    @IBOutlet weak var postThumb: UIImageView!
    @IBOutlet weak var postTitle: UILabel!

    var category : IKCategory?

}

Why not reusing cells caused this? Why am I doing wrong?

A: There are a few things to do that should get you up to speed.
First, uncomment the line that uses reusable cells and remove the line of code that creates the non-reusable cells. It is safe to use reusable cells here.
Second, in MyTableViewCell, set the dataSource for the collection view right after the super.awakeFromNib() call. You only need to set the dataSource once, but layoutSubviews() will potentially get called multiple times. It's not the right place to set the dataSource for your needs.
override func awakeFromNib() {
    super.awakeFromNib()
    categoryCollectionView.dataSource = self
}

I have removed the call to updateData() from awakeFromNib(), as you are already calling it at cell creation. You can also delete the layoutSubviews() override, but as a general rule, you should be careful to call super.layoutSubviews() when overriding it.
Lastly, the reason the posts seemed to re-appear in the wrong cells is that the posts array wasn't being emptied as the cells were reused. To fix this issue, add the following method to MyTableViewCell:
func resetCollectionView {
    guard !posts.isEmpty else { return }
    posts = []
    categoryCollectionView.reloadData()
}

This method empties the array and reloads your collection view. Since there are no posts in the array now, the collection view will be empty until you call updateData again. Last step is to call that function in the cell's prepareForReuse method. Add the following to MyTableViewCell:
override func prepareForReuse() {
    super.prepareForReuse()
    resetCollectionView()
}

Let me know how it goes!


text:
Q: How to unit test code inside validate method nuxtjs vuejs jest I have code inside validate method if condition true it returns true else false.
I want to test that code. Is there any way to do it.

A: So usually asyncData method and validate method are part of nuxt not vuejs and can't be tested usually but we do want to test it if it was possible.
Why test validate : As we are working on a long project we want to test it if every condition works as expected, someone's change didn't hinder the working of this method and thus i came around with solution to call that method manually and pass parameters to it accordingly.
// example.vue
validate({ params, query }) {
    if (params.includes("abc" && query["something"])) {
      return true;
    } else {
      return false;
    }
  }

// example.test.js
import index from "example.vue"

describe("test", () => {
  it("Check validate method", async () => {
    // Check when query present
    const params = {
      abc: "abc"
    };
    const query = {
      something: "abc"
    };
    const validate = Index.validate({ params, $constants, query });
    expect(validate).toBe(true); // or false
  });
});


text:
Q: download large ibook file from safari (ipad) i have a large ibook file and i will share it with my friends via download link (dropbox,mediafire ..etc) so they can download it from safari.
But, how can i show download status for the file because they will wait very long time.
mega.co.nz
have good download status progress but only work on PC
thanks


text:
Q: Select N number of rows and UNION the results TABLEA:
ConditionId ContentId
10004       101
10004       102
10001       104
10001       103
10001       115

From the above data I need to select TOP N records for a particalar ConditionID and merge it with another set of top N results form a different condition id.
For example :
For Condition id 10001 Give out 2 results and Condition ID 10004 give the top 3 results (both of these results should be unique and not overlap):
I Could do :
SELECT top(2) * FROM TABLEA
WHERE Conditionid = 10001
UNION
SELECT top(3) * FROM TABLEA
WHERE Conditionid = 10004

But this is just a limited scenario and the condition Ids requested could be multiple instead of just 2 in the above scenario.
I do not want to write a dynamic SQL for performance reasons, is there a way I could do a similar thing by using ConditionId IN()
EDIT:
The results from the top 2 and top 3 should not overlap the contentids, so if a particular contentid was already part of Query 1, it should not be part of the next top N and so on.

A: One way (edited to deal with potential duplicate Conditionid).
DECLARE @T TABLE
(
Conditionid INT,
Num INT
)

INSERT INTO @T
VALUES(10001, 2),
      (10004, 3)

;WITH T(Conditionid, Num) AS
(
SELECT Conditionid,
       MAX(Num)
FROM @T
GROUP BY Conditionid
)
SELECT A.*
FROM  T
   CROSS APPLY (SELECT TOP (T.Num) *
                FROM   TABLEA A
                WHERE  A.Conditionid = T.Conditionid
                ORDER  BY A.ContentId) A

A: Sql-Server 2005 and above:
Note: Top records should be taken after ordering the results
declare table @t (numRecords int, id int)
insert into @t (numRecords, id)
values (2, 10001),
       (3, 10004)

;with cte as (
   select *, row_number() over (order by yourOrderCol) rn
   from yourTable
)
select cte.*
from cte join @t t
     on cte.ConditionId = t.id and cte.rn <= t.numRecords
Order by cte.ConditionId

A: SELECT top(2) * FROM TABLEA
WHERE Conditionid in ('10004', '10005')
UNION
SELECT top(3) * FROM TABLEA
WHERE Conditionid = ('10004', '10006')

is this what you expected


text:
Q: recursion with python argparse I'm writing a recursive program using argparse. The only required argument is a file (or files) to act on. When I call it recursively, I don't need the filenames (as I'll be calling on a new directory), but i need the options. the problem is that argparse allows both python programname.py -options arg FILENAME FILENAME and python programname.py FILENAME FILENAME -options arg. I could painstakingly search for a '-' and work it out with a ton of if statements, but i feel like there should be a better way.
not sure that it matters, but here are my argparse declarations:
 parser = argparse.ArgumentParser(description='Personal upload script. (defaults to ' + user + '@' + server + directory + ')')
 parser.add_argument('files', nargs="+", help='file(s) to upload')
 parser.add_argument('-s', metavar='example.com', default=server, help='server to upload to')
 parser.add_argument('-u', metavar='username', default=user, help='ftp username')
 parser.add_argument('-p', metavar='password', default=password, help='ftp password')
 parser.add_argument('-d', metavar='example/', default=directory, help='directory to place file in')
 parser.add_argument('-n', metavar='myfile.txt', help='name to save file as')
 parser.add_argument('-c', metavar='###', help='chmod upload')
 parser.add_argument('-l', action='store_true', help='print out new url(s)')
 parser.add_argument('-r', action='store_true', help='recursive')
 parser.add_argument('-F', action='store_true', help='force (overwrite files / create non-existing dirs)')
 parser.add_argument('-v', action='store_true', help='verbose')
 args = parser.parse_args()

thanks so much!

A: You're just making life difficult for yourself. You don't make programs recursive, you make functions recursive. Making a program recursive is an excellent way to run out of memory and generally overwhelm a system.
Rewrite your application so that the recursive work is confined to a function that calls itself, instead of another instance of your application.
Or, better, eliminate recursiveness entirely. It looks like you're just iterating through a directory tree. There's no reason to  do that recursively. In fact, Python has a library function that will take care of walking a directory tree for you. See os.walk.

A: You probably shouldn't be doing process-level recursion. That said, I think that argparse's treatment of "--" might provide the tool you're looking for (if I understand correctly). Search the argparse doc for the string "--".


text:
Q: Swift. How is it possible to get the name of an instance of a class within another class Could the Swift Jedi help me, I'm new to Swift.
There is class A and class B.
Is it possible to get the name (var name = Class A() ) of an instance of class A in the code of class B, which would then be added to the array.

A: You can get the class of an object, using type(of: ...). Example:
class A {
    func test() {
        print (type(of: self))
    }
}
class B : A{
}
let a = A()
a.test()
let b = B()
b.test()

However, this information is available only at runtime and not at compile time.  You may for example display the name of the class.  But you cannot dynamically create an array or a variable of that class.
If you need this, you need to design your classes using some kind of polymorphism. If all the classes have a base class in common, you can just define an array of the base class.  If not, you may consider letting the classes of your design share some common protocol:
protocol MySpecs {
    func test()
}
class AA : MySpecs {
...
}
class BB : MySpecs {
...
}

var mylist = [ MySpecs ]()
mylist.append(AA())
mylist.append(BB())
for x in mylist {
    x.test()
}

There are other possibilities. But unless you provide more details it'll be difficult to be more specific in the recommendations.


text:
Q: Storing API search results in local database Every time someone hits an API route I want to store that information in database, connected with req. IP.
Afther I would like to find some association rules based on similar searches.
Should I store some information in cookies or to use local dartabase?
Example on some hotels site:
I want to store info that i got a lot of request for cheap hotels in some specific area.
Thnaks.

A: Definitely in a database. Cookies wouldn't make sense because

*

*You cannot rely on cookies for persistent data. They can expire, be cleared, etc.

*Cookies can hold a very limited amount of data (4093 bytes usually)

*Cookies are stored locally on your client's browser, you want information across all of your clients.

Tracking user behavior data is very common web feature. You may want to use a web analytics service such as Google Analytics rather then implement your own.


text:
Q: Where to get Dell Inspiron 1545 drivers for the Dell 1397 wlan minicard wireless card? I cant seem to find the drivers for my Dell Wireless WLAN 1397 Minicard for ubuntu 11.04 andone know how i can get them and install them im sort of new to ubuntu?

A: Make sure your connected by an Ethernet cable and open the terminal (Ctrl+Alt+T)
sudo apt-get update; sudo apt-get install bcmwl-kernel-source

Reboot.


text:
Q: Return a number of how many times an attribute has been used in XML using XQuery I have an XML file that looks like this:
<CITY>
<STREET>
<HOUSE>
<FLAT>
<INHABITANT Year="1990" Gender="M">John Doe</INHABITANT>
<INHABITANT Year="1990" Gender="F">Jane Doe</INHABITANT>
<INHABITANT Year="1990" Gender="M">John Doe</INHABITANT>
</FLAT>
</HOUSE>
</STREET>
</CITY>

Using XQuery I need to return this:
<GENDERS><FEMALES>1</FEMALES><MALES>2</MALES></GENDERS>

How would I go about doing this?
What would the code be for this?
As I understand XQuery is for XML what SQL is for databases, so that kind of gives me an idea. This is for a school project that requires XQuery and I have 0 experience with this.

A: One possible solution is as follows:
let $doc := document {
   <CITY>
    <STREET>
      <HOUSE>
        <FLAT>
          <INHABITANT Year="1990" Gender="M">John Doe</INHABITANT>
          <INHABITANT Year="1990" Gender="F">Jane Doe</INHABITANT>
          <INHABITANT Year="1990" Gender="M">John Doe</INHABITANT>
        </FLAT>
      </HOUSE>
    </STREET>
  </CITY>
}
return element GENDERS {
  let $genders := $doc//INHABITANT/@Gender
  return (
    element FEMALES { count($genders[. = 'F']) },
    element MALES   { count($genders[. = 'M']) }
  )
}

A: Combining the answers I got in this post, I've made this code which works exactly as needed. Thanks to everyone who chimed in (Christian Grūn)
let $male:=//INHABITANT[@Gender="M"]
let $female:=//INHABITANT[@Gender="F"]
return
<GENDERS>
<FEMALES>{count($female)}</FEMALES>
<MALES>{count($male)}</MALES>
</GENDERS>


text:
Q: Is there a more elementary example of the holographic principle? Someone was telling me about the holographic principle, basically he said that the state of a system is determined entirely by the values of various physical quantities on its boundary. This is not exactly what it says on Wikipedia's Holographic Principle article - "The holographic principle is a principle of string theories ... that states that the description of a volume of space can be thought of as encoded on a lower-dimensional boundary to the region—preferably a light-like boundary like a gravitational horizon".
I think Wikipedia's definition is a bit confusing to a beginner, since string theories have maybe 10 dimensions, so it's not clear what "lower-dimensional" means (9 dimensions?), and also since it requires one to understand the concept of a "light-like" geodesic and how this concept can be extended to define a "light-like boundary" surface.
I am wondering if the same principle can be stated in a more elementary form without invoking string theory. For example, is it the case that knowing the electric and magnetic field on the surface of a sphere will tell me the spatial distribution and velocities of charges within the sphere? If so, does this simpler idea have a name? (Would it be incorrect to refer to it as the holographic principle?)

A: Disclaimer: I'm not an expert on the holographic principle. I'm posting this answer because it might have some limited value, but I hope somebody else steps in to give you a real answer.

is it the case that knowing the electric and magnetic field on the surface of a sphere will tell me the spatial distribution and velocities of charges within the sphere?

No.
For a counterexample, consider three concentric shells: The innermost one has static electric charge $+Q$ spread uniformly over its surface, the middle one has charge $-Q$ spread uniformly over its surface, and the outer one is where you make your observations. According to classical electrodynamics, the electric and magnetic fields on the outer surface are both zero for any $Q$, so value of $Q$ is not encoded on the boundary.
The holographic principle is different, and despite the name, it's also different than an ordinary hologram. In an ordinary hologram of an opaque object, you don't see the inside of the object. In the thing called the holographic principle, the lower-dimensional encoding is all-seeing, and the possibility of such an all-seeing lower-dimensional encoding is closely associated with impossibility of cramming unlimited amounts of information into arbitrarily small spaces in the bulk. That limitation, in turn, is closely related to the fact that massive objects automatically bend spacetime, the phenomenon we know as gravity.
(Caveat: the question of whether or not a "holographic screen" can encode what's inside a black hole might still be unsettled, but the question of whether or not a black hole really has an "inside" that's informationally independent from its "outside" might also still be unsettled. ...or maybe they are settled and I just haven't learned how yet. I have a lot to learn.)

Is there a more elementary example of the holographic principle?

The the AdS/CFT correspondence is most well-developed family of examples we have that exhibit the holographic principle, but even the simplest examples of the AdS/CFT correspondence (like AdS$_3$/CFT$_2$) are still far from simple by my standards. If a more accessible example of the holographic principle does exist, I hope that somebody else posts an answer about it, because I'd love to learn about it.

A: In the holographic principle for quantum gravity the DOFs are encoded on a spacetime codimension-2 Cauchy surface. A conventional hyperbolic system has a spacetime codimension-1 Cauchy surface. This is e.g. the case for E&M and Maxwell's equations, cf. e.g. my Phys.SE answer here. Similarly, Dirichlet problems are specified on a codimension-1 boundary. See also this related Phys.SE post.