text:
Q: List expansion in lift I'm very new to working with lift, so please bear with me. If I want to implement something like https://help.squareup.com/ where the list items are hidden until the title is clicked. What's the best way to implement something like that in lift? Is there a widget I could use?
Thanks

A: Use jQuery.. Like this (do not forget to attach the library itself)
$('.open_below').click(function(){
    $(this).next('div.info').slideToggle();
});

And HTML code (a small piece related to your question)

Click me

Put some information here

Try it http://jsfiddle.net/3EbdN/


text:
Q: How can I select all entries containing one of two values per user? In Oracle 11g, I have one table, pets. Pets has two columns, owner and type. The only types of pets in the table are dogs, cats and fish.
Some owners have two pets.
I want to select all of the owners that have both a cat and a dog.
How can I do that?

A: Various different ways to do it, here's one:
select owner from pets where type = 'CAT'
intersect
select owner from pets where type = 'DOG'

The INTERSECT operator produces a set of distinct owners of both cats and dogs.

A: You could use GROUP BY and HAVING:
SELECT t.owner
FROM tab t
WHERE t.type IN ('dog', 'cat')
GROUP BY t.owner
HAVING COUNT(DISTINCT t.type) = 2;

A: Imagining a table like this:
|owner  ||  type|
-----------------
|own1   |   dog |
|own1   |   cat |
|own2   |   dog |
|own3   |   dog |
|own3   |   fish|

You could try something like this:
select o.cat_and_dog_owner
from(
    select t.owner as cat_and_dog_owner, sum(case when t.type = 'dog' then 1 else 0 end) as dog_cnt, sum(case when t.type = 'cat' then 1 else 0 end) as cat_cnt
    from table t
    where t.type in ('dog', 'cat')
    group by t.owner
    having (sum(case when t.type = 'dog' then 1 else 0 end) > 0) and (sum(case when t.type = 'cat' then 1 else 0 end) > 0)
) o

Basically you only want to select cat and dog records. The we use sum and case in conjunction to get a count of dogs and cats grouped by owner. Finally we check with the having clause to make sure we only get records where the count in both columns is greater than 0.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Best way for social sharing in Android I've been looking for a way to share information to social networks. I've found 2 possible solutions:

*

*Look for installed apps and sent an intent (like android uses in it's gallery)

*Use the socials network api

When looking for quick ways to implements i say use the installed apps for that but if it goes customization and generalization i think the second option is the best.
I've a hard time deciding if one outweighs the other or not.
So my question is: What is the best approach? One of the ones i suggested or a whole different way?

A: I have worked with the Facebook API and I know that it's a really good one. It looks if a native Facebook app is installed, if not it pops a little popup on your screen where it does it things, if yes, it uses that app to do your things.
I think you have to take the same approach for all your Social Networks: check if app exist. if yes, use. if no, use own implementation

A: You might also check Socialize out  http://www.GetSocialize.com .  Full feature list at http://go.GetSocialize.com/features  It'll let you share social actions in the app out to social networks (currently Facebook; Twitter coming this month, then likely Google+ after that).

A: The Android OS uses intents to do this...
While searching for an answer to this question I came across:
Social sharing on mobile
Quoting @NewProggie
Intent share = new Intent(Intent.ACTION_SEND);
share.setType("image/jpeg") // might be text, sound, whatever
share.putExtra(Intent.EXTRA_STREAM, pathToPicture);
startActivity(Intent.createChooser(share, "share"));

Depending on the MIME type you put in for setType, the chooser will show email, gmail, SMS, twitter, facebook, flickr, or whatever!
This is the easiest way to share content for the developer, and a proven method.

A: What about the case when user does not have specific social network API installed? Then you are left with only using the API. Some might argue that if user doesn't have facebook app installed, he should not be able to share stuff on facebook, but I for example use facebook throught their mobile site, I won't waste precious space on my G1 for the hefty facebook app.
I'd go with using the API.


text:
Q: Class variable query in python Framework: Robot, Language: Python-3.7.1 Proficiency: Novice
I have a variable args=[] defined at class level. The values of the variables are being assigned from command prompt using module 'sys'
import sys

class Runner():
    args = []

    def argument_reader(self):
        self.args = list(sys.argv)

    def login(self):
        return self.args[1], self.args[2]

I could print all the values of args as long as execution stays within the module. If I wanted to call the same values from other module, it does not return anything as the values are being cleared out from the memory. Since class variables are static by default in python, why system is not RETAINING the values?
cmd line>>py Runner.py testing test@123

For Example:
Calling method from same class:-

run = Runner()
run.argument_reader()
print(run.login())

Output>>> testing, testing@123

Calling the same method from another class:-

runn = Runner.Runner()
print(runn.login())

output>> IndexError: list index out of range

A: If you want a singleton-type value, change your code to look like this.
class Runner():
    args = []

    def argument_reader(self):
        Runner.args = list(sys.argv)

    def login(self):
        return Runner.args[1], Runner.args[2]

Otherwise, you'll have to call argument_reader() on each instance.


text:
Q: How to copy an array? I am trying to create a temporary array
Stack<Point[]> v = new Stack<Point[]>();
Point[] c= new Point[4];

then store it in a stack
v.Push(c);

but every time I try to modify the array, it also modify every instance inside the stack.
c[state] = mouse;

Is there a way to copy it into the stack?

A: Because arrays are references type you use the same instance, so every time I  modify the array, it also modifies every instance inside the stack.
I would create a new instance array to Stack instead of c, It can split two array.
Stack<Point[]> v = new Stack<Point[]>();
Point[] c = new Point[4];
v.Push(new Point[4]);
c[0] = new Point(1, 1);

if there are some data in c Point[], you can try to use CopyTo to copy the data to another array.
Stack<Point[]> v = new Stack<Point[]>();
Point[] c = new Point[4];

Point[] pushArr = new Point[c.Length];
c.CopyTo(pushArr, 0);
v.Push(pushArr);

A: Yes. Your stack only keeps the reference to the array. You have to create a copy of the array.
Stack<Point[]> v = new Stack<Point[]>();
Point[] c = new Point[4];
v.Push(c);

c[0] = new Point(5, 5);
Point[] cc = new Point[c.Length];
Array.Copy(c, cc, c.Length);
cc[0] = cc[0];

c[0].X = 20;
c[0].Y = 20;
var cx = v.Pop();

Console.WriteLine(c[0]);
Console.WriteLine(cx[0]);
Console.WriteLine(cc[0]);

EDIT: the result:
{X=20,Y=20}
{X=20,Y=20}
{X=5,Y=5}

A: When you say that:
int[] arr1=arr2;

It does not simply copy the data of one variable to another, it store a reference instead.
The solution to my problem is:
v.Push(new Point[4]);
Point[] c = v.Last();

Here i am referring 'c' to the last variable of my stack.
What was happening before is that i was referring every single variable of my stack to 'c'.


text:
Q: Android: Provider Test Case 2 and getFilesDir() Part of my application involves saving a png file to my local files directory, and then shared via a content provider.
I write the file via getContext().openFileOutput
However, in my content provider, ParcelFileDescriptor will only open actual File objects. So trying to do this via a mocked out content provider using ProviderTestCase2, the following code doesn't work:
return ParcelFileDescriptor.open(new File(getContext().getFilesDir(), filename), ParcelFileDescriptor.MODE_READ_ONLY)

This is because context.getFilesDir() points to /dev/null in the mock context given to the provider via the ProviderTestCase2 code. The code above results in an exception because /dev/null doesn't count as a directory. Is this as intended?

A: This feels like a joke... The docs say:

Returns the absolute path to the directory on the filesystem where files created with openFileOutput(String, int) are stored.

But the IsolatedContext source is this:
@Override
public File getFilesDir() {
    return new File("/dev/null");
}

So we have better ignoring that method and try with
@Rule
public TemporaryFolder tempFolder = new TemporaryFolder();

in out tests.


text:
Q: Style WPF Tabs Like Visual Studio Tabs In WPF is it possible to style the WPF TabControl to lool like those in Visual Studio?
Instead of this: (Normal Tabs)

I will prefer this: (Styled Tabs)

A: It's definitely possible, through the use of a ControlTemplate. See this MSDN entry for an example of a TabControl ControlTemplate. You can use this as a starting point. Good  luck!


text:
Q: How to start a new activity when item is clicked of a custom list view I am trying to start new activity when I select an item of a custom list view, I tried the app on emulator and the new activity is not started and the item was not clickable...!. Why the item is not clickable ? any idea ? any suggestion ?
The following is the activity that uses a custom list view:
package com.example.welcome.madrasti;

import android.content.Intent;
import android.database.Cursor;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;

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

public class ListOfSchoolsPublic extends AppCompatActivity {

        Intent redirect;
        Intent item;
        ListView list;
        ArrayList<String>  _sa;
        DBAdapter db;

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

            openDB();

            list= (ListView) findViewById(R.id.usersList);

            redirect = getIntent();

            Cursor cursor = db.getAllRows();

            _sa= new  ArrayList<String>();

            //cursor.moveToFirst();

            Log.d("CURSORCOUNT","Number of rows in the Cursor is = " + String.valueOf(cursor.getCount()));

            while(cursor.moveToNext()) {

                if(cursor.getString(DBAdapter.COL_SChOOL_TYPE_TABLE_2).equals("حكومية"))
                _sa.add(cursor.getString(DBAdapter.COL_SCHOOLNAME_TABLE_2));

            }

            cursor.close();

            @SuppressWarnings("rawtypes")
            ArrayAdapter adapter = new ArrayAdapter(this,android.R.layout.simple_list_item_1,_sa);

            list.setAdapter(new TempLyaout(ListOfSchoolsPublic.this,_sa));

           list.setOnItemClickListener(new AdapterView.OnItemClickListener()
            {
                @Override
                public void onItemClick(AdapterView<?> arg0, View arg1,int position, long arg3)
                {

                    String selectedItem = (String) arg0.getItemAtPosition(position);

                    itemInfo(selectedItem);
                }
            });

    }

    ///////////////////////////////////////////////////////////////

    public void itemInfo(String selectedItem){

           item = new Intent(getApplicationContext(), NewSchool.class);

           item.putExtra("schoolName",selectedItem);

           startActivity(item);

    }

    ///////////////////////////////////////////////////////////////
    @Override
    protected void onDestroy() {
        super.onDestroy();
        closeDB();

    }// end onDestroy method

    ///////////////////////////////////////////////////////////////

    private void openDB() {
        db = new DBAdapter(ListOfSchoolsPublic.this);
        db.open();
    } // end openDB method

    //////////////////////////////////////////////////////////////

    private void closeDB() {
        db.close();
    } // end closeDB method

}

The following is the xml of the list view:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".ListOfSchoolsPublic">

    <ListView
        android:id="@+id/usersList"
        android:layout_width="395dp"
        android:layout_height="523dp"
        android:focusable="false"
        android:layout_x="4dp"
        android:layout_y="-1dp"
        app:layout_constraintStart_toStartOf="parent"
        tools:layout_editor_absoluteY="7dp"></ListView>

</android.support.constraint.ConstraintLayout>

A: This issue presist when you have some clickable item in your list item.
If your item listener is not working then you can apply this on ListView in xml layout.
android:descendantFocusability="blocksDescendants"

You can also put many clicks listeners if you need in adapter class like
public class MyAdapter extends ArrayAdapter<Contact> {
        Context context;
        public MyAdapter(Context context, ArrayList<Contact> users) {
            super(context, 0, users);
            this.context = context;
        }

        public View getView(int position, View convertView, ViewGroup parent) {

            Contact user = getItem(position);

            if (convertView == null) {
                convertView = LayoutInflater.from(getContext()).inflate(R.layout.listviewadapter, parent, false);
            }
            TextView name = convertView.findViewById(R.id.name);
            TextView num = convertView.findViewById(R.id.num);
            // Populate the data into the template view using the data object

            name.setText(user.name);
            num.setText(user.phone_number);
            // can set click on name or num
            name.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Toast.makeText(context, position + "position clicked", Toast.LENGTH_SHORT).show();
                }
            });
            // can set click on full list item
            convertView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Toast.makeText(context, position + "position clicked", Toast.LENGTH_SHORT).show();
                }
            });
            return convertView;
        }
    }


text:
Q: Какие реализации табов лучше использовать? Насколько грамотен этот код? код на codepen
    'use strict'
    let tabLinks = document.querySelectorAll('.tb-links a'),
    tabContents = document.querySelectorAll('.tb-content div')
tabs.addEventListener('click', function(event) {
    let target = event.target;
    event.preventDefault();
    if(target.tagName != 'A') return false;

    for (let i of tabLinks){
        i.classList.remove('active');
    }
    for (let i of tabContents){
        i.classList.remove('show');
    }

    for (let i = 0; i < tabLinks.length; i++) {
        if(tabLinks[i] == target){
            tabLinks[i].classList.add('active');
                tabContents[i].classList.add('show');
        }
    }

});


text:
Q: divide complex finction in to multiple linear functions im programing a small controler an have to use sqrt but the controler doesnt suport it  . the controler have what they call a 24 point linearization wich means that you chose 24 x and y positions and the controler makes 23 linear functions out of it.
My cucuestion is how do i find the optimal points for the function
Y= sqrt(x)  from 0 to 7, first point is x=0 and last X=7
could it be done in excel?


text:
Q: jQuery and form POST difference to python Bottle I'm trying to figure out how to use jQuery AJAX with Python's Bottle module.
I've created a very basic page containing two buttons, one controlled by jQuery and the other one inside a form as a submit button. Both buttons just send a POST request to the a bottle server which should respond with a "Done!" message.
This is the code of the template:
<!DOCTYPE html>
<html>
    <head>
        <title>Test Template</title>
        <!-- JQuery JS -->
        <script src="http://code.jquery.com/jquery.js"></script>

        <script>
            $(document).ready(function() {
                $('button').on('click', function(){
                    $.post("/home");
                });
            });
        </script>

    </head>
    <body>
        <button>Submit</button>
        <form action="/home" method="post" enctype="multipart/form-data">
            <input type="submit" value="Submit" />
        </form>
    </body>
</html>

And this is the code of the bottle server:
from bottle import route, run, template

@route('/home')
def home():
    return template('template')

@route('/home', method='POST')
def homePost():
    return  "Done!"

run(host='localhost', port=8080, debug=True)
run(reloader=True)

Why clicking the form button returns the message correctly but clicking on the jQuery one does nothing? Is jQuery blocking bottle's response somehow?
Thanks for your help.
Pablo

A: ...because the jquery button sends an ajax request to the server.  An ajax request happens behind the scenes and does nothing to the page.  On the other hand, when you click on a form's submit button a new page is loaded containing whatever the server sent back.
You need to specify a function in your jquery ajax request that will be called when the server returns the data. Inside the function, you can do something with the data--typically inserting it into an already existing  tag, e.g.
$.post("/home", function(dataFromServer) {
  $('#mydiv').html(dataFromServer);
}

The beauty of an ajax request is that you can retrieve data from the server and then insert it into a page--all without reloading a page.


text:
Q: Problema para sumar señales en VHDL Estaba trabajando en una práctica que me encargaron en la escuela, en VHDL, el entorno es el ISE 14.7 y el kit es un Spartan 3E.
La práctica se trata de un pequeño pseudo-procesador. De hecho, está casi funcionando. En teoría, lo que debería hacer sería:

*

*tomará un valor de una memoria (será simulada por los 4 switches de la FPGA)

*guardarlo en una variable A

*tomar otro valor de la misma memoria (de nuevo los switches)

*guardarlo en una variable B

*sumarlos

*mostrar en 2 displays el resultado (máximo 30)

*tomar de nuevo un valor y ponerlo en A

*tomar otro valor y ponerlo en B

*restar A-B

*mostrarlo en los displays (sólo módulo, no signo)

Cuando lo probé, solucioné el rebote con la primera parte. Ésta hace un preescaler y a la vez funciona como filtro. La parte del final actúa como un multiplexor (aclaro en ninguno de los dos casos está el problema).
El problema radica en el process del procesador central. Éste tiene en lista de sensibilidad T y cada vez que se da un clic avanza, funciona todo bien, muestra los valores y avanza cada vez que se da el clic al botón llamado timer. El problema es que al llegar a la suma o resta de los valores almacenados en las variables A y B no da un resultado correcto, simplemente no almacena el valor.

Éste es el fragmento que me da problemas. Pareciera que cada vez que T se incrementa, los valores de A y B, si es que ya se capturaron, se resetean, de modo que la operación nunca se lleva a cabo correctamente.
Por su parte, val es una señal que se manda a dos displays para multiplexar. Esta parte funciona correctamente, mi problema es que cada que cambio de posición en los If con "T" los valores de las variables A y B no se mantienen.
PROCESS(T)
    variable A:    std_logic_vector(3 DOWNTO 0);
    variable B:    std_logic_vector(3 DOWNTO 0);
    variable C:    STD_LOGIC_VECTOR(4 DOWNTO 0);
BEGIN  --  BLOQUE #2

IF T="00000" THEN--0
    X0<="00000011";
END IF;

IF T="00001" THEN--1
    IF MEM="0001" THEN
       VAL<="00001";
    ELSE
       VAL<="11111";
    END IF;
    X0<="00000110";
END IF;
IF T="00010" THEN--2
    X0<="00011010";
END IF;

IF T="00011" THEN--3
    X0<="00000011";
END IF;

IF T="00100" THEN--4
    VAL<=('0'& MEM);--se carga el primer valor
    X0<="00000110";
END IF;

IF T="00101" THEN--5
    A:=MEM;
    VAL<=('0' & A);
    X0<="00110010";
END IF;

IF T="00110" THEN--6
    --X0<="01010010";
    X0<="00000011";
END IF;

IF T="00111" THEN--7
    B:=MEM;
    VAL<=('0' & B);
    X0<="00000110";
END IF;

IF T="01000" THEN--8
    X0<="01010010";
END IF;

IF T="01001" THEN--9
   C:=STD_LOGIC_VECTOR(UNSIGNED(A)+UNSIGNED(B));
   VAL<=(C);--se muestra el resultado
    X0<="10000010";
END IF;

IF T="01010" THEN--10
    X0<="00000011";
END IF;

IF T="01011" THEN--11
    IF MEM="0001" THEN
       VAL<="00010";
    ELSE
       VAL<="11111";
    END IF;
    X0<="00000110";
END IF;

IF T="01100" THEN--12
    X0<="00011010";
END IF;

IF T="01101" THEN--13
    X0<="00000011";
END IF;

IF T="01110" THEN--14
    VAL<=('0' & MEM);--se muestra el primer valor
    X0<="00000110";
END IF;

IF T="01111" THEN--15
    A:=MEM;
    VAL<=('0' & MEM);
    X0<="00110010";
END IF;

IF T="10000" THEN--16
    X0<="00000011";
END IF;

IF T="10001" THEN--17
    VAL<=('0' & MEM);--se muestra el segundo valor
    X0<="00000110";
END IF;

IF T="10010" THEN--18
    B:=MEM;
    VAL<=('0' & B);
    X0<="01010010";
END IF;

IF T="10011" THEN--19
   C:=STD_LOGIC_VECTOR(UNSIGNED(A)-UNSIGNED(B));--se muestra la operacion
    VAL<=(C);
    X0<="00000000";
END IF;

if T>"10011" then
   X0<="00000000";
end if;

END PROCESS;


text:
Q: Adding 8BIM profile metadata to a tiff image file I'm working on a program which requires 8BIM profile information to be present in the tiff file for the processing to continue.
The sample tiff file (which does not contain the 8BIM profile information) when opened and saved in Adobe Photoshop gets this metadata information.
I'm clueless as to how to approach this problem.
The target framework is .net 2.0.
Any information related to this would be helpful.

A: No idea why you need the 8BIM to be present in your TIFF file. I will just give some general information and structure about 8BIM.
8BIM is the signature for Photoshop Image Resource Block (IRB). This kind of information could be found in images such as TIFF, JPEG, Photoshop native image format etc. It could also be found in non-image documents such as in PDF.
The structure of the IRB is as follows:

Each IRB block starts with 4 bytes signature which translates to string "8BIM." After that, is a 2 bytes unique identifier denoting the kind of resource for this IRB. For example: 0x040c for thumbnail; 0x041a for slices; 0x0408 for grid information; 0x040f for ICC Profile etc.
After the identifier is a variable length string for name. The first byte of the string tells the length of the string (excluding the first length byte). After the first byte comes the string itself. There is a requirement that the length of the whole string (including the length byte) should be even. Otherwise, pad one more byte after the string.
The next 4 bytes specifies the size of the actual data for this resource block followed by the data with the specified length. The total length of the data also should be an even number. So if the size of the data is odd, pad another one byte. This finishes a whole 8BIM.
There could be more than one IRBs but they all conform to the same structure as described above. How to interpret the data depends on the unique identifier.
Now let's see how the IRBs are include in images. For a JPEG image, metadata could be present as one of the application (APPn) segment. Since different application could use the same APPn segment to store it's own metadata, there must be some kind of identifier to let the image reader know what kind of information is contained inside the APPn. Photoshop uses APP13 as it's IRB container and the APP13 contains "Photoshop 3.0" as it's identifier.
For TIFF image which is tag based and arranged in a directory structure. There is a private tag 0x8649 called "PHOTOSHOP" to insert IRB information.
Let's take a look at the TIFF image format (quoted from this source):

The basic structure of a TIFF file is as follows:
The first 8 bytes forms the header. The first two bytes of which is
  either "II" for little endian byte ordering or "MM" for big endian
  byte ordering. In what follows we'll be assuming big endian ordering.
  Note: any true TIFF reading software is supposed to be handle both
  types. The next two bytes of the header should be 0 and 42dec (2ahex).
  The remaining 4 bytes of the header is the offset from the start of
  the file to the first "Image File Directory" (IFD), this normally
  follows the image data it applies to. In the example below there is
  only one image and one IFD.
An IFD consists of two bytes indicating the number of entries followed
  by the entries themselves. The IFD is terminated with 4 byte offset to
  the next IFD or 0 if there are none. A TIFF file must contain at least
  one IFD!
Each IFD entry consists of 12 bytes. The first two bytes identifies
  the tag type (as in Tagged Image File Format). The next two bytes are
  the field type (byte, ASCII, short int, long int, ...). The next four
  bytes indicate the number of values. The last four bytes is either the
  value itself or an offset to the values. Considering the first IFD
  entry from the example gievn below:

       0100 0003 0000 0001 0064 0000
       |    |    |         |
 tag --+    |    |         |
 short int -+    |         |
 one value ------+         |
 value of 100 -------------+

In order to be able to read a TIFF IFD, two things must be done first:

*

*A way to be able to read either big or little endian data

*A random access input stream which wraps the image input so that we can jump forward and backward while reading the directory.

Now let's assume we have a structure for each and every 12 bytes IFD entry called Entry. We read the first two bytes (the endianess is not applied here since it's either MM or II) to determine the endianess. Now we can read the remaining IFD data and interpret them according to the the endianess we already know.
Right now we have a list of Entry. It's not so difficult to insert a new Entry into the list - in our case, it's a "Photoshop" Entry. The difficult part is how to write the data back to create a new TIFF. You can't just write the Entries back to the output stream directly which will break the
overall structure of the TIFF. Cautions must be taken to keep track of where you write the data and update the pointer of the data accordingly.
From the above description, we can see that it's not so easy to insert new Entries into TIFF format. JPEG format will make it much easier given the fact that each JPEG segment is self-contained.
I don't have related C# code but there is a Java library here which could manipulate metadata for JPEG and TIFF images like insert EXIF, IPTC, thumbnail etc as 8BIM. In your case, if file size is not a big issue, the above mentioned library can insert a small thumbnail into a Photoshop tag as one 8BIM.


text:
Q: Numero aleatorio de 36 digitos en C# Quiero obtener un numero de 36 digitos aleatorios en C#, utilice el Random pero no pude hacer que el numero de digitos solo fuera 36
Saludos y gracias

A: Se me ocurre que podrías acomularlos en una variable String si lo que quieres es un número tan largo.
Random random = new Random();
String numero="";
for(int i=0;i<36;i++){
    numero +=  Convert.ToString(random.Next(0, 9));

}

De esta forma tendrías un número de 36 dígitos aleatorio guardado en una variable String. Si lo que quieres es hacer cálculos con el la cosa se complica.
Que yo sepa el valor máximo de Int64 según microsof es 9.223.372.036.854.775.807

Int64 de microsoft
Int32 de microsfot
Límites de Integer

Si intentas pasar ese número a una variable int básicamente te va a dar

System.OverflowException: 'Valor demasiado grande o demasiado pequeño para tipo de valor.'


text:
Q: Использование @Value в Spring Пытаюсь получить данные из файла application.properties находящегося в корне resources таки образом:
@Component
public class TestSpAn {
    @Getter
    @Value("${test.a.b}")
    String val;
}

В application.properties это выглядит так:
test.a.b=12345

Вызываю вот так:
public static void main(String[] args) {
    ApplicationContext context = new AnnotationConfigApplicationContext(SpringBeansConfigurationInjector.class);
    final TestSpAn bean = context.getBean(TestSpAn.class);
    System.out.println(bean.getVal());
}

Вывод в консоль вместо 12345, получаю ${test.a.b}.
Подскажите пожалуйста почему так происходит, и как это исправить?
Вот такие модули спринга подключены:
    ...
    <spring-version>4.3.9.RELEASE</spring-version>
    ...

    <!-- https://mvnrepository.com/artifact/org.springframework/spring-core -->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-core</artifactId>
        <version>${spring-version}</version>
        <exclusions>
            <exclusion>
                <artifactId>commons-logging</artifactId>
                <groupId>commons-logging</groupId>
            </exclusion>
        </exclusions>
    </dependency>

    <!-- https://mvnrepository.com/artifact/org.springframework/spring-context -->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId>
        <version>${spring-version}</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/org.springframework/spring-beans -->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-beans</artifactId>
        <version>${spring-version}</version>
    </dependency>
    <dependency>
        <groupId>javax.inject</groupId>
        <artifactId>javax.inject</artifactId>
        <version>1</version>
    </dependency>
    ...

Спасибо.

A:
application.properties

Автоматически подключается в Spring Boot приложении, но так как у вас, не Spring Boot, вам необходимо явно подключить property файл. Делается это при помощи аннотации:

@PropertySource

В вашем классе

SpringBeansConfigurationInjector

добавьте следующее :

@PropertySource("aplication.properties")

или

@PropertySource("classpath:/путь_до_файла")

A: Всё, что нужно - это иметь в контексте бин типа PropertyPlaceholderConfigurer. Если у вас xml-конфигурация, то для этого есть специальный тег:
<context:property-placeholder
    location="classpath:META-INF/application.properties" />

А если java-конфигурация, то поможет аннотация @PropertySource, как уже написал @aleshka-batman


text:
Q: How to detect a player on a specific block(s) I'm making a map and I'm trying to separate players by building a wall when ever one crosses a certain point, but I can't seem to get the command block to detect when i'm on something and build a wall.
I want each person to go a seperate way

I realize I didn't give enough info so I made this image. The coordinates represent the blocks themselves not the air.

A: Note: I only noticied that it's the bedrock version as I was finishing this answer. Apologies if it does not work since I can't test myself. I read the wiki and it theoretically should work.

The execution is pretty simple. Since you didn't give me real valeus, I'll try to show it using your screenshot and will be considering the direction you are facing as north, which means foward will decrease Z and to the left will decrease X.

You want to execute as someone within the black grid range and 2-3 block above.
To do that, I'm going to be using the target selector with 'x' and 'dx' (as well for 'y' and z'). 'x' stands for the coordinates on the X axis and 'dx' stands for the distance, using the previus 'x' value
/execute as @a[x=purple.x,dx=3.9,z=purple.z,dz=1.4,y=purple.y+1,dy=3] at @s run fill blue.x blue.y+1 blue.z darkblue.x darkblue.y darkblue.z minecraft:block

Consider color.axis the coordinates for the painted block and y+1 is the block Y axis +1 (So for instance, if it is 6, you will use 7)
This will build a wall made of 'block' starting from the block above the light blue color and until the dark blue one, filling up the whole area.
Apply the same setup on the other side.

Considering the coordinates given, this will be the command:
/execute as @a[x=-44,dx=2.4,z=223,dz=-3.4,y=5,dy=3] at @s run fill -40 5 223 -40 8 219 torch

Change "torch" to any block you want.

A: First, go to settings and turn on show coordinates.
Second, go to the block you want it to detect players on and then place your persons legs on that block and write down your coordinates.
Third, type in this command with the coordinates you got in the place the random coordinates I chosen like this :  /testfor @p 1200 360 -100.


text:
Q: RerfreshControl background does not cover I'm trying to customize the refreshControl in my tableView. however when i pull down it seem to show a little white margin of the backgroundColor. Is there anyway beside changing backgroundColor to the same as refreshColor to avoid this? since by changing background Color it will be seen when i pull up and this won't be nice looking?
    reloadControl.tintColor = UIColor.blackColor().colorWithAlphaComponent(0.4)
    reloadControl.backgroundColor = UIColor.redColor()
    reloadControl.tintColor = UIColor.whiteColor()
    self.tableView.addSubview(reloadControl)


text:
Q: Word wrap not right on Windows Phone I don't know if you care yet (or at all) but sometimes the word wrapping or simply the right column is wrong in Internet Explorer on a Windows Phone:

Note the RHS of the displayed text is not the RHS of the display.

This is further up in the same question.
This problem appears on a number of SE sites.
I should mention the best solution I've noticed so far is to rotate my phone and look at the landscape ratio. (And there are differing results as you zoom in and out, but this is the default scenario it returns to eventually.) Note also it really has the wrong idea of my screen width, which is why I have been able to shift the display left before taking these screen grabs - i.e. there's no problem on the LHS, I've just been able to "scroll right" to highlight I cannot see the RHS text.
(I added this question on my phone without the help of the toolbar and no preview. I've since edited it from a computer.)


text:
Q: Radius of a power series We have the power series:
$$
\sum_{n = 0}^{\infty}a_nz^n
$$
The radius of convergence of that series is $R$.
Now I need to find the radius of convergence for:
$$
\sum_{n = 0}^{\infty}a_nc^nz^n, \quad c \in \mathbb C
$$
The answers say that the new series converges for:
$$
|cz| < R
$$
And then says that because it holds that:
$$
|cz| = |c||z|
$$
We can conclude that the radius of convergence of the new series is: (for $|c| \neq 0$)
$$
R' = \frac{R}{|c|}
$$
Why is the new radius not $R$, as we said that $|cz| < R$? Why do they go ahead and find $R'$?

A: $\sum a_nz^n$ converges if $|z|<R$ and diverges if $ |z|>R$.
thus
$\sum a_n(cz)^n$ converges if $|cz|<R $
or $|z|<\frac{R}{|c|}$
and diverges if $|cz|>R$ or $|z|>\frac{R}{|c|}$
hence, by definition, $$R'=\frac{R}{|c|}$$
$c $ is a real or a complex $ (\ne 0)$.


text:
Q: View animation massive lag I've written a method that animate an ImageView when it is clicked.
It works, but between the start of the method and the moment it actually animates the view I have a delay that goes from 30ms to 4000ms. The very first time I click the image it take 30-50ms, the subsequent times it take 1000-4000ms to start the animation.
I'm trying to make a chain of animations, so face_out calls face_in in its onAnimationEnd callback. face_in has a variable delay, taken from the duration of the sound that play when face_out finishes. Also, if choise is a particular int, before face_in, parkour_anim is called. This animation just rotate the imageview by 360 degrees, the on it's onAnimationEnd it reset the rotation, but it doesn't work well.
private void onFaceClicked() {
    Log.d("CLICK", "Face clicked");

    final long startTime = System.currentTimeMillis();
    vibrator.vibrate(50);
    choise = 0;

    if(period == Constants.A){
        choise = new Random().nextInt(Constants.CHOISES_A-1);
    }else{
        if (period == Constants.B){
            choise = new Random().nextInt(Constants.CHOISES_B-1);
        }
        else{
            choise = 0;
        }
    }

    ivFace.setEnabled(false);

    //FACE_OUT
    ivFace.animate().scaleX(2f).scaleY(2f)
    .setDuration(Constants.FACE_OUT_ANIMATION)
    .setInterpolator(new AnticipateOvershootInterpolator())
    .setListener(new AnimatorListener() {
        @Override public void onAnimationStart(Animator animation) {
            Log.d("ANIM", "Face_out started after: " + (System.currentTimeMillis()-startTime));
            imageViewAnimatedChange(ivFace,facesDrawables[choise]);
        }
        @Override public void onAnimationRepeat(Animator animation) {}
        @Override public void onAnimationEnd(Animator animation) {
            Log.d("ANIM", "Face_out ended after: " + (System.currentTimeMillis()-startTime));

            if(choise == Constants.PARKOUR){
                Log.d("ANIM", "Parkour_anim started after: " + (System.currentTimeMillis()-startTime));
                ivFace.animate().rotationBy(360f).setDuration(sounds[choise].durationInMillis).setListener(new AnimatorListener() {
                    @Override public void onAnimationStart(Animator animation) {}
                    @Override public void onAnimationRepeat(Animator animation) {}
                    @Override public void onAnimationEnd(Animator animation) {ivFace.setRotation(0);}
                    @Override public void onAnimationCancel(Animator animation) {}
                });
            }
            soundPool.play(sounds[choise].soundId, 1, 1, 1, 0, 1);
            //FACE_IN
            ivFace.animate().scaleX(1f).scaleY(1f)
            .setDuration(Constants.FACE_OUT_ANIMATION)
            .setStartDelay(sounds[choise].durationInMillis + 100)
            .setInterpolator(new AnticipateOvershootInterpolator())
            .setListener(new AnimatorListener() {

                @Override
                public void onAnimationStart(Animator animation) {
                    Log.d("ANIM", "Face_in started after: " + (System.currentTimeMillis()-startTime));
                    imageViewAnimatedChange(ivFace, facesDrawables[3]);
                }

                @Override public void onAnimationRepeat(Animator animation) {}
                @Override public void onAnimationEnd(Animator animation) {
                    Log.d("ANIM", "Face_in ended after: " + (System.currentTimeMillis()-startTime));

                    ivFace.setEnabled(true);
                }

                @Override public void onAnimationCancel(Animator animation) {}
            });
        }

        @Override public void onAnimationCancel(Animator animation) {}
    });

}

What can cause such massive delay?
Update: The rootview contains other views that are animated as well (variable number, between 3 and 5).


text:
Q: How to make the Route53 domain point to the newly created instance in AWS I have 2 AWS accounts , say A and B. I have to move the ec2 instances and domains & records to the account B.
I was able to make AMI for account A and successfully launched it in account B. I was ablee to move the domains also to account B and made new records in account B.
But the domain still points to the account A instance. Is there any delay in the process and by how much. Thanks in advance.

A: You need to update the name servers (NS records) of the new AWS account route53 to your domain registrar (Basically from where you purchased the domain)
Once that is done, wait for sometime now your domain will work as per the domain settings in your new account.

A: It depends on the TTL value of records in your DNS. For example, if it is 3600 means need to wait 1 hour to update.


text:
Q: Fibers of a dominant complex algebraic function are generically homeomorphic this is my first post so I apologize in advance for any formatting issues or community guidelines I might have overlooked.
I have come across the following basic question concerning complex algebraic varieties.
Let $X$ be a complex algebraic variety and $f:X \to\mathbb{C}$ a dominant morphism. Then does there exist a dense open set $U\subset \mathbb{C}$ such that the fibers $f^{-1}(t)$ for all $t\in U$ are all homeomorphic?
I believe the answer involves Whitney stratifications, a topic I am woefully ignorant of. I'm currently reading a bit on this subject, but I would appreciate a direct answer to my question or at least confirmation that I am headed in the right direction.
Here's what I tried:
Pick a stratification of $X$, a filtration by closed subsets  $F_{i-1}\subset F_{i}$ such that the complements $S_i=F_{i}\backslash F_{i-1}$ are smooth. First, remove the images of all strata with zero dimensional image under $f$, i.e. if $f\vert_{S_i}$ is not dominant onto $\mathbb{C}$, then remove $f(S_i)$ from $\mathbb{C}$.
For all the remaining strata, remove the critical values of $f\vert_{S_i}$. Now for any $t\in U$, the remaining dense open subset of $\mathbb{C}$ after we've removed all those points, we see that the fibers $f^{-1}(t)\cap S_i$ are all diffeomorphic. Thus, $f^{-1}(t)$ is always a union of the same diffeomorphic pieces.
And that's where I got stuck - I could not find a way to reason that these pieces glue in the 'same way' each time to give homeomorphic fibers. Indeed, it seemed unlikely without any further condition on the stratification, which is why I was reminded of Whitney stratifications.
Thank you!


text:
Q: D3 line chart line selected on hoover even if opacity of the line is zero I have a D3 line chart in my application and on hovering on the line a text is shown above the line displaying the line name. After that I had implemented a legend alongside with the chart and legend allows making lines appear and disappear upon clicking on legend item. My Sample code is given below. But now it has caused a problem like this. As now I'm setting the opacity of the line which was selected from legend to zero, the line gets disappeared. But if I hover in the area where the line was earlier still it shows the on hover text. Does anyone know a solution to avoid this problem.
You can see this issue by clicking on both items in the legend, Then all lines get disappeared. But if you move the mouse over the chart, where the lines were earlier, you will see that text will show on hovering
Example : https://jsfiddle.net/yasirunilan/ymavtsbj/4/
var data = [{
    name: "USA",
    values: [{
        date: "2000",
        price: "100"
      },
      {
        date: "2001",
        price: "110"
      },
      {
        date: "2002",
        price: "145"
      },
      {
        date: "2003",
        price: "241"
      },
      {
        date: "2004",
        price: "101"
      },
      {
        date: "2005",
        price: "90"
      },
      {
        date: "2006",
        price: "10"
      },
      {
        date: "2007",
        price: "35"
      },
      {
        date: "2008",
        price: "21"
      },
      {
        date: "2009",
        price: "201"
      }
    ]
  },
  {
    name: "Canada",
    values: [{
        date: "2000",
        price: "100"
      },
      {
        date: "2001",
        price: "110"
      },
      {
        date: "2002",
        price: "145"
      },
      {
        date: "2003",
        price: "241"
      },
      {
        date: "2004",
        price: "101"
      },
      {
        date: "2005",
        price: "90"
      },
      {
        date: "2006",
        price: "10"
      },
      {
        date: "2007",
        price: "35"
      },
      {
        date: "2008",
        price: "21"
      },
      {
        date: "2009",
        price: "201"
      }
    ]
  }
];
var width = 500;
var height = 300;
var margin = 50;
var duration = 250;

var lineOpacity = "0.25";
var lineOpacityHover = "0.85";
var otherLinesOpacityHover = "0.1";
var lineStroke = "1.5px";
var lineStrokeHover = "2.5px";

var circleOpacity = '0.85';
var circleOpacityOnLineHover = "0.25"
var circleRadius = 3;
var circleRadiusHover = 6;

/* Format Data */
var parseDate = d3.timeParse("%Y");
data.forEach(function(d) {
  d.values.forEach(function(d) {
    d.date = parseDate(d.date);
    d.price = +d.price;
  });
});

/* Scale */
var xScale = d3.scaleTime()
  .domain(d3.extent(data[0].values, d => d.date))
  .range([0, width - margin]);

var yScale = d3.scaleLinear()
  .domain([0, d3.max(data[0].values, d => d.price)])
  .range([height - margin, 0]);

var color = d3.scaleOrdinal(d3.schemeCategory10);

/* Add SVG */
var svg = d3.select("#chart").append("svg")
  .attr("width", (width + margin) + "px")
  .attr("height", (height + margin) + "px")
  .append('g')
  .attr("transform", `translate(${margin}, ${margin})`);

/* Add line into SVG */
var line = d3.line()
  .x(d => xScale(d.date))
  .y(d => yScale(d.price));

let lines = svg.append('g')
  .attr('class', 'lines');

lines.selectAll('.line-group')
  .data(data).enter()
  .append('g')
  .attr('id', d => d.name.replace(/\s+/g, '') + "-line")
  .attr('class', 'line-group')
  .on("mouseover", function(d, i) {
    svg.append("text")
      .attr("class", "title-text")
      .attr("font-weight", "bold")
      .style("fill", color(i))
      .text(d.name)
      .attr("text-anchor", "middle")
      .attr("x", (width - margin) / 2)
      .attr("y", -30);
  })
  .on("mouseout", function(d) {
    svg.select(".title-text").remove();
  })
  .append('path')
  .attr('class', 'line')
  .attr('d', d => line(d.values))
  .style('stroke', d => color(d.name))
  .style('opacity', lineOpacity)
  .on("mouseover", function(d) {
    d3.selectAll('.line')
      .style('opacity', otherLinesOpacityHover);
    d3.selectAll('.circle')
      .style('opacity', circleOpacityOnLineHover);
    d3.select(this)
      .style('opacity', lineOpacityHover)
      .style("stroke-width", lineStrokeHover)
      .style("cursor", "pointer");
  })
  .on("mouseout", function(d) {
    d3.selectAll(".line")
      .style('opacity', lineOpacity);
    d3.selectAll('.circle')
      .style('opacity', circleOpacity);
    d3.select(this)
      .style("stroke-width", lineStroke)
      .style("cursor", "none");
  });

/* Add circles in the line */
lines.selectAll("circle-group")
  .data(data).enter()
  .append("g")
  .attr('id', d => d.name.replace(/\s+/g, '') + "-circle")
  .style("fill", d => color(d.name))
  .selectAll("circle")
  .data(d => d.values).enter()
  .append("g")
  .attr("class", "circle")
  .on("mouseover", function(d) {
    d3.select(this)
      .style("cursor", "pointer")
      .append("text")
      .attr("class", "text")
      .text(`${d.price}`)
      .attr("x", d => xScale(d.date) + 5)
      .attr("y", d => yScale(d.price) - 10);
  })
  .on("mouseout", function(d) {
    d3.select(this)
      .style("cursor", "none")
      .transition()
      .duration(duration)
      .selectAll(".text").remove();
  })
  .append("circle")
  .attr("cx", d => xScale(d.date))
  .attr("cy", d => yScale(d.price))
  .attr("r", circleRadius)
  .style('opacity', circleOpacity)
  .on("mouseover", function(d) {
    d3.select(this)
      .transition()
      .duration(duration)
      .attr("r", circleRadiusHover);
  })
  .on("mouseout", function(d) {
    d3.select(this)
      .transition()
      .duration(duration)
      .attr("r", circleRadius);
  });

/* Add Axis into SVG */
var xAxis = d3.axisBottom(xScale).ticks(5);
var yAxis = d3.axisLeft(yScale).ticks(5);

svg.append("g")
  .attr("class", "x axis")
  .attr("transform", `translate(0, ${height-margin})`)
  .call(xAxis);

svg.append("g")
  .attr("class", "y axis")
  .call(yAxis)
  .append('text')
  .attr("y", 15)
  .attr("transform", "rotate(-90)")
  .attr("fill", "#000")
  .text("Total values");

var keys = []

// Add the Legend
var legend = d3.select("body").selectAll(".legend")
  .data(data.map(d => d.name))
  .enter().append("font")
  .attr("class", "legend") // style the legend
  .style("color", color)
  .style("margin-left", 10 + "px")
  .style("padding-left", 10 + "px")
  .html(d => d)

d3.selectAll(".legend")
  .on("click", function(d) {

    keys.includes(d) ?
      keys.splice(keys.indexOf(d), 1) :
      keys.push(d)

    d3.select(this).style("opacity", () => keys.includes(d) ? .5 : 1)

    d3.select("#" + d.replace(/\s+/g, '') + "-line")
      .transition().duration(100)
      .style("opacity", () => keys.includes(d) ? 0 : 1);
    d3.select("#" + d.replace(/\s+/g, '') + "-circle")
      .transition().duration(100)
      .style("opacity", () => keys.includes(d) ? 0 : 1);
  })

A: You can set the CSS pointer-events to none in order to disable all mouse interactions and the set it to auto when you change the opacity back to 1 to enable them.
You can do it using this line:
.style("pointer-events", () => keys.includes(d) ? "none" : "auto");
Working demo: JsFiddle
Alternatively you can replace the lines that sets the opacity and the pointer-events by just setting the display css property like so:
.style("display", () => keys.includes(d) ? "none" : "inline");

Working demo: JsFiddle


text:
Q: Sharepoint Fetch data I have sharepoint list with thousand data. If i execute query in caml query builder than it takes a second to fetch data. and when i am trying to fectch data in sharepoint with spservice / c# code than it takes 15 seconds to execute that query. Why this much is diffrent. Can any one suggest.
I am using SPService js to fetch data.The code that I have used is:
var querySkill = "<Query><Where><And><Eq><FieldRef Name='User_x003a_ID' /><Value Type='Lookup'>"+rowUserId+"</Value></Eq><And><Eq><FieldRef Name='Role_x003a_ID' /><Value Type='Lookup'>"+rowRoleId+"</Value></Eq><And><Eq><FieldRef Name='Skill_x0020_Category_x003a_ID' /><Value Type='Lookup'>"+rowCategoryId+"</Value></Eq><Eq><FieldRef Name='Skill_x0020_Group_x003a_ID' /><Value Type='Lookup'>"+rowGroupId+"</Value></Eq></And></And></And></Where></Query>"
        var camlViewFieldsSkill = "<ViewFields><FieldRef Name='Fulfillment' /></ViewFields>";
        var groupPer;
        var groupArray = new Array();
        $().SPServices({
            operation: "GetListItems",
            async: false,
            listName: "User Skills",
            CAMLQuery: querySkill,
            CAMLViewFields: camlViewFieldsSkill,
            completefunc: function (xData, Status) {
                $(xData.responseXML).find("z\\:row, row").each(function () {
                  var skillId = $(this).attr("ows_ID");
                  var skillName=$(this).attr("ows_Skill").split("#")[1];
                  var fulfilment=$(this).attr("ows_Fulfillment");
                    $(subGridSkill).jqGrid('addRowData', skillId, { id: skillId, skillid: skillId, skill:skillName, skillfulfillment: fulfilment });

                });

            }
        });

Even if i am writing server side code than also it takes 15-20 seconds to fetch data. Plz help
Regards
Priya

A: Not sure why in CAML builder your query is fast. Something that will speed up the query is to index the fields you are using to search:
http://msdn.microsoft.com/en-us/library/ff798465.aspx

A: Here is a link explaining the difference between using SPServices and CSOM which also includes both their PROS and CONS.
Maybe CAML builder uses RESTful webservices which might impact performance of your query and we all know that there are performance issues with javascript/jquery.
You might want to try converting to CSOM and check if it affects the performance of your code. Let me know if you need a sample code block and I'll gladly write one for you.


text:
Q: How to toggle the link in my case? I am trying to toggle a link  texts and content when user clicks the link.
I have something like
click me

title here

texts here...

 $('#link').on('click', function(e){
     e.preventDefault();
     $(this).text('isClicked');
     $('#items').empty().html("")
 })

When user click the link, the link text will become isClicked and the items html will be replaced with a image. However, if user clicks again, I want to see the link text changes back to click me and the items will hide the image and display the title and p tag contents again.
I am not sure how to accomplish this. Can anyone help me about it? Thanks a lot!

A: $('#link').on('click', function(e){
    e.preventDefault();
    if ($(this).text() == "isClicked") {
        $(this).text("click me");
        .. etc
    } else {
        $(this).text('isClicked');
        $('#items').empty().html("")
    }
});

Like I said in my comment, use a condition like this. Simple and effective.

A: One way you could do it:
$('#link')
//  Set data attribute to hold original text
.data('primeText', $('#link').text())
//  set click event using jQuery1.73+
.on('click', function(e) {
    e.preventDefault(); // prevents going to link, not needed if you set link href to "javascript:void(0)"
    //  begin setting text, within is a inline-if statement testing current text against prime text
    $(this).text($(this).text() == $(this).data('primeText') ? 'isClicked' : $(this).data('primeText'));
});

Another way, if you were working with more than one, like using a class name instead of ID:
$('.link')
//  jQuery's .each method allows you to do things to each element in an object group
.each(function(i) { $(this).data('primeText', $(this).text()); })
//  again, calling click method
.on('click', function(e) {
    $(this).text($(this).text() == $(this).data('primeText') ? 'isClicked' : $(this).data('primeText'));
});

Examples

A: You can add a dummy class to the link and work with that condition
//Have a dummy class added to the link and toggle it on click
 $('#link').on('click', function(e){
     e.preventDefault();
     var $this = $(this),
         $textDiv = $('#items'),
         $imageDiv = $('#image')
     if($this.hasClass('clicked')) {
         // remove the class
         $this.removeClass('clicked');
         // change the text
         $this.text('click me');
         // Hide image
         $imageDiv.addClass('hide');
         // show text
          $textDiv.removeClass('hide');

     } else {
         // remove the class
         $this.addClass('clicked');
         // change the text
         $this.text('isClicked');
         // Show image
         $imageDiv.removeClass('hide');
         // Hide text
          $textDiv.addClass('hide');
     }
 });

Check Fiddle
You can also chain the methods applied on the same element.

A: What about using  a CSS approach?
Your HTML would stay the same:
click me

title here

texts here...

But we can use .toggleClass() here to make our lives easier
$('#link').on('click', function(e){
     e.preventDefault();
     $(this).text('isClicked');
     $('#items').toggleClass('display-image');
 })

The CSS would look like:
#items.display-image > h1,
#items.display-image > p,
{
     visibility:hidden;
}
#items.display-image{
     background-image:url("/images/image.png");
}

This way, you don't have to worry about removing things and .toggleClass handles their visibility.
You might have to do additional styling to get the image to work properly, or you may consider adding another element to contain the image and you can just set its visibility or display property

A: Try something like this:
HTML:
click me

title here

texts here...

CSS:
img {
    display: none;
}

JavaScript:
$('#link').off().on('click', function(e) {
    e.preventDefault();
    if($('#items > img').is(':visible')) {
        $(this).text('click me');
        $('#items > img').hide();
        $('#items > .text-item').show();
    } else {
        $(this).text('isClicked');
        $('#items > .text-item').hide();
        $('#items > img').show();
    }
 });

Fiddle

A: You can try to store the value in a var and then toggle with on off in functions themselfs;
 var initialState = $('#items').html(),
 functionBla(e) {
     e.preventDefault();
     $(this).text('isClicked');
     $('#items').empty().html("")
     $('#link').off('click').on('click', functionCla);
 },
 functionCla(e) {
     e.preventDefault();
     $(this).text('click');
     $('#items').html(initialState);
     $('#link').off('click').on('click', functionBla);
 };

 $('#link').on('click', functionBla);

A: You can do it like,
$('#link').on('click', function(e){
 e.preventDefault();
 $(this).text('isClicked');
 $('#items').children().toggle();
 var img=$('#items img');
 if(img.length>0){
     img.remove();
 }
 else{
     $('#items').append("");
    $(this).text('Click me');
 }

})


text:
Q: How to set Fragments To Android Tabbed Activity I create new tabbed activity in android and I want to set special fragment for each tabs but I don't know how can I do it!
I searched on net but nothing found!
I want to add X_fargment layout to section 2 and make fragment class for each fragment! Can anybody help me?
public class MainActivity extends ActionBarActivity implements ActionBar.TabListener {

    SectionsPagerAdapter mSectionsPagerAdapter;
    ViewPager mViewPager;

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

        final ActionBar actionBar = getSupportActionBar();
        actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);

        mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());

        mViewPager = (ViewPager) findViewById(R.id.pager);
        mViewPager.setAdapter(mSectionsPagerAdapter);
        mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
            @Override
            public void onPageSelected(int position) {
                actionBar.setSelectedNavigationItem(position);
            }
        });

        for (int i = 0; i < mSectionsPagerAdapter.getCount(); i++) {
            actionBar.addTab(actionBar.newTab().setText(mSectionsPagerAdapter.getPageTitle(i)).setTabListener(this));
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onTabSelected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
        // When the given tab is selected, switch to the corresponding page in
        // the ViewPager.
        mViewPager.setCurrentItem(tab.getPosition());
    }

    @Override
    public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {}

    @Override
    public void onTabReselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {}

    public class SectionsPagerAdapter extends FragmentPagerAdapter {

        public SectionsPagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            return PlaceholderFragment.newInstance(position + 1);
        }

        @Override
        public int getCount() {
            // Show 3 total pages.
            return 3;
        }

        @Override
        public CharSequence getPageTitle(int position) {
            Locale l = Locale.getDefault();
            switch (position) {
                case 0:
                return getString(R.string.title_section1).toUpperCase(l);
                case 1:
                return getString(R.string.title_section2).toUpperCase(l);
                case 2:
                return getString(R.string.title_section3).toUpperCase(l);
            }
            return null;
        }
    }

    public static class PlaceholderFragment extends Fragment {

        private static final String ARG_SECTION_NUMBER = "section_number";

        public static PlaceholderFragment newInstance(int sectionNumber) {
        PlaceholderFragment fragment = new PlaceholderFragment();
        Bundle args = new Bundle();
        args.putInt(ARG_SECTION_NUMBER, sectionNumber);
        fragment.setArguments(args);
        return fragment;
        }

        public PlaceholderFragment() {}

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
            View rootView = inflater.inflate(R.layout.fragment_main, container, false);
            return rootView;
        }
    }
}

A: you can create FragmentTabHost programatically in code instead of xml.. It may help otherwise this tutorial may help.http://maxalley.wordpress.com/2013/05/18/android-creating-a-tab-layout-with-fragmenttabhost-and-fragments/

A: You can use the ViewPager provided by google in the support version 4 library, it uses fragments as tabs and provids a swipe animation between them, check out this link:
ViewPager | Android Developers


text:
Q: Getting errors of kind invalid use of incomplete type 'struct node' #include<iostream>
#include<string>
#include<algorithm>
using namespace std;
class sequence{
   struct node{
       string name;
       string data;
       struct node * next;};
    sequence();
   ~sequence();
    void print(struct node *);
    struct node *sortlist(struct node *);
    struct node *deletenode(struct node *, string);
    struct node *searchnode(struct node *, string);
    struct node *insertnode(struct node *, string);};

void print(struct node *st){ //method to print the linked list
while(st!=0){
    cout<<st->data<<endl;
    st=st->next;}}

struct node *deletenode(struct node *st, string x){//to delete a node containing element x
    struct node *s1=st, *t,*ptr;
    string m=x;
    ptr=st;
    if (s1==0)// if linked list is empty {
        cout<<"linkedlist empty"<<endl;}
    else if(s1->next==0)//if linked list contains only one element
    {
        if(s1->data==m)
        {
        free(s1);
        s1=0;}
        else
        cout<<m<<"is not in the list."<<endl;
    }
    else if(s1->next!=0&&s1->data==m)
    {
        t=s1->next;
        free(s1);
        s1=t;

     }
    else
    {
        while(s1->data!=m&&s1->next!=0)
        {
            t=s1;
            s1=s1->next;
        }
        if(s1->data==m)
        {

            t->next=s1->next;
            free(s1);
            s1=t;
        }
        else
        cout<<m<<"is not in the list."<<endl;

    }
    return(ptr);
}

int main(){

sequence obj=new sequence();
struct node *root1, *root2, *root3, *s, *p,*t;
string v;
root1= new node;
root2= new node;
root3= new node;
s=root1;
root1->next=root2;
root2->next=root3;
root3->next=0;
root1->data="man";//data in the nodes of linked list
root2->data="aan";
root3->data="van";
root1->name="1";
root2->name="2";
root3->name="3";
    cout<<"enter the string :";
    cin>>v;
    cout<<endl;
    p=obj.deletenode(s, v);// delete node function call
    obj.print(p);

return(0);}

Problem 1: when i am running this code, it executes with bug in deletenode method where it is not deleting the first element of linked list but deleting every other element.Please enlighten me where i am getting wrong in the code.
Problem 2: I was trying to create a class with all above mention methods, a constructor and a destructor but when i am running this code i am getting errors like "invalid use of incomplete type 'struct node'".I am new to the concept of classes kindly guide me where i am getting wrong in this code.
Apologies for no proper formatting.
looking for a positive reply.

A: well you are not supposed to define a whole Structure within the class definition
, instead of doing this define the structure publicly and include its instance within the class . Hope this Helps
#include<iostream>
#include<string>
#include<algorithm>
using namespace std;
struct node{             //structure definition outside the class
   string name;
   string data;
   struct node * next;
};
class sequence{

node node1;        //define a node variable
sequence();
~sequence();
void print(struct node *);
struct node *sortlist(struct node *);
struct node *deletenode(struct node *, string);
struct node *searchnode(struct node *, string);
struct node *insertnode(struct node *, string);};enter code here


text:
Q: Trying to mount a folder from school's network This is what I'm told to do...
mount -t smbfs -o username=USERNAME,port=9900 \ //localhost/USERNAME /YOUR_LOCAL_MOUNT_POINT

I'm new to Linux so I'm sure I'm not doing this right but I can't figure out what the right syntax is for the last part.  I tried...
/home/andyd/documents/school

for /YOUR_LOCAL_MOUNT_POINT
that didn't work


text:
Q: how to use diffdate function in mysql using variables CREATE DEFINER=`root`@`localhost` PROCEDURE `bill`(subid int(10), uprice float, sd date, ed date)
BEGIN
declare numberofdays int;
declare totalprice float;

set numberofdays = datediff(ed,sd);
set totalprice= numberofdays*uprice;

insert into invoice (subscriptionid,price_perunit,numberofdays,totalprice)
values (subid, uprice,numberofdays,totalprice);

A: Your code (syntax) is correct. You might have a problem with variable and field names, try to use different names, e.g. -
CREATE DEFINER = root@localhost PROCEDURE bill (subid int(10), uprice float, sd date, ed date)
BEGIN
  DECLARE var_numberofdays int;
  DECLARE var_totalprice float;

  SET var_numberofdays = DATEDIFF(ed, sd);
  SET var_totalprice = var_numberofdays * uprice;

  INSERT INTO invoice (subscriptionid, price_perunit, numberofdays, totalprice)
    VALUES (subid, uprice, var_numberofdays, var_totalprice);

  ...
END;


text:
Q: Algorithm negotiation fail Jsch with OpenSSH Can someone tell me how server or client part can be configured to have common cipher?
It throws com.jcraft.jsch.JSchException: Algorithm negotiation fail
Server side uses OpenSSH and the log shows:
no matching cipher found: client aes128-cbc,blowfish-cbc,3des-cbc server aes128-ctr,aes192-ctr,aes256-ctr,aes128-gcm@openssh.com,aes256-gcm@openssh.com,chacha20-poly1305@openssh.com
JSCH version used is 0.1.43, I have tried to run it with java 8 and have updated JCE jars(as suggested in other similar posts) but without success


text:
Q: How do I remove an array of referenced Objects when deleting the main document? This is my MongoDB schema:
const MenuSchema = new Schema({
  name: {
    type: String,
    require: true
  },
  category: {
    type: String,
    require: true
  },
  description: {
    type: String,
    require: true
  },
  image: {
    type: String,
  },
  caterer: {
    type: Schema.Types.ObjectId,
    ref: 'User'
  },
  products: [{
    type: Schema.Types.ObjectId,
    ref: 'Product'
  }]
}, { timestamps: true })

const ProductSchema = new Schema({
  name: {
    type: String,
    require: true
  },
  category: {
    type: String,
    require: true
  },
  description: {
    type: String,
    require: true
  },
  image: {
    type: String,
  },
  price: {
    type: String
  }
}, { timestamps: true })

What I'm wondering - is how I can delete the array of products, at the same time as I delete the main "Menu" document? When I remove the Menu, I can also assume that the products belonging to the menu should be removed.
At the moment this is how I remove the menu (and tried to remove its products):
await Menu.findOneAndDelete({ _id: req.params.menu_id }, (err, response) => {
      if (err) {
        console.error(err);
      }
      Product.remove({ _id: { $in: req.body.products }}, (err, res) => {
        if (err) {
          console.error(err);
        }
        console.log('Deleted products');
      });
    });

However, the products do not get removed. Any suggestions?

A: Try This It works for Me.
await Menu.findOneAndDelete({ _id: req.params.menu_id }, (err, response) => {
  if (err) {
    console.error(err);
  }
  Product.remove({ _id: { $in: response.products }}, (err, res) => {
    if (err) {
      console.error(err);
    }
    console.log('Deleted products');
  });
});

A: Mongoose provides a pre and post middleware on your schema. Which means you can delete all the referenced documents before or after you do an operation on the current schema.
Read more here.
Here's an example, inside your schema add this:
const MenuSchema = new Schema({
  name: {
    type: String,
    require: true
  },
  category: {
    type: String,
    require: true
  },
  description: {
    type: String,
    require: true
  },
  image: {
    type: String,
  },
  caterer: {
    type: Schema.Types.ObjectId,
    ref: 'User'
  },
  products: [{
    type: Schema.Types.ObjectId,
    ref: 'Product'
  }]
}, { timestamps: true })

const ProductSchema = new Schema({
  name: {
    type: String,
    require: true
  },
  category: {
    type: String,
    require: true
  },
  description: {
    type: String,
    require: true
  },
  image: {
    type: String,
  },
  price: {
    type: String
  }
}, { timestamps: true })

MenuSchema.post('remove', removeProducts);

function removeProducts(doc) {
   Products.remove({_id: { $in: doc.products}})
}

Assuming Products is the name of your model.

A: You can use post schema hooks of mongoose as below
schema.post('remove', function(doc) {
  console.log('%s has been removed', doc._id);
});

Mongoose Post Hook
But the best approach is to use transactions to execute multiple operations on the database as below.
let session = null;
db.startSession()
.then((_session) =>{
    session = _session;
    session.startTransaction();
    return Menu.deleteOne({ _id: req.params.menu_id });
})
.then(()=> Product.deleteMany({ _id: { $in: req.body.products }}))
.then(()=>{
    session.commitTransaction();
})
.catch((err)=>{
    session.abortTransaction()
    return handleError(err);
})

Mongoose Transactions


text:
Q: MySQL limiting within a LEFT JOIN Hi so i have a database with the multiple tables with different records like so,
- table_1
    - student_name
    - student_id
    - id
    - note
    - ...

- table_2
    - id
    - leave
    - ...

leave currently contains the records of all the days the student has taken day off.
sample data for table_2 as requested

id
leave
...

675
2011-05-04
...

675
2012-04-15
...

675
2021-06-23
...

345
2019-10-14
...

345
2011-04-05
...

345
2019-02-13
...

So my question is how do i LEFT JOIN the tables and return the last leave date for the student instead of fetching all the leave date's for that particular student.
here's the current output that i'm getting

name
id
note
last absent
...

John Doe
675
good student
2011-05-04
...

John Doe
675
good student
2012-04-15
...

John Doe
675
good student
2021-06-23
...

Jack Sparrow
345
average student
2019-10-14
...

Jack Sparrow
345
average student
2019-10-14
...

Jack Sparrow
345
average student
2019-02-13
...

Ryan Reynolds
567
below average student
2011-07-22
...

Here is my expected output.

name
id
note
last absent
...

John Doe
675
good student
2021-06-23
...

Jack Sparrow
345
average student
2019-10-14
...

Ryan Reynolds
567
below average student
2011-07-22
...

All help is appreciated and thanks in advance.

A: As Martin already commented, you need to use an aggregate query. Since dates are effectively ordered lexicographically, the most recent date in a set of dates is its maximum. Therefore, you need to use the MAX() aggregator. Since you want to get the most recent date per student, you need to group the query by student. And since MySQL usually does not want you to print columns that are not in the GROUP BY clause, you'll need to add all columns from TABLE_1 to that clause. This should do what you want:
SELECT TABLE_1.NAME, TABLE_1.ID, TABLE_1.NOTE, MAX(TABLE_2.LEAVEDATE) AS last_absent
FROM TABLE_1 LEFT JOIN TABLE_2 ON TABLE_1.ID = TABLE_2.ID
GROUP BY TABLE_1.ID, TABLE_1.NAME, TABLE_1.NOTE;

A: SELECT Distinct table_1.Id, table_1.name,table_1.notes,MAX(table_2.leavedate)
AS Latestleavedate
FROM Employeedetails table_1 JOIN Leavedetails table_2 ON table_1.Id=table_2.Id
GROUP BY table_1.Id, table_1.name,table_1.notes;

Here I have used the MAX function to get the latest leave details from the table_2 and then I have grouped this by Id, name, notes.


text:
Q: Get access to created class object from another class ViewController1.h
@interface ViewController : UIViewController
@property AVAudioPlayer *audioPlayer;
@end

ViewController1.m
@synthesize audioPlayer;
...
audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path] error:NULL];
[audioPlayer play];

How can I stop the music from method in class ViewController2?

A: Use an NSNotification:
Put this where the user clicks stop music in ViewController2:
[[NSNotificationCenter defaultCenter] postNotificationName:@"stopMusic" object:nil];

and in ViewController1 should have this:
-(void)viewDidLoad:
{
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(stopTheMusic:) name:@"stopMusic" object:nil];
}

-(IBAction)stopTheMusic:(id)sender {
        [audioPlayer stop];
}

Good Luck!


text:
Q: Comparing 2 GPS location data files to find if any location from one file is within a specified elliptical region of a location from another I have 2 CSV files with GPS coordinates. I want to check if there are any locations in the first file which are inside a specified elliptical region surrounded by each location in the 2nd file. The major axis , minor axis and major axis bearing(angle) is given in the 2nd file for each location coordinates. For start I have plotted the points from both files in an ArcMap document where I can see red dots as first file locations and green dots as 2nd file locations.
For example if the coordinates of one location in 2nd file is 39.6145,-89.7823 (latitude(h), longitude(k)) and the major axis(a) 1200 and minor axis(b) 400 and bearing(A) 114 degree, then I want the list of the instances in first file which falls inside that region
N.B its is basically solving (x,y) in following equation,

The image is basically the ellipse equation if you can't view it.
〖((x-h)  cosA+(y-k)  sin〖A)〗〗^2/a^2 +〖((x-h)  sinA-(y-k)  cosA)〗^2/b^2 ≤ 1
I am totally new in ArcGIS. I am also trying to do it in Python but want to know how to implement it in ArcGIS too. And both the files are pretty large, with millions of entries in both. So I would also like to know if it is too much time consuming in ArcGIS.


text:
Q: setretaininstance(true) doesn't retain its class members using headless fragment Android Studio 1.3 RC 3

Hello,
I am trying to retain state of my headless fragment RetainedFragment.java through contiguration changes.
Rotation of the devices works ok. However, the problem is in my MainFragment.java I startActivityResult(...) for a implicit activity (Opening gallary app) to view photos.
The RetainedFragment.java doesn't retain its class members, even though I have setRetainInstance(true) in onCreate() of RetainedFragment.java.
I have also tried using the onSavedInstanceState to saved the mDataInt to a bundle and retrieve it from the onActivityCreated method.
RetainedFragment.java is a headless fragment so doesn't contain any UI, its just used to keep and restore state.
The thing I can't understand, rotational changes work fine. Its only when I start a new implicit activity to start the gallary app.
The class member I am testing this is called mDataInt and I set its initial value to 101 when the class is instantiated. Then to 2015 in the onSavedInstanceState to retain that value when the RetainedFragment is re-created.
Many thanks for any suggestions,
public static class RetainedFragment extends Fragment {
    private static final String TAG = RetainedFragment.class.getSimpleName();

    private Integer mDataInt = 101;

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

        /* Ensure the data survives runtime configuration changes */
        setRetainInstance(true);

        if(savedInstanceState == null) {
            Log.d(TAG, "onCreate savedInstanceState == null - dataInt: " + mDataInt);
         }
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);

        mDataInt = 2015;
        Log.d(TAG, "onSavedInstanceState mDataInt: " + mDataInt);
        outState.putInt("DATAINT_KEY", mDataInt);
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        Log.d(TAG, "onActivityCreated mDataint: " + mDataInt);

        if(savedInstanceState != null) {
            Log.d(TAG, "onActivityCreated savedInstanceState != null - dataInt: " + savedInstanceState.getInt("DATATINT_KEY"));
        }
    }
}

A: I found the reason why this has a problem, and I would like to post here to hear from anyone who has some ideas about this.
Under developer options I had enabled Don't keep activities I have disabled this option. Now the application works as expected


text:
Q: How to create table in partition data in hive? drwxr-xr-x   - mgupta supergroup          0 2018-03-26 22:16 /kylin/retailer/qi_basket_brand_bucket_fact/_impala_insert_staging
drwxr-xr-x   - mgupta supergroup          0 2018-03-26 22:18 /kylin/retailer/qi_basket_brand_bucket_fact/product_hierarchy_type=CI
[mgupta@sjc-dev-binn01 ~]$ hadoop fs -ls /kylin/retailer/qi_basket_brand_bucket_fact/product_hierarchy_type=CI
Found 27 items
drwxr-xr-x   - mgupta supergroup          0 2018-03-26 22:16 /kylin/retailer/qi_basket_brand_bucket_fact/product_hierarchy_type=CI/month_id=201601
drwxr-xr-x   - mgupta supergroup          0 2018-03-26 22:16 /kylin/retailer/qi_basket_brand_bucket_fact/product_hierarchy_type=CI/month_id=201602
drwxr-xr-x   - mgupta supergroup          0 2018-03-26 22:16 /kylin/retailer/qi_basket_brand_bucket_fact/product_hierarchy_type=CI/month_id=201603
drwxr-xr-x   - mgupta supergroup          0 2018-03-26 22:16 /kylin/retailer/qi_basket_brand_bucket_fact/product_hierarchy_type=CI/month_id=201604
drwxr-xr-x   - mgupta supergroup          0 2018-03-26 22:16 /kylin/retailer/qi_basket_brand_bucket_fact/product_hierarchy_type=CI/month_id=201605
drwxr-xr-x   - mgupta supergroup          0 2018-03-26 22:16 /kylin/retailer/qi_basket_brand_bucket_fact/product_hierarchy_type=CI/month_id=201606
drwxr-xr-x   - mgupta supergroup          0 2018-03-26 22:16 /kylin/retailer/qi_basket_brand_bucket_fact/product_hierarchy_type=CI/month_id=201607
drwxr-xr-x   - mgupta supergroup          0 2018-03-26 22:16 /kylin/retailer/qi_basket_brand_bucket_fact/product_hierarchy_type=CI/month_id=201608
drwxr-xr-x   - mgupta supergroup          0 2018-03-26 22:17 /kylin/retailer/qi_basket_brand_bucket_fact/product_hierarchy_type=CI/month_id=201609
drwxr-xr-x   - mgupta supergroup          0 2018-03-26 22:17 /kylin/retailer/qi_basket_brand_bucket_fact/product_hierarchy_type=CI/month_id=201610
drwxr-xr-x   - mgupta supergroup          0 2018-03-26 22:17 /kylin/retailer/qi_basket_brand_bucket_fact/product_hierarchy_type=CI/month_id=201611
drwxr-xr-x   - mgupta supergroup          0 2018-03-26 22:17 /kylin/retailer/qi_basket_brand_bucket_fact/product_hierarchy_type=CI/month_id=201612
drwxr-xr-x   - mgupta supergroup          0 2018-03-26 22:17 /kylin/retailer/qi_basket_brand_bucket_fact/product_hierarchy_type=CI/month_id=201701
drwxr-xr-x   - mgupta supergroup          0 2018-03-26 22:17 /kylin/retailer/qi_basket_brand_bucket_fact/product_hierarchy_type=CI/month_id=201702
drwxr-xr-x   - mgupta supergroup          0 2018-03-26 22:17 /kylin/retailer/qi_basket_brand_bucket_fact/product_hierarchy_type=CI/month_id=201703
drwxr-xr-x   - mgupta supergroup          0 2018-03-26 22:17 /kylin/retailer/qi_basket_brand_bucket_fact/product_hierarchy_type=CI/month_id=201704
drwxr-xr-x   - mgupta supergroup          0 2018-03-26 22:17 /kylin/retailer/qi_basket_brand_bucket_fact/product_hierarchy_type=CI/month_id=201705
drwxr-xr-x   - mgupta supergroup          0 2018-03-26 22:17 /kylin/retailer/qi_basket_brand_bucket_fact/product_hierarchy_type=CI/month_id=201706
drwxr-xr-x   - mgupta supergroup          0 2018-03-26 22:17 /kylin/retailer/qi_basket_brand_bucket_fact/product_hierarchy_type=CI/month_id=201707
drwxr-xr-x   - mgupta supergroup          0 2018-03-26 22:18 /kylin/retailer/qi_basket_brand_bucket_fact/product_hierarchy_type=CI/month_id=201708
drwxr-xr-x   - mgupta supergroup          0 2018-03-26 22:18 /kylin/retailer/qi_basket_brand_bucket_fact/product_hierarchy_type=CI/month_id=201709
drwxr-xr-x   - mgupta supergroup          0 2018-03-26 22:18 /kylin/retailer/qi_basket_brand_bucket_fact/product_hierarchy_type=CI/month_id=201710
drwxr-xr-x   - mgupta supergroup          0 2018-03-26 22:18 /kylin/retailer/qi_basket_brand_bucket_fact/product_hierarchy_type=CI/month_id=201711
drwxr-xr-x   - mgupta supergroup          0 2018-03-26 22:18 /kylin/retailer/qi_basket_brand_bucket_fact/product_hierarchy_type=CI/month_id=201712
drwxr-xr-x   - mgupta supergroup          0 2018-03-26 22:18 /kylin/retailer/qi_basket_brand_bucket_fact/product_hierarchy_type=CI/month_id=201801
drwxr-xr-x   - mgupta supergroup          0 2018-03-26 22:18 /kylin/retailer/qi_basket_brand_bucket_fact/product_hierarchy_type=CI/month_id=201802
drwxr-xr-x   - mgupta supergroup          0 2018-03-26 22:18 /kylin/retailer/qi_basket_brand_bucket_fact/product_hierarchy_type=CI/month_id=201803
[mgupta@sjc-dev-binn01 ~]$ hadoop fs -ls /kylin/retailer/qi_basket_brand_bucket_fact/product_hierarchy_type=CI/month_id=201601
Found 3 items
drwxr-xr-x   - mgupta supergroup          0 2018-03-26 22:16 /kylin/retailer/qi_basket_brand_bucket_fact/product_hierarchy_type=CI/month_id=201601/company_sid=0
drwxr-xr-x   - mgupta supergroup          0 2018-03-26 22:16 /kylin/retailer/qi_basket_brand_bucket_fact/product_hierarchy_type=CI/month_id=201601/company_sid=38527
drwxr-xr-x   - mgupta supergroup          0 2018-03-26 22:16 /kylin/retailer/qi_basket_brand_bucket_fact/product_hierarchy_type=CI/month_id=201601/company_sid=__HIVE_DEFAULT_PARTITION__
[mgupta@sjc-dev-binn01 ~]$ hadoop fs -ls /kylin/retailer/qi_basket_brand_bucket_fact/product_hierarchy_type=CI/month_id=201601/company_sid=0
Found 1 items
-rw-r--r--   3 mgupta supergroup    2069014 2018-03-26 22:16 /kylin/retailer/qi_basket_brand_bucket_fact/product_hierarchy_type=CI/month_id=201601/company_sid=0/f9466a0068b906cf-6ace7f8500000049_294515768_data.0.parq
[mgupta@sjc-dev-binn01 ~]$

A: You may try the steps given below.
Approach 1

*

*Identify the schema (column names and types, including the partitioned column)

*Create a hive partitioned table (Make sure to add partition column & delimiter information)

*Load data into the partitioned table.(In this case, the loading file will not have partition column as you will hard-code it via the load command)
 create table <table_name> (col1 data_type1, col2 data_type2..)
 partitioned by(part_col data_type3)
 row format delimited
 fields terminated by '<field_delimiter_in_your_data>'

 load data inpath '/hdfs/loc/file1' into table <table_name>
 partition (<part_col>='201601');

 load data inpath '/hdfs/loc/file2' into table <table_name>
 partition (<part_col>='201602')

 load data inpath '/hdfs/loc/file3' into table <table_name>
 partition (<part_col>='201603')

and so on.

Approach 2

*

*Create a staging table (temporary table) with same schema as of main table but without any partitions

*Load your entire data into this table (Make sure you have the 'partition column' as one of the fields in these files)

*Load data to your main table from staging table using dynamic partition insert.
 create table <staging_table> (col1 data_type1, col2 data_type2..)
 row format delimited
 fields terminated by '<field_delimiter_in_your_data>'

 create table <main_table> (col1 data_type1, col2 data_type2..)
 partitioned by(part_col data_type3);

 load data inpath '/hdfs/loc/directory/' into table <staging_table>;

 SET hive.exec.dynamic.partition=true;
 SET hive.exec.dynamic.partition.mode=nonstrict;

 insert into table <main_table>
 partition(part_col)
 select col1,col2,....part_col from <staging_table>;

Key aspects in approach 2 are:

*

*Making the 'part_col' available as a field in the loading file

*In the final insert statement, get 'part_col' as the last field from select clause.

A: Let's create a table with a partition on a year and month, with a timestamp in the table:
CREATE TABLE `mypart_p`(
   `id` bigint,
   `open_ts` string
)
PARTITIONED BY (YEAR INT, MONTH INT)

Now I have to alter the table.
ALTER TABLE mypart_p ADD PARTITION (YEAR=2020, MONTH=1)

I had to do that for every year and month, did it in a loop in python. Now lets fill it with data and assign which partition that data belongs to:
INSERT into mypart_p PARTITION (YEAR=2020, MONTH=1)

select id,
open_ts

FROM some_other_table

WHERE substring(open_ts,0,4) = '2020'
AND substring(open_ts,6,2) = '01'


text:
Q: What happens with a binary search on an uneven array/table Let's say we have a table or an array of N-length.
What happens if the length of the table is uneven ?
With an even table the length would be determined by doing N/2.
I would assume that for an uneven table this still holds true.
Does it do N/2 and then take the integer part of the result and use that as "the middle" or does it round up/down ? Or does it do something else entirely ?


text:
Q: How to get percentage total of data with group by date in MongoDB How to get percentage total of data with group by date in MongoDB ?
Link example : https://mongoplayground.net/p/aNND4EPQhcb
I have some collection structure like this
{
    "_id" : ObjectId("5ccbb96706d1d47a4b2ced4b"),
    "date" : "2019-05-03T10:39:53.108Z",
    "id" : 166,
    "update_at" : "2019-05-03T10:45:36.208Z",
    "type" : "image"
}
{
    "_id" : ObjectId("5ccbb96706d1d47a4b2ced4c"),
    "date" : "2019-05-03T10:39:53.133Z",
    "id" : 166,
    "update_at" : "2019-05-03T10:45:36.208Z",
    "type" : "image"
}
{
    "_id" : ObjectId("5ccbb96706d1d47a4b2ced4d"),
    "date" : "2019-05-03T10:39:53.180Z",
    "id" : 166,
    "update_at" : "2019-05-03T10:45:36.208Z",
    "type" : "image"
}
{
    "_id" : ObjectId("5ccbb96706d1d47a4b2ced4e"),
    "date" : "2019-05-03T10:39:53.218Z",
    "id" : 166,
    "update_at" : "2019-05-03T10:45:36.208Z",
    "type" : "image"
}

And I have query in mongodb to get data of collection, how to get percentage of total data. in bellow example query to get data :
db.name_collection.aggregate(
   [
        { "$match": {
            "update_at": { "$gte": "2019-11-04T00:00:00.0Z", "$lt": "2019-11-06T00:00:00.0Z"},
             "id": { "$in": [166] }
        } },
        {
           "$group" : {
               "_id": {
                       $substr: [ '$update_at', 0, 10 ]
                },
               "count" : {
                   "$sum" : 1
               }
           }
        },
        {
            "$project" : {
                "_id" : 0,
                "date" : "$_id",
                "count" : "$count"
            }
        },
        {
            "$sort" : {
                "date" : 1
            }
        }
   ]
)

and this response :
{
    "date" : "2019-11-04",
    "count" : 39
},
{
    "date" : "2019-11-05",
    "count" : 135
}

how to get percentage data total from key count ? example response to this :
{
    "date" : "2019-11-04",
    "count" : 39,
    "percentage" : "22%"
},
{
    "date" : "2019-11-05",
    "count" : 135,
    "percentage" : "78%"
}

A: You have to group by null to get total count and then use $map to calculate the percentage. $round will be a useful operator in such case. Finally you can $unwind and $replaceRoot to get back the same number of documents:
db.collection.aggregate([
    // previous aggregation steps
    {
        $group: {
            _id: null,
            total: { $sum: "$count" },
            docs: { $push: "$$ROOT" }
        }
    },
    {
        $project: {
            docs: {
                $map: {
                    input: "$docs",
                    in: {
                        date: "$$this.date",
                        count: "$$this.count",
                        percentage: { $concat: [ { $toString: { $round: { $multiply: [  { $divide: [ "$$this.count", "$total" ] }, 100 ] } } }, '%' ] }
                    }
                }
            }
        }
    },
    {
        $unwind: "$docs"
    },
    {
        $replaceRoot: { newRoot: "$docs" }
    }
])

Mongo Playground


text:
Q: Sails JS : Blueprint API : Get Many to Many Relationship by ID is not working Followed the documentation to create Users to Pets - Many to Many Relationship in Sails JS V10.5 - BluePrint API with MongoDB v2.6
Yet localhost:1337/user/54e38754b27f02212458e68e/pets?name=Pinkie%20Pie
Finding the Owner's Pet by Name works ..
{
    "name": "Pinkie Pie",
    "color": "pink",
    "createdAt": "2015-02-17T18:24:20.720Z",
    "updatedAt": "2015-02-17T18:24:20.720Z",
    "id": "54e38754b27f02212458e691"
  }
But when the same pet is accessed via its ID
localhost:1337/user/54e38754b27f02212458e68e/pets?id=54e38754b27f02212458e691 , the REST API is not returning any value.
Can you please let me know, how to enable additional logs to troubleshoot this basic Blueprint REST API access?

A: Have you tried using
GET /user/54e38754b27f02212458e68e/pets/54e38754b27f02212458e691

? The same applies also to POST and DELETE requests.


text:
Q: get the generated clientid for a form field Is there a way to get the client id generated for a field generated with a html helper?
i have several components that sometimes are inside another forms, and i wan't to attach javascript events to them.
so, for sample, i would like to have:
@Html.TextBoxFor(model => model.client.email)

<script>
$('#@getmyusercontrolid(model=>model.client.email)').val("put your mail here");
</script>

A: Use @Html.IdFor(model => model.client.email) as this functionality already exists like so:
@Html.TextBoxFor(model => model.client.email)

<script>
$('#@Html.IdFor(model => model.client.email)').val("put your mail here");
</script>

You can read more about it at the following page:
https://msdn.microsoft.com/en-us/library/hh833709%28v=vs.118%29.aspx

A: You could try specifying the id in the HtmlAttributes argument when you generate the input field, e.g.
@Html.TextBoxFor(model => model.client.email, new { id = "emailTextBox" })

Then you can use this in your javaScript
var email = $('#emailTextBox').val();

A: I use this helper:
public static partial class HtmlExtensions
{
    public static MvcHtmlString ClientIdFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression)
    {
        return MvcHtmlString.Create(htmlHelper.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldId(ExpressionHelper.GetExpressionText(expression)));
    }
}

Use it just as you would any other helper: @Html.ClientIdFor(model=>model.client.email)

A: MVC 5 has NameFor, so your example using it is:
@Html.TextBoxFor(model => model.client.email)

<script>
$('#@Html.NameFor(model => model.client.email)').val("put your mail here");
</script>

EDIT
IdFor is also available, which may be more appropriate in this situation than NameFor.


text:
Q: How to set app icon between home indicater icon and app title on action bar This is my Action Bar i wanna set app icon between arrow and activity title so please tell me how to achieve this OR instead of acivity title i can set app icon there?
Please tell me how to achieve this.
i have used this code to do so.
ActionBar actionBar = getSupportActionBar();
            actionBar.setDisplayHomeAsUpEnabled(true);
            actionBar.setDisplayUseLogoEnabled(true);
            actionBar.setIcon(R.drawable.ic_notification1);
            actionBar.setDisplayShowTitleEnabled(false);
            actionBar.setHomeAsUpIndicator(R.drawable.ic_drawer);

A: In code:
getSupportActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
getSupportActionBar().setCustomView(R.layout.layout_actionbar);

In layout folder make layout_actionbar.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal" >
    <ImageView />
    <TextView />

</LinearLayout>

The back arrow should remain in place, in imageview add your icon and in text view your text.


text:
Q: Setting up ajaxterm with apache I have ajaxterm running in my localmachine. I want to access it from remote machines (virtual machine)
I mainly followed this http://www.tbaumi.de/blog/?p=585 tutor
https://localhost/ajaxterm
  Colors   GET   Paste     Connection status:404

Here is my httpd.conf file
NameVirtualHost *:443
<VirtualHost *:443>
 SSLEngine on
 SSLCertificateFile /etc/pki/tls/certs/ca.crt
 SSLCertificateKeyFile /etc/pki/tls/private/ca.key
 <Directory  /usr/share/ajaxterm >
        AllowOverride All
        </Directory>
        DocumentRoot  /usr/share/ajaxterm
# ErrorLog error_log.log
 #TransferLog access_log.log
 #ServerName 192.168.1.3
</VirtualHost>

cat /etc/httpd/conf.d/ssl.conf
</VirtualHost>
ProxyRequests Off
<Proxy *>
Order deny,allow
Allow from all
</Proxy>
ProxyPass /ajaxterm http://localhost:8022
ProxyPassReverse /ajaxterm http://localhost:8022

      [Sat Jul 31 17:22:20 2010] [error] [client ::1] ModSecurity: Unable to retrieve   collection (name "global", key "global"). Use SecDataDir to define data directory first.
[hostname "localhost"] [uri "/ajaxterm"] [unique_id "TFQOdH8AAAEAAE-nKKsAAAAG"]
       [Sat Jul 31 17:22:20 2010] [error] [client ::1] ModSecurity: Unable to retrieve collection (name "ip", key "::1"). Use SecDataDir to define data directory first. [hostname "localhost"] [uri "/ajaxterm"] [unique_id "TFQOdH8AAAEAAE-nKKsAAAAG"]
      [Sat Jul 31 17:22:20 2010] [error] [client ::1] ModSecurity: Unable to retrieve collection (name "global", key "global"). Use SecDataDir to define data directory first. [hostname "localhost"] [uri "/u"] [unique_id "TFQOdH8AAAEAAE-oKZQAAAAH"]
      [Sat Jul 31 17:22:20 2010] [error] [client ::1] ModSecurity: Unable to retrieve     collection (name "ip", key "::1"). Use SecDataDir to define data directory first. [hostname "localhost"] [uri "/u"] [unique_id "TFQOdH8AAAEAAE-oKZQAAAAH"]

A: Following this guide helped.
http://antony.lesuisse.org/software/ajaxterm/

A: Yeah erm, read your logs. You didn't configure mod_security. SecDataDir must point somewhere.


text:
Q: MS Access aggregate function Query works on a single table but but not on multiple tables This query works fine:
SELECT
    SessionResults.Driver,
    SUM( IIF( SessionResults.Place = 1, 1, NULL ) ) AS [Race Wins],
    ROUND( AVG( SessionResults.Place ), 2 )         AS [Avg Race Pos],
    SUM( SessionResults.TotalLaps )                 AS [Total Laps]
FROM
    SessionResults
GROUP BY
    SessionResults.Driver;

This one does not:
SELECT DISTINCT
    SessionResults.Driver,
    ( SUM( IIF( [SessionResults.Place] = 1, 1, NULL ) ) ) AS [Race Wins],
    ROUND( AVG( SessionResults.Place ), 2 )               AS [Avg Race Placing],
    ROUND( AVG( SegmentData.SegPlace ), 2 )               AS [Avg Heat Placing],
    COUNT( SessionResults.TotalLaps )                     AS [Total Laps],
    EventHistory.TrackID                                  AS [Track/Layout],
    MAX( EventHistory.Date )                              AS [Last Race]
FROM
    SessionResults,
    SegmentData,
    EventHistory
WHERE
    (
        (
            ( SessionResults.EventID ) = EventHistory.EventID
            AND
            SegmentData.EventID = SessionResults.EventID
        )
    )
GROUP BY
    SessionResults.Driver,
    EventHistory.TrackID;

The second query produces excessive counts in the [Race Wins] column. The other columns appear to be accurate.
I know there are better ways to do this in newer Access versions but I'm not up to speed on those methods either.
What am I missing here? I messed with different Join options but couldn't get anything to work. Can this be done with Access? The version I'm running is very old, Access 2000, V9.
Again, a single table query seems to work fine. The data gets messed up in the [Race Wins] column when I extend the query to other tables within the same mdb file. The single table query produces a max of 36 wins in the Race Wins column. When the query is extended to multiple tables those numbers increase to well over 600 wins, which is not accurate.


text:
Q: Break after inline-block quirks with doctypes I updating a website and trying to prepare it for a move from its current doctype to the html 5 one. Currently if I use the css below:
br {
  line-height: 5px;
}

div {
  display: inline-block;
}

and html:

div 1

div 2

with doctype:
 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

It renders so that there is no gap between the two div's, the breaks line-height is applied to the same line as the first div not on it's own line.
If I use the same css and html with:
<!DOCTYPE html>

The break is rendered on it's own line giving the 5px break which seems more logical to me for this particular element. Is there a css solution that would render the 5px gap under both doctypes as I transition?
I thought about giving the div bottom padding or a margin but I think that will lead to issues if the div's are nested.


text:
Q: when i apply share intent myapplication get closed in android My problem is when  I use share event at that time, my first activity get closed
    public boolean onCreateOptionsMenu(Menu menu) {
            // Inflate the menu; this adds items to the action bar if it is present.
            getMenuInflater().inflate(R.menu.main, menu);

            MenuItem shareItem = (MenuItem) menu.findItem(R.id.action_share);

            ShareActionProvider mShare = (ShareActionProvider)shareItem.getActionProvider();

            Intent shareIntent = new Intent(Intent.ACTION_SEND);
            shareIntent.setAction(Intent.ACTION_SEND);
            shareIntent.setType("text/plain");`enter code here`
            String Scategory_id = global.getcategoryid();
        }
       <item
            android:id="@+id/action_share"
            android:orderInCategory="100"
            android:showAsAction="ifRoom"
            android:actionProviderClass="android.widget.ShareActionProvider"/>

ABOVE CODE APPLY IN MENU. XML AND I GET THE PROBLEM WHEN I USE SHARE INTENT MY MAIN APPLICATION GET CLOSED ACTCHULY ITS AFTER USING SHARE BUTTON ITS SHOULD BE REDIRECT ON MY FIRST APPLICATION

A: You need to call setShareIntent on mShare.
mShare.setShareIntent(shareIntent);