text:
Q: Map an array of JSON objects to a java.util.Map and vice versa The question is how to map an array of JSON objects to a java.util.Map where each key would be some specified property of an object and the value is the object itself.
JSON:
{"items": [{"field1": 1, "field2": "Hello"}, {"field1": 2, "field2":"World"}]}

Java POJO:
public class Storage {
    private Map<Integer, Item> items;
}

public class Item {
    private Integer field1;
    private String field2;
}

So is there a some way to specify to ObjectMapper that it should use field1 property of each JSON object as key when deserializing array of items to the Map?

A: How to deserialize a JSON string
You can use Jackson to deserialize a JSON string:
For example if you have class Foo
public class Foo {

   private Bar[] items;

   // Constructor / Getters & Setters

}

And that class has an array of class Bar
 public class Bar {

     private int field1;
     private String field2;

     // Constructor / Getters & Setters

 }

Where the field names match those in your JSON string then you can do the following to convert it:
String jsonString = "{\"items\": [{\"field1\": 1, \"field2\": \"Hello\"}, {\"field1\": 2, \"field2\":\"World\"}]}";

ObjectMapper mapper = new ObjectMapper();

Foo foo = mapper.readValue(jsonString, Foo.class);

If you are using Maven, the following dependency would be required in your pom.xml:
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
        <version>${jackson.version}</version>
    </dependency>

Approaches to solve your problem:

Option 1 - Custom Deserializer

Write a custom JsonDeserializer to deserialize your JSON string into a Storage object with a field items of type Map<String,Item>
 public class CustomDeserializer extends JsonDeserializer<Storage> {

    @Override
    public Storage deserialize(JsonParser jsonParser, DeserializationContext deserializationContext)
            throws IOException {

        Map<Integer, Item> map = new HashMap<>();

        ObjectCodec oc = jsonParser.getCodec();
        JsonNode rootNode = oc.readTree(jsonParser);
        JsonNode items = rootNode.get("items");

        for (int i = 0; i < items.size(); i++) {

            JsonNode childNode = items.get(i);

            Item item = new Item(childNode.get("field1").asInt(), childNode.get("field2").asText());

            map.put(item.getField1(), item);
        }

        return new Storage(map);
    }
}

You would then annotate your Storage class with the following:
@JsonDeserialize(using = CustomDeserializer.class)

Your Storage class would look something like;
@JsonDeserialize(using = CustomDeserializer.class)
public class Storage {

   private Map<Integer, Item> items;

   public Storage(Map<Integer, Item> map) {
    this.items = map;
   }

   ...

}

Option 2 - Create Map post deserialization

Deserialize the JSON string into a Storage object with an array of Item as described at the beginning and then construct your Map<Integer, Item> after.
Hope this helps.

A: You can create your own custom Serializers/Deserializers to achieve this. Jackson provides a neat way of doing this. Just annotate the Storage class with @JsonDeserialize(using = YourDeserializer.class) and have the logic to convert the json in YourDeserializer.

A: The array of JSON objects is an array of Items, right? So why not simply deserialize the array into a Java array of Items and then build the Map from there?


text:
Q: How to flip Y axis of pixel data I am learning C++ and after collection The data from glMapBuffer to an array i want to flip the data in y axis
unsigned char * Data = (unsigned char *)glMapBuffer(GL_PIXEL_PACK_BUFFER,
    GL_READ_ONLY);

   char firstarray[ length * width * 4] ;
   memcpy( firstarray ,  Data , sizeof( firstarray ));

Now i want to flip the data of firstarray in y axis.

A:
i did try that but i am unable to get the maths right.

Well, would be far better to get that right instead. You actually just produced an XY-problem...
Appropriate accessor functions could look like these:
unsigned char* getPixel(unsigned int row, unsigend int column)
{
    return array + (row * width + column) * 4;
}

unsigned char* getSubPixel(unsigned int row, unsigend int column, unsigned int color)
{
    return getPixel(row, column) + color;
}

i want to flip the buffer in y axis

Assuming you want to produced a new image mirrored at x-axis, you can simply
std::swap(*getSubPixel(x, y, 0), *getSubPixel(x, width - y, 0))
// same for the other three sub-pixels
// if you decide to return references instead of pointers, you don't need
// to dereference (can skip the asterisks)

for each pixel in half of the row (must be half, otherwise you'd be swapping all values twice resulting in identical image again) and for each row.

A: An array of that size allocated on stack is most likely going to stack-overflow (pun intended), so use a vector instead.
Also from the * 4 (and the dimensions) i think you are using the array to store images, so you can create a struct to store the inner most dimension, like:
struct rgba //or color
{
    uint8_t red;
    uint8_t green;
    uint8_t blue;
    uint8_t alpha;
};

And then create an std::vector that contains the color struct (rgba in my example): std::vector<rgba> img;
And you use it like:
int length = 1080;
int width = 1920;

std::vector<rgba> img(length * width);

for (int i = 0; i != length; i++)
    for (int j = 0; j != width; j++)
        img[i * width + j] = { 255, 255, 255, 255 };

Or you can take a look at some library that does image processing, example OpenCV

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to convert csv file into Python dictionary and sum/operate values based on certain conditions? I have a huge csv file containing information about COVID-19 cases and deaths for every single county in the United States.
To give you a general idea of the information contained in this file, here are the first 10 lines of it:
date,county,state,fips,cases,deaths,confirmed_cases,confirmed_deaths,probable_cases,probable_deaths
2021-03-18,Autauga,Alabama,01001,6483,96,5557,85,926,11
2021-03-18,Baldwin,Alabama,01003,20263,295,14329,220,5934,75
2021-03-18,Barbour,Alabama,01005,2199,54,1225,37,974,17
2021-03-18,Bibb,Alabama,01007,2512,58,2031,35,481,23
2021-03-18,Blount,Alabama,01009,6371,129,4901,109,1470,20
2021-03-18,Bullock,Alabama,01011,1193,39,1059,29,134,10
2021-03-18,Butler,Alabama,01013,2069,66,1888,60,181,6
2021-03-18,Calhoun,Alabama,01015,14137,301,10608,242,3529,59
2021-03-18,Chambers,Alabama,01017,3460,113,1720,73,1740,40

Anyways, I want to create a Python dictionary for this data with each of the keys being a tuple consisting of the state and county names and the each of the values being a list of integers: the first int representing the number of confirmed cases and the second one representing the number of confirmed deaths.
Basically, I want output like this:
dic = {("state","county"):[confirmed_cases, confirmed_deaths]}

How would I generate a python dictionary like the one above for all the counties in the csv file? Please use csv.reader.
Additionally, I need to find the sum of all the confirmed deaths for a particular state. How would I, for example, sum up the values in 'confirmed deaths' for all of the rows where 'state' is 'Alabama'?
I also want to find number of counties in the entire file where the number of confirmed cases is between certain intervals. How would I go about doing that in Python?
Additionally, I have another csv file with all the population values for each state for the past couple of years. To get an idea of the info this file contains, here are the first 10 lines:
table with row headers in column A and column headers in rows 3 through 4. (leading dots indicate sub-parts),,,,,,,,,,,,
.Alabama,4779736,4780125,4785437,4799069,4815588,4830081,4841799,4852347,4863525,4874486,4887681,4903185
.Alaska,710231,710249,713910,722128,730443,737068,736283,737498,741456,739700,735139,731545
.Arizona,6392017,6392288,6407172,6472643,6554978,6632764,6730413,6829676,6941072,7044008,7158024,7278717
.Arkansas,2915918,2916031,2921964,2940667,2952164,2959400,2967392,2978048,2989918,3001345,3009733,3017804
.California,37253956,37254519,37319502,37638369,37948800,38260787,38596972,38918045,39167117,39358497,39461588,39512223
.Colorado,5029196,5029319,5047349,5121108,5192647,5269035,5350101,5450623,5539215,5611885,5691287,5758736
.Connecticut,3574097,3574147,3579114,3588283,3594547,3594841,3594524,3587122,3578141,3573297,3571520,3565287
.Delaware,897934,897937,899593,907381,915179,923576,932487,941252,948921,956823,965479,973764
.District of Columbia,601723,601767,605226,619800,634924,650581,662328,675400,685815,694906,701547,705749

The most recent population estimate is represented by the last value for each state. For example, for Alabama, '4903185' is the most recent population estimate.
I want to create a python dictionary with the keys being strings representing each state name and the values being an integer representing only the last number for each state in the csv file.
Basically, {"state":population"}
And to add on to that, I would like to calculate the death density rate for each state by dividing the number of confirmed deaths in each state and dividing them by the most recent population figure for each state. How would I program that?
And finally, I want to calculate the us death density rate (entire country) by adding all of the values in the confirmed deaths column and dividing that sum by the sum of all of the values in the latest population column. How would I do that?
Thank you!

A: I highly recommend checking out pandas. It is a wonderful library based all around tabular data. There are specific commands in it to read a csv, then send it to json, making it easily manipulatable in Python.
It would go something like:
import pandas as pd

df = pd.read_csv("filename.csv")
json_variable = df.to_json()
print(json_variable)

Of course, you can format this with pretty print, but if you already have the CSV, all you should need to do now is access that "json_variable".

A: Better use pandas.DataFrame instead of dictionary - it will be more useful.
I use io.StringIO only to simulate file in memory.
I changed few states in example data to have more then one state
Using groupby(['state', 'county']) I could get expected values and create dictionary but it is more useful to use directly values.
text = '''date,county,state,fips,cases,deaths,confirmed_cases,confirmed_deaths,probable_cases,probable_deaths
2021-03-18,Autauga,Alabama,01001,6483,96,5557,85,926,11
2021-03-18,Baldwin,Alabama,01003,20263,295,14329,220,5934,75
2021-03-18,Barbour,Alabama,01005,2199,54,1225,37,974,17
2021-03-18,Bibb,Alabama,01007,2512,58,2031,35,481,23
2021-03-18,Blount,Alabama,01009,6371,129,4901,109,1470,20
2021-03-18,Bullock,Alaska,01011,1193,39,1059,29,134,10
2021-03-18,Butler,Alaska,01013,2069,66,1888,60,181,6
2021-03-18,Calhoun,Alaska,01015,14137,301,10608,242,3529,59
2021-03-18,Chambers,Alaska,01017,3460,113,1720,73,1740,40'''

import pandas as pd
import io

df = pd.read_csv(io.StringIO(text))
#df = pd.read_csv("filename.csv")

for name, group in df.groupby(['state', 'county']):
    print('\n---', name, '---\n')
    #print(group)
    print('confirmed_cases :', group['confirmed_cases'].values[-1])
    print('confirmed_deaths:', group['confirmed_deaths'].values[-1])

Result:
--- ('Alabama', 'Autauga') ---

confirmed_cases: 5557
confirmed_deaths: 85

--- ('Alabama', 'Baldwin') ---

confirmed_cases: 14329
confirmed_deaths: 220

--- ('Alabama', 'Barbour') ---

confirmed_cases: 1225
confirmed_deaths: 37

--- ('Alabama', 'Bibb') ---

confirmed_cases: 2031
confirmed_deaths: 35

--- ('Alabama', 'Blount') ---

confirmed_cases: 4901
confirmed_deaths: 109

--- ('Alaska', 'Bullock') ---

confirmed_cases: 1059
confirmed_deaths: 29

--- ('Alaska', 'Butler') ---

confirmed_cases: 1888
confirmed_deaths: 60

--- ('Alaska', 'Calhoun') ---

confirmed_cases: 10608
confirmed_deaths: 242

--- ('Alaska', 'Chambers') ---

confirmed_cases: 1720
confirmed_deaths: 73

The same way you can groupby('state') and calculate sum() of confirmed_deaths
for name, group in df.groupby('state'):
    print('\n---', name, '---\n')
    print('confirmed_deaths:', group['confirmed_deaths'].sum())

Result:
--- Alabama ---

confirmed_deaths: 486

--- Alaska ---

confirmed_deaths: 404

Or shorter
df_state = df.groupby('state').sum()
print(df_state)

And you have new DataFrame
         fips  cases  deaths  ...  confirmed_deaths  probable_cases  probable_deaths
state                         ...
Alabama  5025  37828     632  ...               486            9785              146
Alaska   4056  20859     519  ...               404            5584              115

which uses state as row's index so you could use it to join with other CSV.
text2 = '''.Alabama,4779736,4780125,4785437,4799069,4815588,4830081,4841799,4852347,4863525,4874486,4887681,4903185
.Alaska,710231,710249,713910,722128,730443,737068,736283,737498,741456,739700,735139,731545
.Arizona,6392017,6392288,6407172,6472643,6554978,6632764,6730413,6829676,6941072,7044008,7158024,7278717
.Arkansas,2915918,2916031,2921964,2940667,2952164,2959400,2967392,2978048,2989918,3001345,3009733,3017804
.California,37253956,37254519,37319502,37638369,37948800,38260787,38596972,38918045,39167117,39358497,39461588,39512223
.Colorado,5029196,5029319,5047349,5121108,5192647,5269035,5350101,5450623,5539215,5611885,5691287,5758736
.Connecticut,3574097,3574147,3579114,3588283,3594547,3594841,3594524,3587122,3578141,3573297,3571520,3565287
.Delaware,897934,897937,899593,907381,915179,923576,932487,941252,948921,956823,965479,973764
.District of Columbia,601723,601767,605226,619800,634924,650581,662328,675400,685815,694906,701547,705749
'''

import pandas as pd
import io

df2 = pd.read_csv(io.StringIO(text2), header=None)

# convert first column into index - and remove `.`
df2.index = df2[0].str.replace('.', '')

# get name of last column
last_column = df2.columns[-1]

print(df2[[last_column]])

Result:
                            12
0
Alabama                4903185
Alaska                  731545
Arizona                7278717
Arkansas               3017804
California            39512223
Colorado               5758736
Connecticut            3565287
Delaware                973764
District of Columbia    705749

And join both
df3 = df_state.join(df2[[last_column]])

print(df3)

to get
         fips  cases  deaths  ...  probable_cases  probable_deaths       12
state                         ...
Alabama  5025  37828     632  ...            9785              146  4903185
Alaska   4056  20859     519  ...            5584              115   731545

And then I can calculate density for every state
density = df3['confirmed_deaths']/df3.iloc[:,-1]

print('density:', density)

Result:
Alabama    0.000099
Alaska     0.000552

And the same for all country
density = df3['confirmed_deaths'].sum() / df3.iloc[:,-1].sum()

print('density:', density)

Result:
density: 0.00015794900554241286

With pandas.DataFrame I could do this without for-loops.

EDIT:
Full example with small changes
text1 = '''date,county,state,fips,cases,deaths,confirmed_cases,confirmed_deaths,probable_cases,probable_deaths
2021-03-18,Autauga,Alabama,01001,6483,96,5557,85,926,11
2021-03-18,Baldwin,Alabama,01003,20263,295,14329,220,5934,75
2021-03-18,Barbour,Alabama,01005,2199,54,1225,37,974,17
2021-03-18,Bibb,Alabama,01007,2512,58,2031,35,481,23
2021-03-18,Blount,Alabama,01009,6371,129,4901,109,1470,20
2021-03-18,Bullock,Alaska,01011,1193,39,1059,29,134,10
2021-03-18,Butler,Alaska,01013,2069,66,1888,60,181,6
2021-03-18,Calhoun,Alaska,01015,14137,301,10608,242,3529,59
2021-03-18,Chambers,Alaska,01017,3460,113,1720,73,1740,40'''

text2 = '''.Alabama,4779736,4780125,4785437,4799069,4815588,4830081,4841799,4852347,4863525,4874486,4887681,4903185
.Alaska,710231,710249,713910,722128,730443,737068,736283,737498,741456,739700,735139,731545
.Arizona,6392017,6392288,6407172,6472643,6554978,6632764,6730413,6829676,6941072,7044008,7158024,7278717
.Arkansas,2915918,2916031,2921964,2940667,2952164,2959400,2967392,2978048,2989918,3001345,3009733,3017804
.California,37253956,37254519,37319502,37638369,37948800,38260787,38596972,38918045,39167117,39358497,39461588,39512223
.Colorado,5029196,5029319,5047349,5121108,5192647,5269035,5350101,5450623,5539215,5611885,5691287,5758736
.Connecticut,3574097,3574147,3579114,3588283,3594547,3594841,3594524,3587122,3578141,3573297,3571520,3565287
.Delaware,897934,897937,899593,907381,915179,923576,932487,941252,948921,956823,965479,973764
.District of Columbia,601723,601767,605226,619800,634924,650581,662328,675400,685815,694906,701547,705749
'''

import pandas as pd
import io

df = pd.read_csv(io.StringIO(text1))

# ---

for name, group in df.groupby(['state', 'county']):
    print('\n---', name, '---\n')
    #print(group)
    print('confirmed_cases:', group['confirmed_cases'].values[0])
    print('confirmed_deaths:', group['confirmed_deaths'].values[0])

for name, group in df.groupby('state'):
    print('\n---', name, '---\n')
    print('confirmed_deaths:', group['confirmed_deaths'].sum())

print('\n--- df_state ---\n')
df_state = df.groupby('state').sum()
print(df_state)

# ---

df_population = pd.read_csv(io.StringIO(text2), header=None)

# ---

df_population.index = df_population[0].str.replace('.', '', regex=False)
# get last column
last_column = df_population.columns[-1]
# rename last column
df_population = df_population.rename(columns={last_column: 'last_population'})

# ---

print('\n--- df_population ---\n')
print(df_population['last_population'])

df_joined = df_state.join(df_population['last_population'])
print('\n--- df_joined ---\n')
print(df_joined)

density_states = df_joined['confirmed_deaths']/df_joined['last_population']
print('\n--- density states ---\n')
print(density_states)

density_country = df_joined['confirmed_deaths'].sum() / df_joined['last_population'].sum()
print('\n--- density country ---\n')
print(density_country)


text:
Q: Como usar regex correctamente espero esten bien, la verdad no se si es de principiantes, pero no me familiarizo mucho con el modulo re, y estoy a punto de volverme loco con algo tan simple
Estoy tratando de buscar esta cadena, y el filename varia entre minusculas, mayusculas, digitos, caracteres especiales como %$#_- etc
attachments/018/796/036/original/Aleatorio.txt
attachments/118/496/034/original/Test1.txt
attachments/028/196/336/original/Test_1.txt
attachments/028/196/336/original/Test_1_test.txt

page = requests.get(url, headers=HEADERS, timeout=10)
pattern='(attachments\\/\d{3,}\\/\d{3,}\\/\d{3,}\\/original\\/\w.*.txt?)'
regex = re.compile(pattern, re.I | re.U)
file = regex.search(page.text)
print(file)

Quisiera saber como es la forma para aceptar cualquier carácter en el filename

A: Algunas cosas:

*

*El carácter \ dentro de una expresión regular es especial, y se usa para varias cosas, como por ejemplo para indicar que el siguiente que aparezca tras él debe tomarse "literalmente" (es decir, quitar el significado especial de otros caracteres, como por ejemplo en \. para indicar que el punto ha de ser literal), o para crear símbolos con un significado concreto, como por ejemplo \w que significa "cualquier carácter alfanumérico o guión bajo").

*Pero se da la (desafortunada) circunstancia de que el \ también tiene un significado especial dentro de una cadena en la mayoría de los lenguajes de programación, y sirve para cambiar el significado de la letra que aparezca detrás. Un ejemplo típico es \n que significa "retorno de carro". En particular, si queremos meter un \ dentro de un string, sin que tenga significado especial, debemos precederlo de otro \, y escribir por tanto \\.

*Por culpa de esto último, cuando queremos construir expresiones regulares en las que el \ es un signo habitual, ya que las tenemos que meter en una cadena, el \\ debe aparecer duplicado.

En tu expresión regular hay un \w al final que debería ser por tanto \\w. Aunque pienso que podría sobrar por completo ese \\w, pues con él estás forzando a que el nombre de fichero comience por letra, dígito, o guión bajo. Si quieres cualquier carácter inicial como válido, no pongas ese \\w.
Además tienes un .txt? que debería ser \\.txt, para forzar a que el punto sea literal (si no, el punto significa "cualquier caracter"). Y sobra el interrogante final, que en expresiones regulares marca el carácter anterior como "opcional", es decir, que la t final podría aparecer o no.
Por otro lado:

*

*Si abres un paréntesis dentro de una expresión regular estarás dando comienzo a un grupo de captura, que finaliza cuando se cierra el paréntesis.

*Los grupos de captura sirven para poder "quedarte" con un trozo de toda la expresión. Por ejemplo, para quedarse con el nombre de fichero como tú quieres.

En tu expresión regular hay un paréntesis al inicio y otro al final, por tanto estás creando un grupo de captura que se queda con "la ruta completa". No es eso lo que querías.
Finalmente:

*

*Ya que las expresiones regulares abundan en \, y las cadenas normales fuerzan a duplicarlos, al final te queda todo lleno de \\  y se hacen dificil de leer. Para evitar esto, Python tiene cadenas raw, que se marcan poniendo una r delante de la cadena, y dentro de las cuales el \ no tiene significado especial y por tanto no es necesario duplicarlo.

Teniendo todo esto en cuenta, tu expresión regular sería:
pattern = r'attachments\/\d{3,}\/\d{3,}\/\d{3,}\/original\/(.*\.txt)'

Observa la r delante de las comillas de apertura, para marcar ese string como raw y así no tener que duplicar los \. He corregido también los problemas antes señalados, y he hecho que el grupo de captura contenga sólo el nombre del fichero.
Al grupo de captura puedes acceder mediante el método .group() del objeto resultante del match. Por ejemplo:
txt = """
attachments/018/796/036/original/Aleatorio.txt
attachments/118/496/034/original/Test1.txt
attachments/028/196/336/original/Test_1.txt
attachments/028/196/336/original/Test_1_test.txt
"""

for linea in txt.split("\n"):
  r = re.search(regex, linea)
  if r:
    print(r.group(1))

producirá como resultado:
Aleatorio.txt
Test1.txt
Test_1.txt
Test_1_test.txt

Bonus. Para practicar con expresiones regulares, probar si funcionarán antes de escribir el programa, y obtener el significado de cada carácter dentro de ellas, es muy útil el sitio regex101.com. Por ejemplo puedes practicar con tu caso a partir de esto


text:
Q: Toggle jQuery function on and off I am new to jQuery and am having some trouble figuring something out.
I have this function that is called at the bottom of the page to attach an auto-complete feature to a text box, this part is working fine. Here is the code that is called to enable the auto-complete:
$(function(){
    $('#intext').autocomplete('get-data.php?mode=sql', {
        width: 400,
        max: 5,
        selectFirst: false
    });
});

However the search box contains two radio buttons for two different types of searches. The auto-complete feature should only be available for one type of search.
So my question is, how can I enable this by clicking one radio button, and disable it by clicking the second radio button?
EDIT
The auto-complete script has a .autocomplete( "disable" ) method, but I don't know how to enable/disable that based on which radio button is checked.
EDIT 2
I am trying to get the method suggested by "Rory McCrossan" to work, as I am using jQuery UI Autocomplete. Here's the code for my radio buttons and search box:
News: <input type="radio" class="myRadio" name="search_type" value="news" checked="checked" onclick="this.form.action='/search.php';" />
Media Gallery: <input type="radio" class="myRadio" name="search_type" value="media" onclick="this.form.action='/media.php';" />
<input id="intext" class="txt" type="text" name="searchterms" />

I have the following code in the script that runs on each page:
addAutoComplete($("#intext"));

$(".myRadio").change(function() {
    if ($(this).val() == "news") {
        if (!$("#intext").hasClass("ui-autocomplete-input"))
            addAutoComplete($("#intext"));
    }
    else {
        $("#intext").autocomplete('destroy')
    }
});

function addAutoComplete($el) {
    $('#intext').autocomplete('autocomplete-data.php?mode=sql', {
        width: 400,
        max: 5,
        selectFirst: false
    });

}

This does not seem to work, and the Error Console in Firefox doesn't show any errors.

A: Assuming this is the jQueryUI autocomplete, you can use $el.autocomplete("destroy") to remove the autocomplete function.
addAutoComplete($("#intext")); // on load

$(".myRadio").change(function() {
    if ($(this).val() == "a") {
        if (!$("#intext").hasClass("ui-autocomplete-input"))
            addAutoComplete($("#intext"));
    }
    else {
        $("#intext").autocomplete('destroy')
    }
});

function addAutoComplete($el) {
    $el.autocomplete('get-data.php?mode=sql', {
        width: 400,
        max: 5,
        selectFirst: false
    });
}

A: The best solution would be to disable the autocomplete when one of the two radiobuttons is selected. You call a jQuery UI method by giving the methodname as the first parameter to the jQuery plugin call. So for example:"
// First create the autocomplete
$('#textbox1').autocomplete();

// call a method on the 'autocompleted' textbox
$('#textbox1').autocomplete('methodname', 'methodparam1', methodparam2, etc)

So in this case:
$('.classOfTheTwoRadioButtons').change(function(e) {
  var method = $(e.target).is(':checked [value=valueIfAutocomplete]')? 'enable': 'disable';
  $('#textbox').autocomplete(method);
});

Other option: Create two textboxes with the same name and only attach the autocomplete on one of them. Use the toggle() function of jquery to hide the one you do not want to see when the selected radiobutton is checked.
$('.classOfTheTwoRadioButtons').change(function(e) {
  var $e = $(e.target);
  $('#firstTextBox').toggle($e.val() === 'value1');
  $('#secondTextBox').toggle($e.val() === 'value2');
});

A: You should check if you autocomplete() plugin has a destroy action of some kind that removes his behavior. If so, just call it when your "autocomplete off" radio is selected.
If your plugin doesn't have that option, just create to text fields. The first one with attached autocomplete, the second without it. Then toggle them based on your checkboxes.

A: given that radio button with value 'a' enables the autocomplete and the one with value 'b' disables it
$(".myRadio[value='a']").click(function() {
    $('#intext').autocomplete('enable');
}
$(".myRadio[value='b']").click(function() {
    $('#intext').autocomplete('disable');
}


text:
Q: SSIS 2008 : crm dynamics 2013 webservice timeout I'm using SSIS 2008 to insert data in CRM Dynamics 2013.
We have two servers, the first is for the CRM installation and the seconde SQLServer database.
I wrote a script in SSIS to push data to the CRM, but every time I get a timeout error even if I set it to a higher number.
Anyone have an idea how to solve this problem? Thanks.

A: Try replicating your script component in to 10 parts. This way, you will have several different instances of service inserting/updating data parallel.


text:
Q: How Close is "Last Crusade" to Actual Grail Lore? In Indiana Jones and the Last Crusade, almost anything that we see once they enter the temple would have to be made up (the three traps, the very old grail knight, the great seal, and so on), but how much of the rest of what is told in relation to the Holy Grail is true and how much is made up just for the movie?
For instance, is everything Indy reads on the tablet, before he starts out on the quest, true, or is that made up?  Is anything based on actual grail lore?

A: Your first mistake in the title is to imply that "Actual Grail Lore" is something definitive or even vaguely consistent. The truth is that there is a wealth of legendary material relating to the Grail, and a whole range of related mythology around the Rosecrucians, the Templars, and pretty much anything else you can throw in that cannot be proven either way. TBH, the mythology around the Templars themselves is enough to twist most peoples credulity.
This is why Dan Brown (sorry) can take a random collection of these stories, and build his own around them. And why Umberto Eco can do the same only 10 times better. And the writers of myth-based-fantasy can play fast and loose with them without is actually seeming to make any difference.
All of which means that some of the material used may well be part of grail legend, it matters not on any level. I would be reasonably sure that all of the words used in the inscriptions appeared in grail legends, and that someone could use a bible-code-style process to extract them.

A: The legend of the Grail is exactly that. The Bible says nothing about Jesus' blood being caught in a cup. The only mention of a cup is during the Last Supper, which is the only true statement about the "grail" in IJ:LC. The look of the cup in the movie is consistent in design; the gold glaze on the inside (which was either just incidental or meant to be an effect of Jesus' blood) would have been unlikely.
It is extremely unlikely that the cup used at the Last Supper would have been anywhere near Golgotha. It belonged to the man who owned the house in which the Last Supper took place, which the Disciples were led to by an unnamed water-carrier whom Jesus told them to look for upon entering Jerusalem. For the next two and a half centuries after the Crucifixion, until the Edict of Milan in 313, the Romans did everything they could to stomp out any mention of any other Son of God besides Caesar. The cup used in the Last Supper, if ever identified as such, was likely destroyed, and in any case virtually all scholars agree it has been lost to time.
The majority of "Actual Grail Lore" is in Celtic and English myth, and states that Joseph of Arimathea took the cup to the British Isles, where it remains to this day in the care of faithful guardians (the Knights Templar). So, the path beginning in Iskenderun (Alexandretta) is wildly inconsistent with Grail lore (it's on the complete opposite side of the old Roman Empire from where the Arthur legends and older works say it should be). That would mean pretty much everything else is completely inaccurate; the knights trying to get back to Rome would have gone through Genoa instead (Venice is on the opposite side of northern Italy), The first marker being in the Middle East, the path of the Grail leading to present-day Jordan, etc etc, all total hogwash both from Biblical and Arthurian sources.


text:
Q: Sending mail with SSL with Python 2.3 I'm working with Python 2.3 and I need to send e-mails with SSL.
According to the docs, SMTP_SSL was added in Python 2.6.
Is there a way to use SSL also in Python 2.3 (maybe with a third-party module)?

A: Maybe you can just use starttls()
just like:
smtp = smtplib.SMTP(mailhost)
smtp.starttls()

In SMTP_SSL doc you can find:

SMTP_SSL should be used for situations where SSL is required from the
  beginning of the connection and using starttls() is not appropriate.


text:
Q: Change line width (thickness) sjPlot sjp.int R I would like to change the width of the lines (thicker lines) in an sjp.int plot. I tried all help arguments, but somehow could not find it.
Example code:
require(ggplot2)
require(sjPlot)
head(diamonds)
test<-lm(price ~ carat*depth, data=diamonds)
sjp.int(test, type = "eff")

A: You cannot change line size for sjp.int currently, so you have to modify the returned plot object(s), which are in the return value plot.list. Then you can overwrite geom_line().
dummy <- sjp.int(test, type = "eff")
dummy$plot.list[[1]] + geom_line(size = 3)

I've added a geom.size argument to sjp.int, see GitHub.


text:
Q: How to use substitution in xargs? What I want to do is

*

*find all file with .txt extension

*cp them to .dat file

it could do like this:
for f in `find . -type f -name "*.txt"`; do cp $f ${f%.txt}.dat; done

I want to do this with xargs, I have tried this:
find . -type f -name "*.txt" | xargs -i cp {} ${{}%.txt}.dat

I go error like this:
bad substitution

About this, I have these questions:

*

*how to do the substitution rightly?

*I am curious about that xargs will do things parallel when for loop do things one by one?

A: You can use:
find . -type f -name "*.txt" -print0 |
xargs -0 -i bash -c 'echo cp "$1" "${1%.txt}.dat"' - '{}'

A:

*

*How to do the substitution rightly?

You cannot use substitution in the way you are trying to do because {} is not a bash variable (only part of xargs syntax), therefore bash cannot do substitution on it.
A better way to it would be to create a full bash command and provide it as and argument to xargs (e.g. xargs -0 -i bash -c 'echo cp "$1" "${1%.txt}.dat"' - '{}' - this way you can do bash substitution).

*I am curious about that xargs will do things parallel when for loop do things one by one?

Yes, for loop will do things sequently but by default xargs always will. However, you can use -P option of xargs to parallelize it, from xargs man pages:

   -P max-procs, --max-procs=max-procs
          Run up to max-procs processes at a time; the default is 1.  If max-procs is 0, xargs will run as many processes as possible at a time.  Use the -n option or the -L  option
          with  -P;  otherwise  chances are that only one exec will be done.  While xargs is running, you can send its process a

SIGUSR1 signal to increase the number of commands to
run simultaneously, or a SIGUSR2 to decrease the number.  You cannot increase it above an implementation-defined limit (which is
shown with --show-limits).  You cannot de‐
crease it below 1.  xargs never terminates its commands; when asked to decrease, it merely waits for more than one existing
command to terminate before starting another.
Please  note that it is up to the called processes to properly manage parallel access to shared resources.  For example, if

more than one of them tries to print to stdout,
the ouptut will be produced in an indeterminate order (and very likely mixed up) unless the processes collaborate in some
way to prevent this.  Using some kind of  locking
scheme  is one way to prevent such problems.  In general, using a locking scheme will help ensure correct output but
reduce performance.  If you don't want to tolerate the
performance difference, simply arrange for each process to produce a separate output file (or otherwise use separate
resources).

A: If you are unhappy about the bash -c '...' - construct, you can instead use GNU Parallel:
find . -type f -name "*.txt" -print0 | parallel -0 cp {} {.}.dat

A: xargs and other tools are not as flexible as Perl for this kind of stuff.
~ ❱ find . | perl -lne '-f && ($old=$_) && s/\.txt/.dat/g && print "$old => $_"'
./dir/00.file.txt => ./dir/00.file.dat
./dir/06.file.txt => ./dir/06.file.dat
./dir/05.file.txt => ./dir/05.file.dat
./dir/02.file.txt => ./dir/02.file.dat
./dir/08.file.txt => ./dir/08.file.dat
./dir/07.file.txt => ./dir/07.file.dat
./dir/01.file.txt => ./dir/01.file.dat
./dir/04.file.txt => ./dir/04.file.dat
./dir/03.file.txt => ./dir/03.file.dat
./dir/09.file.txt => ./dir/09.file.dat

then instead of print function use: rename $old, $_
With this one-liner you can rename anything you like

For forcing the xargs with parallel mode you should use -P like:
ls *.mp4 | xargs -I xxx -P 0 ffmpeg -i xxx xxx.mp3

converting all the .mp4 files to .mp3 in parallel. So if you have 10 mp4 then 10 ffmpeg is running simultaneously.


text:
Q: Running node only works correctly from app directory When I run node from my app directory, namely:
/var/www/html/
node server.js

The site runs correctly.
When I try to start node from a different directory it runs, but has a wrong root:
#(not in /var/www/html)
node /var/www/html/server.js

What happens is that the correct file is being executed, but all the paths get messed up. Here's an error for example:
GET /auth/login 500 32.511 ms - 2206
Error: Failed to lookup view "login" in views directory "/home/ec2-user/views"

The error is not surprising because the view "login" is not found in
/home/ec2-user/views

but in
/var/www/html/views

How can I correct this behavior?
Clarification:
I am asking this question because I am trying to set up forever to run node on upstart.
The service is successfully runs on upstart, but runs into the same problem manually starting the server does.

A: This will most likely happen if you define paths like e.g. for the template engine like:
app.set('views', './views');

With the . it looks up the directory from where you launched the app.
You need to use __dirname like:
app.set('views', __dirname + '/views');

in order to search the views directory in the script's folder. As also explained here: What is the difference between __dirname and ./ in node.js?


text:
Q: Setting linker preferences for multiple shared libraries of same name I link my application against multiple shared libraries, one of which is Google's gRPC, which in turn links against boringSSL. I also link against other libraries, which in turn link against OpenSSL. In the end, calling ldd on my binary and grepping for ssl gives:
    libssl.so.1.1 => /lib/x86_64-linux-gnu/libssl.so.1.1 (0x00007f62f35c8000)
    libssl.so => /usr/local/grpc/lib/libssl.so (0x00007f62f28b6000)

I would rather not statically link against gRPC and friends. Is there a way I can set preferences that the second result should be used for gRPC only and the first for everything else?
I am using CMake as a build project, if that helps.


text:
Q: How to integrate windows authentication (SSO) in my custom web server Java based? I have a custom web server application Java based and I need to support Single-Sign-On.
I made a research on the issue and found out that I can use JAAS to implement SSO. I already configured my http server to accept the Authentication handshake process, so I have the logged-in user Authentication encoded in my java application and I am passing it my JAAS authentication function.
Now, I need to authenticate the user with my domain controller. So, I'm using jaas.conf file to define the LoginModule:
SSOAUTH {
  com.sun.security.auth.module.Krb5LoginModule required
  useKeyTab=false
  storeKey=true
  useTicketCache=false
  debug=true;
};

As you can see I would like to use the Kerberos protocol. The first question is: Do I need to make some installation/configuration for my domain controller to support this protocol?
This is my java code in my web server application that will handle the whole authentication process using JAAS:
public class LDAPClient
{
   private static final String LOGIN_MODULE_NAME = "SSOAUTH";

/**
 * Constructor
 * @param domain
 * @param ldapServer
 * @param jaasConfigPath
 */
public LDAPClient(String domain, String ldapServer, String jaasConfigPath)
{
    System.setProperty("sun.security.krb5.debug", "true");
    System.setProperty("java.security.krb5.realm", domain);
    System.setProperty("java.security.krb5.kdc", ldapServer); // LDAP active directory server name
    System.setProperty("javax.security.auth.useSubjectCredsOnly", "true");
    System.setProperty("java.security.auth.login.config", jaasConfigPath); // path to the jaas.conf file.
}

/**
 * Authenticates the given kerberos token and returns the client principal.
 *
 * @param argKerberosTokenAsBase64 The kerberos content token.
 * @return
 * @throws Exception
 */
public String authenticate(String argKerberosTokenAsBase64) throws Exception
{
    BASE64Decoder decoder = new BASE64Decoder();
    byte[] kerberosToken = decoder.decodeBuffer(argKerberosTokenAsBase64.substring("Negotiate ".length()));
    String clientName;

    try
    {
        // Login to the KDC and obtain subject for the service principal
        Subject subject = createServiceSubject(argKerberosTokenAsBase64);
        if (subject != null)
        {
            clientName = acceptSecurityContext(subject, kerberosToken).toUpperCase();
            System.out.println("Security context successfully initialized!");
        }
        else
        {
            throw new Exception("Unable to obtain kerberos service context");
        }
    }
    catch (Throwable throwable)
    {
        System.out.println("Token: " + argKerberosTokenAsBase64);
        throwable.printStackTrace();
        throw new Exception(throwable);
    }

    return clientName;
}

/**
 * Creates service subject based on the service principal and service
 * password.
 *
 * @param password
 * @return
 * @throws LoginException
 */
private static Subject createServiceSubject(String password)
        throws LoginException
{
    // "Client" references the JAAS configuration in the jaas.conf file.
    LoginContext loginCtx = new LoginContext(LOGIN_MODULE_NAME, new LoginCallbackHandler(password));
    loginCtx.login();
    return loginCtx.getSubject();
}

/**
 * Completes the security context initialisation and returns the client
 * name.
 * @param argSubject
 * @param serviceTicket
 * @return
 * @throws GSSException
 */
private static String acceptSecurityContext(Subject argSubject, final byte[] serviceTicket) throws GSSException
{
    // Accept the context and return the client principal name.
    return (String) Subject.doAs(argSubject, new PrivilegedAction()
    {
        public Object run()
        {
            try
            {
                // Identify the server that communications are being made
                // to.
                GSSManager manager = GSSManager.getInstance();
                GSSContext context = manager.createContext((GSSCredential) null);
                context.acceptSecContext(serviceTicket, 0, serviceTicket.length);
                return context.getSrcName().toString();
            }
            catch (GSSException exp)
            {
                throw new RuntimeException(exp);
            }
        }
    });
}

}

I am having the following LoginException: javax.security.auth.login.LoginException: Pre-authentication information was invalid (24)
I am passing the kerberos authentication token to the LoginContext, see the call to createServiceSubject(), in order to get the Subject, is it correct or I missing something here?
And this is parts from the System.out debug error:
>>>KRBError:
 sTime is Wed Feb 12 14:29:17 IST 2014 1392208157000
 suSec is 301542
 error code is 25
 error Message is Additional pre-authentication required
 realm is DOMAIN.LOCAL
 sname is krbtgt/DOMAIN.LOCAL
 eData provided.
 msgType is 30
>>>Pre-Authentication Data:
 PA-DATA type = 19
 PA-ETYPE-INFO2 etype = 23
 PA-ETYPE-INFO2 salt = null
 salt for 3 is DOMAIN.LOCALskadar
>>>Pre-Authentication Data:
 PA-DATA type = 2
 PA-ENC-TIMESTAMP
>>>Pre-Authentication Data:
 PA-DATA type = 16
>>>Pre-Authentication Data:
 PA-DATA type = 15
AcquireTGT: PREAUTH FAILED/REQUIRED, re-send AS-REQ
Updated salt from pre-auth = DOMAIN.LOCALskadar
>>>KrbAsReq salt is DOMAIN.LOCALskadar
Pre-Authenticaton: find key for etype = 3
AS-REQ: Add PA_ENC_TIMESTAMP now
>>> EType: sun.security.krb5.internal.crypto.DesCbcMd5EType

A: Use SPNEGO/Kerberos Authenticator and Active Directory Realm for Apache Tomcat 6 if you are on Tomcat.


text:
Q: Find the variable with the most data in dataset I have a technical question for you, please.
STATION NOM LONGITUDE   LATITUDE    ALTITUDE    DATE    RR  DRR TM  DG  TNTXM   FFM DXI HNEIGEF NEIGETOT06
34008001    LES AIRES(LA GARENE)    3`06'30"E   43`35'00"N  190 2006/01/01  3.2     8.2     7.3         0   0
34008001    LES AIRES(LA GARENE)    3`06'30"E   43`35'00"N  190 2006/01/02  0       7.4     8           0   0
34008001    LES AIRES(LA GARENE)    3`06'30"E   43`35'00"N  190 2006/01/03  0       6       6.6         0   0
34008001    LES AIRES(LA GARENE)    3`06'30"E   43`35'00"N  190 2006/01/04  0       3.5     5.8         0   0
34008001    LES AIRES(LA GARENE)    3`06'30"E   43`35'00"N  190 2006/01/05  2       -0.4        -0.4            1   0
34008001    LES AIRES(LA GARENE)    3`06'30"E   43`35'00"N  190 2006/01/06  35.4        4.1     3.5         0   1
34008001    LES AIRES(LA GARENE)    3`06'30"E   43`35'00"N  190 2006/01/07  10      5.7     5.8         0   0
34008001    LES AIRES(LA GARENE)    3`06'30"E   43`35'00"N  190 2006/01/08  17.4        6       5.9         0   0
34008001    LES AIRES(LA GARENE)    3`06'30"E   43`35'00"N  190 2006/01/09  24.6        5.3     5.3         0   0
34008001    LES AIRES(LA GARENE)    3`06'30"E   43`35'00"N  190 2006/01/10  0.2     5.3     8.4         0   0
34008001    LES AIRES(LA GARENE)    3`06'30"E   43`35'00"N  190 2006/01/11  0.2     1       3.3         0   0
34008001    LES AIRES(LA GARENE)    3`06'30"E   43`35'00"N  190 2006/01/12  0.2     4.8     6.1         0   0
34008001    LES AIRES(LA GARENE)    3`06'30"E   43`35'00"N  190 2006/01/13  1.4     3.7     3.6         0   0
34008001    LES AIRES(LA GARENE)    3`06'30"E   43`35'00"N  190 2006/01/14  1.8     5.3     5.7         0   0
34008001    LES AIRES(LA GARENE)    3`06'30"E   43`35'00"N  190 2006/01/15  39.2        5.2     5.5         0   0
34010001    ANIANE(GEND.)   3`34'54"E   43`40'54"N  65  2006/08/14  0                           0   0
34010001    ANIANE(GEND.)   3`34'54"E   43`40'54"N  65  2006/08/15  28                          0   0
34010001    ANIANE(GEND.)   3`34'54"E   43`40'54"N  65  2006/08/16  0                           0   0
34010001    ANIANE(GEND.)   3`34'54"E   43`40'54"N  65  2006/08/17  0.6                         0   0
34010001    ANIANE(GEND.)   3`34'54"E   43`40'54"N  65  2006/08/18  0                           0   0
34010001    ANIANE(GEND.)   3`34'54"E   43`40'54"N  65  2006/08/19  0                           0   0
34010001    ANIANE(GEND.)   3`34'54"E   43`40'54"N  65  2006/08/20  0                           0   0
34010001    ANIANE(GEND.)   3`34'54"E   43`40'54"N  65  2006/08/21  0                           0   0
34010001    ANIANE(GEND.)   3`34'54"E   43`40'54"N  65  2006/08/22  0                           0   0
34010001    ANIANE(GEND.)   3`34'54"E   43`40'54"N  65  2006/08/23  0                           0   0
34010001    ANIANE(GEND.)   3`34'54"E   43`40'54"N  65  2006/08/24  0                           0   0
34010001    ANIANE(GEND.)   3`34'54"E   43`40'54"N  65  2006/08/25  7.5                         0   0
34010001    ANIANE(GEND.)   3`34'54"E   43`40'54"N  65  2006/08/26  0                           0   0
34010001    ANIANE(GEND.)   3`34'54"E   43`40'54"N  65  2006/08/27  0                           0   0
34010001    ANIANE(GEND.)   3`34'54"E   43`40'54"N  65  2006/08/28  0                           0   0
34010001    ANIANE(GEND.)   3`34'54"E   43`40'54"N  65  2006/08/29  0                           0   0
34010001    ANIANE(GEND.)   3`34'54"E   43`40'54"N  65  2006/08/30  0                           0   0
34010001    ANIANE(GEND.)   3`34'54"E   43`40'54"N  65  2006/08/31  0                           0   0
34010001    ANIANE(GEND.)   3`34'54"E   43`40'54"N  65  2006/09/01  0
34028003    BEDARIEUX(AERODROME)    3`08'42"E   43`38'24"N  373 2008/10/20  4       16.6    0   17.5    1.8 140
34028003    BEDARIEUX(AERODROME)    3`08'42"E   43`38'24"N  373 2008/10/21  23.6        17  0   16.7    2.6 140
34028003    BEDARIEUX(AERODROME)    3`08'42"E   43`38'24"N  373 2008/10/22  0       11.5    0   11.4    4.9 320
34028003    BEDARIEUX(AERODROME)    3`08'42"E   43`38'24"N  373 2008/10/23  0.4     9.8 0   10.4    2.8 340
34028003    BEDARIEUX(AERODROME)    3`08'42"E   43`38'24"N  373 2008/10/24  0.8     11.6    0   11.6    1.1 20
34028003    BEDARIEUX(AERODROME)    3`08'42"E   43`38'24"N  373 2008/10/25  0.2     14.6    0   15.6    2.8 340
34028003    BEDARIEUX(AERODROME)    3`08'42"E   43`38'24"N  373 2008/10/26  0       14  0   14.8    2.7 340
34028003    BEDARIEUX(AERODROME)    3`08'42"E   43`38'24"N  373 2008/10/27  5.4     13.3    0   14.3    1   180
34028003    BEDARIEUX(AERODROME)    3`08'42"E   43`38'24"N  373 2008/10/28  2.6     9.8 0   10.1    3.8 340
34028003    BEDARIEUX(AERODROME)    3`08'42"E   43`38'24"N  373 2008/10/29  0       6.8 0   7.1 5.4 340
34028003    BEDARIEUX(AERODROME)    3`08'42"E   43`38'24"N  373 2008/10/30  1.8     4   0   3.8 1.2 260
34028003    BEDARIEUX(AERODROME)    3`08'42"E   43`38'24"N  373 2008/10/31  0.8     10.9    0   9.2 3.1 120
34028003    BEDARIEUX(AERODROME)    3`08'42"E   43`38'24"N  373 2008/11/01  11.8        14.9    0   15  4.9 100
34028003    BEDARIEUX(AERODROME)    3`08'42"E   43`38'24"N  373 2008/11/02  36      13  0   13.2    5.3 100
34028003    BEDARIEUX(AERODROME)    3`08'42"E   43`38'24"N  373 2008/11/03  0.2     10.3    0   11.3    2.5 120
34028003    BEDARIEUX(AERODROME)    3`08'42"E   43`38'24"N  373 2008/11/04  27.8        10.2    0   10.3    1.7 320
34028003    BEDARIEUX(AERODROME)    3`08'42"E   43`38'24"N  373 2008/11/05  13.6        9   0   9.1 1.3 300
34028003    BEDARIEUX(AERODROME)    3`08'42"E   43`38'24"N  373 2008/11/06  0.4     9.3 0   9.4 1.3 320
34028003    BEDARIEUX(AERODROME)    3`08'42"E   43`38'24"N  373 2008/11/07  0       10.2    0   11.1    1.4 360
34028003    BEDARIEUX(AERODROME)    3`08'42"E   43`38'24"N  373 2008/11/08  0.4     10  0   12.1    1.2 120

I have weather data. From variable "RR" to "NEIGETOT06" they are meteorological parameters (9 variables). The problem is that I have very well informed stations and others much less informed. For some stations there are variables with only N'A.
I would like to know which stations have the most data. I would like to find a function that would tell me which are the stations with the most variables filled and which are the stations with the less filled variables. For example station 1 and 2, 6 variables with information (ex RR, DRR ...), stations 3-4, 4 variables with information ... Do you think it would be possible please?
Thank you all!

A: Here's a solution (based on a similar dataset in which there's actually missing values):
rbindlist(lapply(unique(df$STATION), function(m) data.frame(STATION = m, NonNAValues = sum(!is.na(df[df$STATION == m, ])))))

What it does: per station, get the number of all non-NA values (in all columns).
Output:
          STATION NonNAValues
 1:      34010001             448
 2:      34028003             392
 3:      34028007             975

A: Here is an option:
It might be better suited for numeric variables and will not be suitable for many variables.
library(tidyverse)
iris %>%
  mutate_if(is.factor,as.numeric) %>%
map_dbl(~sum(.x)) %>%
  sort(decreasing = T)

If you're only interested in numeric variables then:
iris %>%
  select_if(is.numeric) %>%
  map_dbl(~sum(.x))

Find Missing Values? Then:
iris %>%
  select_if(is.numeric) %>%
  map_dbl(~sum(is.na(.x)))

Cheers!

A: Thank you everybody,
may be a solution like that :
testdata <- matrix(0, nrow = 3000, ncol = 1)

ncol <- c(7:15)
for(i in 1:length(testdata)){
    cat(i,"\r")
  testdata[i] <- length(which(!is.na(WEATHER[i, ncol])))
}

follow :
WEATHER_test <- cbind.data.frame(WEATHER, testdata)
testest <- as.matrix(tapply(WEATHER_test$testdata, WEATHER_test$NOM, FUN = "mean"))

?


text:
Q: R - adjust the y-value of the x axis I have a some data that I want to display graphically. Here's what it looks like:
data<- c(0.119197746, 0.054207788, 0.895580411, 0.64861727, 0.143249592,
0.284314897, 0.070027632, 0.297172433, 0.183569184, 0.713896071,
1.942425326, 1)

Using this command:
barplot(data, main="Ratio of Lipidated and Unlipidated LC3 I & II forms\nNormalized
to GAPDH", names.arg = c("PT250", "PT219", "PT165", "PT218", "PT244", "PT253", "PT279", "PT281",
"PT240", "PT262", "PT264", "CCD"), ylab = "Fold LC3 II/LC3I/GAPDH")

I produced this graph:

I would like to position the X-axis at 1 so that all values less-than-one will appear as down bars. I could achieve the desired affect by simply subtracting 1 from all of the values and plotting again but this would cause the numbers on the y-axis to be inaccurate. Is there some way to get R to plot values less than 1 as down bars?

A: Solution with custom axis.
barplot(data - 1, main="Ratio of Lipidated and Unlipidated LC3 I & II forms\nNormalized
to GAPDH", names.arg = c("PT250", "PT219", "PT165", "PT218", "PT244", "PT253", "PT279", "PT281",
                         "PT240", "PT262", "PT264", "CCD"), ylab = "Fold LC3 II/LC3I/GAPDH",
         axes = F, ylim = c(-1, 1)
my_labs <- seq(-1, 1, by = 0.5)
axis(side = 2, at = my_labs, labels = my_labs + 1)


text:
Q: How can i stream media via Bluetooth mono? I have a Samsung galaxy note 10 plus, which is rooted with magisk if that makes any difference.
My car only supports calls.
I want to stream my music, as though it is a call, to my car. I have considered setting up a ras pi with some program I'm sure I could make to get it to streak music it takes from the Bluetooth of my phone, to a call that is connected back to my phone and therefore coming through the car.
But I would rather find some way to use only my phone. I have tried a few Bluetooth mono router apps but they are either inconsistent or don't work at all, unless I am missing something.
If it makes any difference I ideally want to stream via yt music vanced however I have been testing with other apps also.


text:
Q: TypeScript can't implement interface Given the following interface
interface Expando {
    new<T extends {}>(template: T): T & Expando;
}

I tried to implement this like so
class Expando implements ExpandoConstructor {
    constructor(template: {}) {

    }
}

But I get an error because the constructor definition is incomplete. How do I implement this interface?

A: You can't have a class implement a constructor interface because this interface describes static properties of the class.
You can do this:
interface ExpandoConstructor {
    new<T extends {}>(template: T): T & Expando;
}

class Expando {
    constructor(template: {}) {}
}

let ctor = Expando as ExpandoConstructor;
let instance = new ctor({});

(code in playground)


text: Q: How do I run as bash script from a WebApp? I currently am developing a custom Ubuntu dist. that runs a dedicated Kiosk app upon boot. I would like an easy method to shutdown from inside the Kiosk app, but I am currently at a standstill at what I can do to run a bash script from the app itself. The Kiosk app (custom, and proprietary) that I am using, is a WebApp. I know what the bash script is suppose to contain to shut down the system, but I can't figure out how to actually execute the script from the Kiosk WebApp. Any help?


text:
Q: Mobile images slider I want to do a mobile webpage, which in the middle of the webpage, I will be able to swipe my finger to the left/right and scroll between images there.
a photo to demonstrate:

I wanna be able to swipe between the censored images with my finger.
How do I do such a thing?
Thanks in advance!

A: You're looking for a cover-flow like thing. This might guide you in the proper direction : http://andrebrov.net/dev/carousel/
Source Link : http://forum.jquery.com/topic/jquery-mobile-carousel-widget
GITHUB Link : https://github.com/andrebrov/jqm.carousel
Here's how the HTML would look like :

Then, the initialisation would go this way :
var carousel = new $.widgets.Carousel({
    uuid: "carousel",
    args: {
        "scrollInterval": 600,
        "itemWidth": 290
    },
    value: [{
        "title": "Tron.Legacy",
        "image": "images/1.jpg"
    }, {
        "title": "Yogi Bear",
        "image": "images/2.jpg"
    }, {
        "title": "The Chronicles of Narnia: The Voyage of the Dawn Treader",
        "image": "images/3.jpg"
    }, {
        "title": "The Fighter",
        "image": "images/4.jpg"
    }, {
        "title": "Tangled",
        "image": "images/5.jpg"
    }]
});

Hope this helps!


text:
Q: cor/opacidade em view selecionada Eu implementei um Navigation Drawer (sem mtas modificações do exemplo do Android Developers)
Alterei somente as cores do background do ListView e do Texto dos itens:
layout/activity_main.xml:
<android.support.v4.widget.DrawerLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

<!-- As the main content view, the view below consumes the entire
     space available using match_parent in both dimensions. -->

<FrameLayout
    android:id="@+id/content_frame"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />

<!-- android:layout_gravity="start" tells DrawerLayout to treat
     this as a sliding drawer on the left side for left-to-right
     languages and on the right side for right-to-left languages.
     The drawer is given a fixed width in dp and extends the full height of
     the container. A solid background is used for contrast
     with the content view. -->
<ListView
    android:id="@+id/left_drawer"
    android:layout_width="240dp"
    android:layout_height="match_parent"
    android:layout_gravity="start"
    android:choiceMode="singleChoice"
    android:dividerHeight="0dp"
    android:background="#ffe1e1e1"/>

</android.support.v4.widget.DrawerLayout>

layout/drawer_list_item.xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="48dp"
    android:background="?android:attr/activatedBackgroundIndicator">

<ImageView
    android:id="@+id/icon"
    android:layout_width="25dp"
    android:layout_height="wrap_content"
    android:layout_alignParentLeft="true"
    android:layout_marginLeft="12dp"
    android:layout_marginRight="12dp"
    android:contentDescription="@string/list_item_icon"
    android:src="@drawable/ic_logo_icone"
    android:layout_centerVertical="true"/>

<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/text1"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:textAppearance="?android:attr/textAppearanceListItemSmall"
    android:gravity="center_vertical"
    android:paddingLeft="45dp"
    android:paddingRight="16dp"
    android:textColor="#ff555555"
    android:textStyle="bold"
    android:hint="@string/item_desc"
    android:background="?android:attr/activatedBackgroundIndicator"
    android:minHeight="?android:attr/listPreferredItemHeightSmall" />

</RelativeLayout>

E eis que surge meu Navigation Drawer:

O problema, como vcs podem ver, é que quando o item está selecionado, a cor azul sobrepõe o Icone deixando ele mais apagado, e a cor do texto também é sobreposta tendo uma leve alteração de tonalidade.
Eu gostaria de que meu icone e meu texto nao tivesse alteração de cor, que ficasse azul somente nas áreas brancas da view. Eu já tentei mtas configurações nos XMLs e tentei fazer outras coisas programaticamente também, mas nada resolveu.

A: Consegui resolver o problema. Eis a solução:
Na app de exemplo do Android Developers, é utilizado a seguintes funções para selecionar um item:
    mDrawerList.setItemChecked(position, true);
    mDrawerList.setSelection(position);
    setTitle(mTitles[position]);
    mDrawerLayout.closeDrawer(mDrawerList);

Ai foi sugerido eu fazer manualmente o selection, porém mesmo eu comentando os métodos mDrawerList.setItemChecked(position, true); e mDrawerList.setSelection(position);
ainda continuava selecionado devido a configuração: android:choiceMode="singleChoice" que não poderia ser retirada pois isso impactou em outros problemas no programa.
A solução foi entcontrada ao recarregar o adapter usando a função mDrawerList.setAdapter(adapter); e no meu adapter eu pude fazer manualmente o selection.
Então meu código ficou assim:
    mDrawerList.setItemChecked(position, true);
    mDrawerList.setSelection(position);
    adapter.setSelectedItem(position);
    for(int i = 0; i < DrawerItems.size(); i++){
        DrawerItems.set(i, new DrawerItem(mTitles[i], getResources().obtainTypedArray(R.array.nav_drawer_icons_light).getResourceId(i, -1)));
    }
    DrawerItems.set(position, new DrawerItem(mTitles[position], getResources().obtainTypedArray(R.array.nav_drawer_icons).getResourceId(position, -1)));

    mDrawerList.setAdapter(adapter);
    setTitle(mTitles[position]);
    mDrawerLayout.closeDrawer(mDrawerList);

E meu adapter assim:
public class DrawerAdapter extends BaseAdapter {

 (...)
 private int mSelectedItem = -1;

 (...)

  @Override
  public View getView(int position, View convertView, ViewGroup parent) {
    if (convertView == null) {
        LayoutInflater mInflater = (LayoutInflater)
                context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
        convertView = mInflater.inflate(R.layout.drawer_list_item, null);
    }

    RelativeLayout container = (RelativeLayout) convertView.findViewById(R.id.drawer_item_container);
    ImageView imgIcon = (ImageView) convertView.findViewById(R.id.icon);
    TextView txtTitle = (TextView) convertView.findViewById(R.id.text1);

    if(position == mSelectedItem){
        txtTitle.setTextColor(context.getResources().getColor(R.color.white));
        container.setBackgroundColor(context.getResources().getColor(R.color.blue));
    } else {
       txtTitle.setTextColor(context.getResources().getColor(R.color.drawer_text_unselected));
       container.setBackgroundColor(context.getResources().getColor(R.color.drawer_background));
    }

    imgIcon.setImageResource(DrawerItems.get(position).getIcon());
    txtTitle.setText(DrawerItems.get(position).getTitle());

    return convertView;
  }

  public void setSelectedItem(int position){
      mSelectedItem = position;
  }
}


text:
Q: Tricky Indented Contour Integral of $\int_{0}^{\infty} \frac{x^{3/4}}{(x^2+1)^2} \ dx$
I am trying to evaluate the integral  $$\int_{0}^{\infty} \frac{x^{3/4}}{(x^2+1)^2} \ dx,$$ by finding a suitable branch of $z^{3/4}$ and integrating the function $z\rightarrow z^{3/4}/(z^2+1)^2$ around the contour below:

$\hskip2in$
I am unsure of how to deal with the branch cut. I know that $w^{1/n}$ is not differentiable for $(-\infty,0]$, but I am unsure what to do, as the contour above includes the negative real axis.
So far, I have show by the ML lemma that for $r<1<R$, $$\int_{\Gamma_1} f(z) \ dz\rightarrow 0 \ \text{as} \ R\rightarrow\infty.$$ Similarly, $$\int_{\Gamma_2} f(z) \ dz\rightarrow 0 \ \text{as} \ r\rightarrow 0.$$ I am having trouble solving the line segments. For $0<\delta<\frac{\pi}{2}$, I have shown that as $\delta\rightarrow 0$, the sum of both line segments equals $0$... but this cannot be correct.
Any advice is greatly appreciated.

A: Take the branch cut as the positive real axis. Then you have a branch of
$z^{3/4}$ given by $re^{it}\mapsto r^{3/4}e^{3it/4}$ for $0\le t<2\pi$.
By continuity, on the "lower" horizontal segment of your contour $x^{3/4}$ becomes
$x^{3/4}e^{3\pi i/2}=-ix^{3/4}$.
Alternatively avoid the branch cut by making a preliminary substitution
$x=y^4$ or $x=e^y$.

A: $z^{\frac{3}{4}}=\exp(\frac{3}{4}\ln z)$
Below x-axis $\int_\infty ^0\frac{\exp(\frac{3}{4}\ln x+2\pi i)}{1+x^2}\mathrm dx=\int_0^\infty\frac{ix^{\frac{3}{4}}}{1+x^2}\mathrm dx$
So sum of the two path parallel to the x-axis is $(1+i)\int_0^\infty\frac{x^{\frac{3}{4}}}{1+x^2}\mathrm dx$


text:
Q: Typescript,'NodeListOf' is not an array type or a string type Converting my JS to TS strict mode.
The following syntax looks fine to me but TS is complaining in the for loop on allSubMenus with:
[ts] Type 'NodeListOf<Element>' is not an array type or a string type.

What am I missing?
function subAct(target:Node){

  const allSubMenus : NodeListOf<Element> = document.querySelectorAll('.subMenuItems')

  for (const sub of allSubMenus){
    sub.classList.remove('active')
  }
}

A: You could try
const allSubMenus : NodeListOf<Element> = document.querySelectorAll('.subMenuItems')
Array.from(allSubMenus, subMenu => {/* */})

A: You need to set the target compiler option to es6 or higher for NodeListOf<T> to be iterable.

A: According to your typescript target compiler, parsing error can be occured.
The for-of loop, introduced in the sixth edition of EcmaScript (ES6). Thus, old browsers' JS engine can not understand for-of loop syntax.
https://hacks.mozilla.org/2015/04/es6-in-depth-iterators-and-the-for-of-loop/
To solve this issue,
if you support latest modern browsers(>=ES6) only
change your TS target
//tsconfig.json
{
  "compilerOptions": {
    "target": "es6" //above es6 like ES2015,ES2018 ...
  }
}

if you support old browsers(<=ES5)
I presume that you are using next environment.
//.tsconfig.json
{
  "compilerOptions": {
    "target": "es5"
  }
}

*

*To keep for-of loop, use as any syntax

Note: "as any" will cast collection(Objects) to array and this will affect some type features within "for" scope.
//.ts
const allSubMenus : NodeListOf<SpecifiedElement> = document.querySelectorAll('.subMenuItems')

for (const sub of allSubMenus as any){ // then will pass compiler
  sub.classList.remove('active')
}

The above TS script will be compiled to
//.js output
var allSubMenus = document.querySelectorAll('.subMenuItems');

for (var _a = 0, _b = forms; _a < _b.length; _a++) {
    var sub = _b[_a];
    sub.classList.remove('active');
}

https://stackblitz.com/edit/node-ywn1bq?file=main.js

*Use classic for-loop syntax

const allSubMenus : NodeListOf<SpecifiedElement> = document.querySelectorAll('.subMenuItems')

for (let i = 0; i < allSubMenus.length; i++) {
  allSubMenus[i].classList.remove('active');
}

<Element>
In addition to the above, to avoid the following warning,
Property '<property name>' does not exist on type 'Element'

you may specify <Element> if you know element type and type define exists.
//for example,
NodeListOf<Element>  => NodeListOf<HTMLFormElement>

ECMAScript(ES) history
https://codeburst.io/javascript-wtf-is-es6-es8-es-2017-ecmascript-dca859e4821c

A: Set "downlevelIteration": true in compilerOptions in your tsconfig.json file.
From https://www.typescriptlang.org/tsconfig#downlevelIteration

Downleveling is TypeScript's term for transpiling to an older version of JavaScript. This flag is to enable support for a more accurate implementation of how modern JavaScript iterates through new concepts in older JavaScript runtimes

A: You can iterate over a NodeListOf with the forEach method.
const allSubMenus : NodeListOf<Element> = document.querySelectorAll('.subMenuItems')
allSubMenus.forEach(sub => sub.classList.remove('active'))

Source: https://microsoft.github.io/PowerBI-JavaScript/interfaces/_node_modules_typedoc_node_modules_typescript_lib_lib_dom_d_.nodelistof.html#foreach

A: while compiling your code you may choose target: ES2017 or target: ES2015. also you can set this property in tsconfig.json file unser compilerOptions.
So here is the command line code for that:
npx tsc path/to/file.ts --target ES2015

TIP:
if you are using babel along side with typescript, it is totally recommended that you always make typescript to compile to latest version of Javascript, and then let babel handles rest of transpiring process. With this technique you add another lever of assurance of supportive level to older browsers since typescript is not ok to compile the code that would run in for example ie6; so babel comes to rescue here and make you yo make sure that your js code would run in even ie < 9 with it's helpful polyfills and other mechanisms that it takes to work!
So keep in mind that:
Always let typescript compiles your code to latest javascript ( by setting target: ES2017 ) and let babel transpiles your js code to support older browsers ( separate concerns properly and let each one does the related job).

A: This assumes you want to keep ES5 target (if not, upgrading it to ES6 will solve the issue as well).

*

*Use for loop

function subAct(target:Node){
  const allSubMenus = document.querySelectorAll('.subMenuItems');

  for (let i = 0; i < allSubMenus.length; i += 1){
    const sub = allSubMenus[i];
    sub.classList.remove('active')
  }
}

*Use Array.from
In order to use this, you have to add ES2015.core to compilerOptions.lib and add polyfill for Array.prototype.from Note that this will loop on the collection twice - the first method is better.
function subAct(target:Node){
  const allSubMenus = Array.from(document.querySelectorAll('.subMenuItems'));

  for (const sub of allSubMenus){
    sub.classList.remove('active')
  }
}


text:
Q: Chef - Best way to copy file from a remote host I am trying to copy a file from a remote server to the chef client. I tried to use remote_file resource with ftp source but it requires ftp server to be installed on the chef client. Is there any way to copy a file from remote server to chef-client without explicitly installing anything on the client? I followed https://docs.chef.io/resource_remote_file.html

A: The best way is to put the file on a web server (or conversely run a simple web server where the file already is) and then use the remote_file resource.


text:
Q: Selenium - Find link text containing random string I have to verify that this link exists on a page, and the link contains a random string of numbers between a file name and a date, similar to this:
Report-7895198-01282016.zip
I'm assuming I can use something like this:
driver.findElement(By.linkText("Report-" + somesortofregex + "-01282016.zip"))

How would I go about accomplishing this using linkText, or is there a better option?

A: you can use xpath here.. some thing like below
 //a[contains(text(),'Report-')][contains(text(),'-01282016.zip')]

please provide HTML code of the element to provide possible locators in this case.
Thank You,
Murali


text:
Q: Looping through input fields for validation using Jquery each() I'm making a form and would like the code to execute only if the input values are numbers. I'm trying to avoid using some kind of validation plugin and was wondering if there is a way to loop through the input fields and check for the values.
I've been trying the following but I think my logic is wrong:
(#monthlyincome is the form id)
$("#submit").click(function() {

  $("#monthlyincome input").each(function() {

       if (!isNaN(this.value)) {
       // process stuff here

       }

   });

});

Any ideas?
This is the whole updated code:
$("#submit").click(function() {

    $("#monthlyincome input[type=text]").each(function() {
        if (!isNaN(this.value)) {
            // processing data
            var age         = parseInt($("#age").val());
            var startingage = parseInt($("#startingage").val());

            if (startingage - age > 0) {

                $("#field1").val(startingage - age);
                $("#field3").val($("#field1").val());

                var inflationyrs    = parseInt($("#field3").val());
                var inflationprc    = $("#field4").val() / 100;
                var inflationfactor = Math.pow(1 + inflationprc, inflationyrs);
                $("#field5").val(inflationfactor.toFixed(2));

                var estyearlyinc    = $("#field6").val();
                var inflatedyearlyinc = inflationfactor * estyearlyinc;
                $("#field7").val(FormatNumberBy3(inflatedyearlyinc.toFixed(0), ",", "."));

                var estincyears = $("#field2").val();
                var esttotalinc = estincyears * inflatedyearlyinc;
                $("#field8").val(FormatNumberBy3(esttotalinc.toFixed(0), ",", "."));

                var investmentrate   = $("#field9").val() / 100;
                var investmentfactor = Math.pow(1 + investmentrate, inflationyrs);
                $("#field10").val(investmentfactor.toFixed(2));

                var currentsavings = $("#field11").val();
                var futuresavings  = currentsavings * investmentfactor;
                $("#field12").val(FormatNumberBy3(futuresavings.toFixed(0), ",", "."));

                //final calculations
                var futurevalue = (1 * (Math.pow(1 + investmentrate, inflationyrs) - 1) / investmentrate);
                var finalvalue = (1 / futurevalue * (esttotalinc - futuresavings));

                $("#field13").val(FormatNumberBy3(finalvalue.toFixed(0), ",", "."));

            }
            // end processing
        }
    });

});

FormatNumberBy3 is a function for... formatting the numbers. :)

A: Well testing here this works just fine:
$(function() {
    $("#submit").click(function() {
        $("#myForm input[type=text]").each(function() {
            if(!isNaN(this.value)) {
                alert(this.value + " is a valid number");
            }
        });
        return false;
    });
});

on a form looking like this:
<form method="post" action="" id="myForm">
    <input type="text" value="1234" />
    <input type="text" value="1234fd" />
    <input type="text" value="1234as" />
    <input type="text" value="1234gf" />
    <input type="submit" value="Send" id="submit" />
</form>

Move the return false around as you see fit
Edit: link to code sdded to OPs form
http://pastebin.com/UajaEc2e

A: The value is a string. You need to try to convert it to a number first. In this case a simple unitary + will do the trick:
if (!isNaN(+this.value)) {
  // process stuff here
}

A: Based on Sondre (Thank you! Sondre) example above, I developed a sample in Fiddle so that Folks can understand much better to implement
Example: Click Here

$("#submit").on("click", function() {
  var isValid = [];
  var chkForInvalidAmount = [];
  $('.partialProdAmt').each(function() {
    if ($.trim($(this).val()) <= 0) {
      isValid.push("false");
    } else {
      isValid.push("true");
    }
    if ($.isNumeric($(this).val()) === true) {
      chkForInvalidAmount.push("true");
    } else {
      chkForInvalidAmount.push("false");
    }
  });
  if ($.inArray("true", isValid) > -1) {
    if ($.inArray("false", chkForInvalidAmount) > -1) {
      $(".msg").html("Please enter Correct format ");
      return false;
    } else {
      $(".msg").html("All Looks good");
    }
  } else {
    $(".msg").html("Atlest One Amount is required in any field ");
    return false;
  }

});

<form method="post" action="" id="myForm">
  <input type="text" class="partialProdAmt" value="0" />
  <input type="text" class="partialProdAmt" value="0" />
  <input type="text" class="partialProdAmt" value="0" />
  <input type="text" class="partialProdAmt" value="0" />
  <input type="button" value="Send" id="submit" />
</form>


text:
Q: Django: ValueError: too many values to unpack I'm getting a ValueError, and I cannot figure the bug out for the life of me. I am aware that the error means there are more values being passed to a variable than expected (ie, (x, y) = 1, 2, 3), but I don't see why that's a problem here.
This is where the error is (in a views.py file):
## image_pks is just a list of ImageItem primary keys (eg, [1, 2] or [5])
queryset = ImageItem.objects.filter(pk__in=image_pks)
ImageInfoFormset = modelformset_factory(ImageItem, fields=('title', 'caption'), extra=0)
formset = ImageInfoFormset(queryset) ## Error happening here!!!

This is what the ImageItem model looks like:
class ImageItem(models.Model):
    user = models.ForeignKey(User)
    upload_date = models.DateTimeField(auto_now_add=True)
    last_modified = models.DateTimeField(auto_now=True)
    library = models.ForeignKey(Library)
    img_big = models.ImageField(upload_to=img_get_file_path)
    img_363 = models.ImageField(upload_to=img_get_file_path)
    title = models.CharField(max_length=50,
                             blank=True)
    caption = models.CharField(max_length=1000,
                               blank=True)

This is the information on traceback:

And here are the local variables on the traceback:

Let me know if you guys need any more information, thanks!
EDIT: here is the entire traceback provided:
Traceback:
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response
  111.                         response = callback(request, *callback_args, **callback_kwargs)
File "/Users/sgarza62/riotry_master/riotry/backboard_general/views.py" in Backboard_Home
  44.                 formset = ImageInfoFormset(queryset) # TOO MANY VALUES ERROR HERE!
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/forms/models.py" in __init__
  424.         super(BaseModelFormSet, self).__init__(**defaults)
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/forms/formsets.py" in __init__
  50.         self._construct_forms()
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/forms/formsets.py" in _construct_forms
  114.         for i in xrange(self.total_form_count()):
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/forms/formsets.py" in total_form_count
  88.             return self.management_form.cleaned_data[TOTAL_FORM_COUNT]
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/forms/formsets.py" in _management_form
  74.             if not form.is_valid():
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/forms/forms.py" in is_valid
  124.         return self.is_bound and not bool(self.errors)
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/forms/forms.py" in _get_errors
  115.             self.full_clean()
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/forms/forms.py" in full_clean
  270.         self._clean_fields()
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/forms/forms.py" in _clean_fields
  281.             value = field.widget.value_from_datadict(self.data, self.files, self.add_prefix(name))
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/forms/widgets.py" in value_from_datadict
  205.         return data.get(name, None)
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/db/models/query.py" in get
  358.         clone = self.filter(*args, **kwargs)
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/db/models/query.py" in filter
  624.         return self._filter_or_exclude(False, *args, **kwargs)
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/db/models/query.py" in _filter_or_exclude
  642.             clone.query.add_q(Q(*args, **kwargs))
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/db/models/sql/query.py" in add_q
  1250.                             can_reuse=used_aliases, force_having=force_having)
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/db/models/sql/query.py" in add_filter
  1056.         arg, value = filter_expr

Exception Type: ValueError at /backboard/
Exception Value: too many values to unpack

EDIT 2:
I'm playing around with it, and there's something strange happening. When I change the line queryset = ImageItem.objects.filter(pk__in=image_pks) to queryset = ImageItem.objects.get(pk=10) (where 10 is an arbitrary id), I get the following error: AttributeError: 'ImageItem' object has no attribute 'get', and the originally problematic line is throwing the error!
It's a strange error, because ImageItem is just a normal model. Of course it has the attribute 'get'. Does this have something to do with fact that the queryset is first being evaluated on the problematic line (formset = ImageInfoFormset(queryset))? Is ImageItem being assigned to something else after the query is written, but before it is evaluated?

A: Try getting rid of the queryset= definition (your first line) and doing the following instead:
ImageInfoFormset = modelformset_factory(ImageItem, fields=('title', 'caption'), extra=0)
formset = ImageInfoFormset(queryset=ImageItem.objects.filter(pk__in=image_pks))

You have to explicitly define that you are changing the queryset, otherwise you are just passing another variable to the formset.
See the docs here.

A: I would try with `formset = ImageInfoFormset(queryset.values())
formset = ImageInfoFormset(queryset.values())

instead of
formset = ImageInfoFormset(queryset)


text:
Q: Use value in override error message in Rails 4 for custom Validator I am on Rails 4.2 I have written a custom Validator which will check if a value being entered exists in another table. I have been reviewing some other posts and it seems there is either a context specific or rails version preferred way to reuse the value being validated. In the rails docs i see examples such as:
validates :subdomain, exclusion: { in: %w(www us ca jp),
    message: "%{value} is reserved." }

however, if I try to use %{value} in my custom message override it does not interpolate, but just prints "%{value}". I have seen various ways of calling "value". I also could not get %{value} to work in my Validator definition, but could get #{value} to work (New to ruby, if#{value} getting it from validate_each?).
I have also been struggling with various formats of the validation statement and putting in the custom message. Some things which look repeatable from the docs are not. If the way I am declaring my custom message is causing the error, please let me know how to correct?
class ExistingGroupValidator < ActiveModel::EachValidator
  def validate_each(record, attribute, value)
    unless Group.where(:code => value).any?
     record.errors[attribute] << (options[:message] || "#{value} is not a valid
group code")
    end
  end
end

class Example < ActiveRecord::Base
  validates :group_code, presence: true
  validates :group_code, :existing_group => {:message => "The code you have enterd ( **what goes here?** ) is not a valid code, please check with your teacher or group
leader for the correct code." }

end

A: Rails automatically puts the value at the beginning of the phrase, so you can just do this:
class ExistingGroupValidator < ActiveModel::EachValidator
  def validate_each(record, attribute, value)
    unless Group.where(code: value).any?
     record.errors[attribute] << (options[:message] || 'is not a valid group code')
    end
  end
end

class Example < ActiveRecord::Base
  validates :group_code, presence: true
  validates :group_code, existing_group: {message: 'is not a valid code, please check with your teacher or group leader for the correct code.' }
end

Separately, note that it is always "#{1+1}" to interpolate not %.

A: Rails is using Internationalization style string interpolation to add the value to the message.   You can use the I18n.interpolate method to accomplish this. Something like this should do the trick:
class ExistingGroupValidator < ActiveModel::EachValidator
  def validate_each(record, attribute, value)
    unless Group.where(:code => value).any?
     record.errors[attribute] << (I18n.interpolate(options[:message], {value: value}) || "is not a valid group code")
    end
  end
end

class Example < ActiveRecord::Base
  validates :group_code, presence: true
  validates :group_code, :existing_group => {:message => "The code you have entered, "%{value}", is not a valid code, please check with your teacher or group   leader for the correct code." }
end


text:
Q: iPhone Filling UITableView with JSON results (using search entered in UISearchBar) Does anyone have a link to a tutorial for using a UISearchBar as the entry for a search, and a UITableView to display results returned in JSON?
Thank you!
Please no suggestions to RTFM - I can't find anything about using a UISearchBar for a remote search.

A: Implement the UISearchBarDelegate methods in your class. Then you can hit the web service in this delegate method
- (void)searchBarTextDidEndEditing:(UISearchBar *)searchBar
{
//Hit the webservice from here using searchBar.text

}

or if u need a dynamic search you can use the following method.
- (void)searchBar:(UISearchBar *)theSearchBar textDidChange:(NSString *)searchText {

}

After getting the data from the server update the datasource of your tableView and call the
(You can use SBJSON parser to parse your JSON response)
[self.tableView reloadData];


text:
Q: MySQL several inner joins vs subquery i have a problem with making a complicated query easier without the need to build the query with PHP.
My problem:
A product can have several properties eg. a color, a size and a state.
To get a product which has all 3 properties i can:
products p

INNER JOIN product_propeties p1 on p.pid = p1.pid AND p1.property = 1 (color)

INNER JOIN product_propeties p2 on p.pid = p2.pid AND p2.property = 2 (size)

INNER JOIN product_propeties p3 on p.pid = p3.pid AND p3.property = 3 (state)

This works fine. I will get all products which have all this 3 properties.
My problem is now that i dont want to generate p1,p2,p3 with PHP. The properties are listed in a table "property_groups". In this table i can group properties.
proberty|title|group_name

1|color|winterspecial

2|size|winterspecial

3|state|winterspecial

I want to join the "property_groups" table with "winterspecial" and my example from above i dont know how. Problem is that each property needs to exists. Several single joins do the job. But how to do it in a single MySQL Query.
With PHP i select all "winterspecial" and then i build the query with p1,p2...
There must be a better way. Beware that the properties must be AND connectet.
OR is easy this would be a simple subselect.
INNER JOIN product_propeties p1 on p.pid = p1.pid AND product_propeties IN (
    SELECT * FROM property_groups WHERE "winterspecial"
)

A: This may look a bit clumsy, but is the only thing I can come up with at the moment...
In order to know whether a product has all winterspecial properties, we could count all existing winterspecial properties and the product's winterspecial properties and then compare the two numbers.
Then we can select from products and product_properties where the product ID is in the found set:
select ...
from products p
join product_properties pp on pp.pid = p.pid and pp.property in
  (select property from property_groups where group_name = 'winterspecial')
where p.pid in
(
  select pid
  from product_properties
  where property in
    (select property from property_groups where group_name = 'winterspecial')
  group by pid
  having count(*) =
    (select count(*) from property_groups where group_name = 'winterspecial')
);

A: Ahhh, I think I get the problem now.  You seem to want all products that have the properties in the property_groups table, for a given group.
Here is an approach.  Do a cross join to generate the list of products and properties.  Then do a left join to match to product_properties.  With an aggregation, you can easily tell if all the desired properties match an existing property:
select p.*
from products p cross join
     property_groups g left join
     product_properties pp
     on pp.pid = p.id and pp.property = g.property
where g.group_name = 'winterspecial'
group by p.id
having count(distinct pp.property) = count(distinct g.property)

You can actually simply the having clause to one of these:
having sum(pp.property is null) = 0           -- no null values
having count(pp.property) = count(g.property) -- all match

These should all be equivalent.


text:
Q: A new imaginary number? $x^c = -x$ Being young, I don't have much experience with imaginary numbers outside of the basic usages of $i$. As I was sitting in my high school math class doing logs, I had an idea of something that would allow solving for logs with negative bases or with negative arguments. Taking a similar idea to i, this number, when used as an exponent, would result in a negative number. In other words, as the title says, $x^c = -x$.
For starters, I just quickly mentally ran through simple examples of how it could be used in these cases, (ex. $\log(-100) = 2c$) but I soon began to wonder if it could have other applications and or just if it could be anything else.
I'm also not 100% sure what to tag it, so I kinda guessed.

A: Log of negative numbers can be expressed with usual complex numbers: $\ln(-1)=\pi i$.

A: $x^c = e^{c \log x} = -x = e^{\pi i + \log(x)}$ if $c \log x = \log(x) + (2 n + 1) \pi i $ for some integer $n$.  Thus the answer is $c = 1 + \frac{(2n + 1) \pi i}{\log x}$
(assuming, of course, $x \ne 1$).

A: Robert's answer tells you correctly how to find, given an $x$, a complex $c$ such that $x^c=-x$.
However, it is worth pointing out that you cannot find a single $c$ such $x^c=-x$ will hold for every $x$. There's no existing number that achieves this, and if you try to extend the number system by simply postulating that $c$ exists (which I think was the point of the question), you run into this:
$$ 0 = \frac08 = \frac{-4+4}{8} = \frac{4^c+4}8 = \frac{2^c2^c+4}8 = \frac{(-2)(-2)+4}8 = \frac{4+4}8 = 1 $$
So if you want your $c$ to exist, but don't want to collapse everything into $0=1$, then you have to discard the exponentiation rule $(ab)^c=a^cb^c$. And without that rule, the result isn't really worthy of being called exponentiation in the first place.
I think you have been fooled by a common introduction to complex numbers, which goes like this: "There is no real number whose square is $-1$, but assume we had such a number anyway and call it $i$. Then we can calculate with the assumption $i^2=-1$, and, ta-dah! we have invented a new kind of numbers". This presentation, however, sweeps an important point under the carpet, namely that we had better be sure that assuming $i^2=-1$ doesn't allow us to prove falsehoods such as $0=1$ about the real numbers that we already know and love -- because if it does that means that we haven't invented a new kind of numbers but simply deceived ourselves.
For $i^2=-1$ it turns out that it's not too difficult to prove that it doesn't lead to nonsense. But even when this proof is shown, something is still swept under the carpet here, namely that if we assume $i^2=-1$ and the familiar rule that every number is either 0 or positive or negative (and the usual rules for positive and negative numbers), then we can still derive nonsense. So what's really true is that we can get a $\sqrt{-1}$ if and only if we're willing to drop what we know about positive and negative numbers (or "less than"/"greater than") when we're working with complex numbers.
Extending the concept of number is almost always connected to a loss of some rules that used to hold before the extension. How far we can push the extension depends on how many rules we're willing to let go of. So you can have your $c$, but the cost you must pay is the rules for how exponentiation works. And if you pay that cost, having $c$ becomes pretty useless anyway, so the whole expedition turns out to be pointless.
(But of course we couldn't have known that before we went and checked. The idea was good enough; it just didn't work. Perhaps your next one will.)

A: Your idea is not wrong. From what I assume (and Henning seems to think this, too), your introduction to imaginary and complex numbers has been something like this:
The equation $x^2 + 1 = 0$ has no solution in the Real numbers. So, lets add a new number $i$ that is a solution to this equation and thus "extend" the set of Real numbers to the Complex numbers where every one of them will have this form (proof omitted): $a + bi$ and (again proof omitted) this new set $C$ does not drive us into deriving nonsense statements and has all the properties needed to call it a field.
This new set of Complex numbers does not have all features that the Reals have (as Henning points) like the concept of negatives and positives but it does have a lot of new features that the Reals do not have - like the fact that any polynomial equation with degree $n$ has exactly $n$ solutions, and not just for n=2 but for any positive n - and many others that you will find in any book about Complex Analysis.
So, your idea again, is quite smart and is essentially what many people have used previously in what are called algebraic (field) extensions. Off course, it doesn't work as you expected and depending on how one interprets your equation either (as Robert explained) "your equation already has solutions in the Complex numbers" or (as Henning explained) "it leads to nonsense statements".
Perhaps you can find some other equation that has no solution and thus extend them. Or you can start with something simpler like the Rationals (the field $Q$) and extend it with a solution to the equation $x^2 - 2 = 0$. This is called if I am not wrong $Q(\sqrt{2})$ and you could try to find (and prove) the properties of this set. Is it a field (etc)?
Or the Rationals extended by a solution to $x^2 + 2 = 0$, which would be called $Q(\sqrt{-2})$.

A: $$\log(-100)=\log(100i^2)$$
$$\log(-100)=2+2\log(i)$$


text:
Q: Mapping Cartesian function onto polar plane and finding the Length of that mapped function? The problem involves: mapping a Cartesian function (with domain $0$ - $2\pi$) onto the polar plane.This transformation maps the value of the Cartesian function for every angle around the center point.
E.g $f(x) = 1$ would map the unit circle
$g(x) = x$ would map a spiral
The problem is to find a generalized method of finding the length of the mapped 'curves'
For the general Cartesian function $f(x)$, its length from $a$ to $b$ is $L= \int_a^b \sqrt{1+f'(x)^2}$.
Update: Answer found for 'curved' length $L= \int_0^{2\pi} \sqrt{f(x)^2+f'(x)^2}$.   I am not excactly sure why this works but arrived to this conclusion by trial and error


text:
Q: Creata Jade Agent with another agent please , I need help. How to create a JADE agent in the body of another agent ?
    Profile p = new ProfileImpl();

    p.setParameter(Profile.MAIN_HOST, "localhost");

    p.setParameter(Profile.MAIN_PORT, "1099");

    AgentContainer ac = rt.createMainContainer(p);
    AgentController agent ac.createNewAgent ("agentBD", "agents.AgentBD");

     agent.start();

A: try something like this ("agent" is you current agent from whitch you create other agent):
private static Codec codec = new SLCodec();
private static ContentManager cm = new ContentManager();
static
{
    cm.registerLanguage(codec, FIPANames.ContentLanguage.FIPA_SL0);
    cm.registerOntology(FIPAManagementOntology.getInstance());
    cm.registerOntology(JADEManagementOntology.getInstance());
}

public static AID createNewAgent(Agent agent, String name, String className)
{
    CreateAgent ca = new CreateAgent();
    ca.setAgentName(name);
    ca.setClassName(className);
    ca.setContainer((ContainerID) agent.here());

    ACLMessage request = new ACLMessage(ACLMessage.REQUEST);
    request.addReceiver(agent.getAMS());
    request.setOntology(JADEManagementOntology.getInstance().getName());
    request.setLanguage(FIPANames.ContentLanguage.FIPA_SL0);
    request.setReplyWith("new-agent-" + agent.getName() + System.currentTimeMillis());

    try
    {
        cm.fillContent(request, new Action(agent.getAMS(), ca));
        agent.send(request);

        MessageTemplate mt = MessageTemplate.MatchInReplyTo(request.getReplyWith());
        ACLMessage reply = agent.blockingReceive(mt, 10000);
        if(reply == null)
            throw new RuntimeException("cannot create agent [" + name + "; " + className + "]");

        return new AID(name, AID.ISLOCALNAME);
    }
    catch (Codec.CodecException e)
    {
        throw new RuntimeException(e);
    }
    catch (OntologyException e)
    {
        throw new RuntimeException(e);
    }
}


text:
Q: Create a new array with SecurityGroupIds instead of SecurityGroupNames with Ansible I am relatively new to Ansible and I am struggling to understand how to perform the following scenario:
I have an array with AWS security group names looking like this
['Security-Group-Name1', 'SecurityGroup-Name2', 'SecurityGroup-Name3']

However, what I want is to have an array of SecurityGroupIds. Using Ansible I have the ec2_group_info as an option to retrieve information about a security group. So far so good ...
Now comes my question. I need to loop through the above array using ec2_group_info, set the name of the security group I need and return the retrieved Id into a new array so in the end I have something like this.
['Security-Group-Id1', 'SecurityGroup-Id2', 'SecurityGroup-Id3']

I know I need to use a loop with sort of a dynamic index. But it is not really clear to me how to do this in Ansible.
I am aware of the latest loop section of Ansible Docs and I find them more than confusing...
https://docs.ansible.com/ansible/latest/user_guide/playbooks_loops.html
Edit:
This is the current code which works as needed:
- name: Installing pip if not existing on host
  pip:
    name: boto3

- name: Get SecurityGroupId information
  ec2_group_info:
    filters:
      group_name: ['SG-One', 'SG-Two']
      vpc_id: 'vpc-id'
  register: my_groups

- set_fact:
    my_group_ids: '{{ my_groups.security_groups | map(attribute="group_id") | list }}'

- debug:
    msg: "{{ my_groups }}"

- debug:
    msg: "{{ my_group_ids }}"

This is the outcome:
TASK [Gathering Facts] ***************************************************
ok: [localhost]

TASK [machine-provisioning : Installing pip if not existing on host] ************
ok: [localhost]

TASK [machine-provisioning : Get SecurityGroupId information] *************************
ok: [localhost]

TASK [machine-provisioning : set_fact] *********************************
ok: [localhost]

TASK [machine-provisioning : debug] ***********************************************
ok: [localhost] => {
"msg": [
    "sg-00000000",
    "sg-11111111"
]

}

A: On that linked page about loops, you'll observe the use of register:, which is how you'd capture the result of that ec2_group_info: lookup, then use the map jinja filter to extract map(attribute="group_id") from the resulting list of results; you have to feed the output of map into the list filter, because map and a few others are python generators, and thus need a terminal action to materialize their data. The set_fact: is how ansible does "assignment"
- ec2_group_info:
    filters:
      group_name: '{{ the_group_names }}'
      vpc_id: '{{ my_vpc_id }}'
  register: my_groups
- set_fact:
    my_group_ids: '{{ my_groups.security_groups | map(attribute="group_id") | list }}'

yields:
ok: [localhost] => {"ansible_facts": {"my_group_ids": ["sg-0c5c277ed1edafb54", "sg-7597a123"]}, "changed": false}