text:
Q: %s - что за элемент синтаксиса? Изучаю Django по djbook.ru.
Вот фрагмент кода, в котором фигурирует этот %s. Что-то не пойму.
Это вводная часть, но я полагаю, разъяснён должен быть каждый элемент.
def results(request, question_id):
    response = "You're looking at the results of question %s."
    return HttpResponse (response % question_id)

def vote(request, question_id):
    response = "You're vouting at question %s."
    return HttpResponse (response % question_id)

A: Постановочный оператор, используется не только в Питоне.
%s заменяется на указанную подстроку
В вашем случае по видимому заменяется на question_id.
см. https://pythonworld.ru/osnovy/formatirovanie-strok-operator.html

A: Подставление значения в место с указанием типа. В данном случае: s - string

A: Это "старый", унаследованный от языка Си, синтаксис форматирования строки. Вместо %s подставится значение переменной question_id.
Через метод .format строки будет выглядеть так:
def results(request, question_id):
    response = "You're looking at the results of question {}."
    # Вместо фигурных скобок в строке response подставится значение question_id:
    return HttpResponse (response.format(question_id))

Или через новый синтаксис (f-строки) (начиная с Python 3.6):
def results(request, question_id):
    # Вместо имени переменной в фигурных скобках подставится значение переменной:
    return HttpResponse (f"You're looking at the results of question {question_id}.")


text:
Q: Access to SSL context in faye-websocket+eventmachine connection I would like to get a wire dump of a secure websocket connection where I am the client.
I am using the faye-websocket gem in ruby to connect to a secure websocket service. This works well. To understand a specific issue, I need to get a wire dump of the communication. I typically use wireshark for this (running on the same machine as the client). To decrypt the SSL connection, I need to extract the master key to pass it to wireshark. I know how to extract the master key if I have direct access to the socket, but I fail to get access to it when using the faye-websocket gem.
The code to run faye-websocket is pretty standard:
EM.run {
     ws = Faye::WebSocket::Client.new('wss://...')

ws.on :open do |event|
    p [:open]
    ### authentication
end

ws.on :message do |event|
    p [:message, event.data]
    ### message - response loop here
end

ws.on :close do |event|
    p [:close, event.code, event.reason]
    ws = nil
end
}

Inspecting the content of ws, it has a @socket member, but I fail to receive it (get_instance_var returns nil).
For the record, once I have the SSLcontext, I would use the code from
https://www.trustwave.com/en-us/resources/blogs/spiderlabs-blog/how-to-decrypt-ruby-ssl-communications-with-wireshark/
to extract the master key and pass it to wireshark:
ssl_socket.session.to_text.each_line do |line|
  if match = line.match(/Session-ID\s*: (?<session_id>.*)/)
    session_id = match[:session_id]
  end
  if match = line.match(/Master-Key\s*: (?<master_key>.*)/)
    master_key = match[:master_key]
  end
end

Does someone have a solution to get access to the underlying socket and the SSL context?

redpajama_set_name: RedPajamaStackExchange


text:
Q: Find pattern in pandas column names and change such columns using pipe Let say I have below calculation,
import pandas as pd
dat = pd.DataFrame({'xx1' : [1,2,3], 'aa2' : ['qq', '4', 'd'], 'xx3' : [4,5,6]})
dat2 = (dat
        .assign(xx1 = lambda x : [str(i) for i in x['xx1'].values])
        .assign(xx3 = lambda x : [str(i) for i in x['xx3'].values])
    )

Basically, I need to find those columns for which column names match pattern xx + sequence of numbers (i.e. xx1, xx2, xx3 etc) and then apply some transformation to those column (e.g. apply str function)
One way I can do this is like above i.e. find manually those columns and perform transformation. I wonder if there is any way to generalise this approach. I prefer to use pipe like above.
Any pointer will be very helpful.

A: You could do:
# Matches all columns starting with 'xx' with a sequence of numbers afterwards.
cols_to_transform = dat.columns[dat.columns.str.match('^xx[0-9]+$')]

# Transform to apply (column-wise).
transform_function = lambda c: c.astype(str)

# If you want a new DataFrame and not modify the other in-place.
dat2 = dat.copy()

dat2[cols_to_transform] = dat2[cols_to_transform].transform(transform_function, axis=0)

To use it within assign:
# Here I put a lambda to avoid precomputing all the transformations in the dict comprehension.
dat.assign(**{col: lambda df: df[col].astype(str) for col in cols_to_transform})

A: import pandas as pd
frame = pd.DataFrame({'xx1' : [1,2,3], 'aa2' : ['qq', '4', 'd'], 'xx3' : [4,5,6]})

def parse_column(col, vals):
    if "xx" == col[:2] and col[2:].isdigit():
        return [str(i) for i in vals]
    return vals

for (name, col) in frame.iteritems():
    frame[name] = parse_column(name, col.values)

*

*you can iterate over columns, getting their names and values as a series

*the incredibly niche str.isdigits() function exists as an inherent part of python for some reason, but it came in useful here

A: One option is to select the relevant columns, apply your function and assign them back to the dataframe via unpacking:
result = dat.assign(**dat.filter(regex=r"xx\d+").astype(str))

result.dtypes

xx1    object
aa2    object
xx3    object
dtype: object

dat.dtypes

xx1     int64
aa2    object
xx3     int64
dtype: object


text:
Q: Drop-Down isn't populated with the 'name' field when table name contains "companies" I have this very strange issue I cannot explain:
The table drivers has the belongsTo association to the table transport_companies connected by the field drivers.transport_company_id. Usually in the edit|add mode for the table drivers CakePHP generates a nice drop-down with the content of the name field.
The issue:
The drop-drown shows only the ids instead of the content of the name field as long the table has the word companies in it. When I rename the table to transport_firms | transports | transport_units or something else then the drop-down field is populated correctly. I do NOT change anything, I only bake all models each time I rename the table.
My question:
Is there any CakePHP restriction regarding the word companies in a tablename because the drop-down isn't populated correctly?

A: Greg Schmidt's comment was the important hint. The CakePHP caches got messed up and - according to my another comment - another references began to fail as well.
I avoid this issue running these commands each time I make a change in the database:
bin/cake cache clear_all && bin/cake bake model all

As I don't add any code to the model/table and entity files I can always overwrite all of them. This simplifies the maintenance substantially.


text:
Q: script for mysql + apache + php installation I can install MySQL or any package from the code below but I wish to install multiple packages, one by one, from a single script.

echo "Do you wish to install MySql?"
select yn in "Yes" "No"; do
case $yn in
Yes ) yum -y install mysql; break;;
No ) exit;;
esac
done

1). If type No then it will go on to next level e.g.Do you wish to install Apache.
2). If type Yes it will install MySQL then ask for next packages e.g.Do you wish to install Apache.
Could someone help me writing this script?
I will explain to you. I want to create script for MySQL + Apache + PHP installation.
If MySQL is already installed in my machine, I don't want to install it, then it will ask for me Do you wish to install Apache? if I press 1 it install then it will ask for me Do you wish to install PHP then exit automatically.

A: Correct syntax for your script snippet for Bourne shell would be:
echo "Do you wish to install MySql?"
read yn
case "$yn" in
    Yes)
        yum install mysql
        ;;
    No) ;;
esac


text:
Q: Searching multidimensional array PHP I have this array (shortened for readability)
   array(10) {
    [0] => array(23) {
        ["account_id"] => int(4294967295)["player_slot"] => int(0)["hero_id"] => int(41)["item_0"] => int(0)["item_1"] => int(0)["item_2"] => int(0)["item_3"] => int(0)["item_4"] => int(0)["item_5"] => int(0)["kills"] => int(0)["deaths"] => int(0)["assists"] => int(0)["leaver_status"] => int(1)["gold"] => int(826)["last_hits"] => int(0)["denies"] => int(0)["gold_per_min"] => int(1799)["xp_per_min"] => int(0)["gold_spent"] => int(0)["hero_damage"] => int(0)["tower_damage"] => int(0)["hero_healing"] => int(0)["level"] => int(1)
    }[1] => array(23) {
         ["account_id"] => int(101863674)["player_slot"] => int(1)["hero_id"] => int(0)["item_0"] => int(0)["item_1"] => int(0)["item_2"] => int(0)["item_3"] => int(0)["item_4"] => int(0)["item_5"] => int(0)["kills"] => int(0)["deaths"] => int(0)["assists"] => int(0)["leaver_status"] => int(1)["gold"] => int(0)["last_hits"] => int(0)["denies"] => int(0)["gold_per_min"] => int(1799)["xp_per_min"] => int(0)["gold_spent"] => int(0)["hero_damage"] => int(0)["tower_damage"] => int(0)["hero_healing"] => int(0)["level"] => int(0)
    }[2] => array(23) {
        ["account_id"] => int(112698809)["player_slot"] => int(2)["hero_id"] => int(0)["item_0"] => int(0)["item_1"] => int(0)["item_2"] => int(0)["item_3"] => int(0)["item_4"] => int(0)["item_5"] => int(0)["kills"] => int(0)["deaths"] => int(0)["assists"] => int(0)["leaver_status"] => int(1)["gold"] => int(0)["last_hits"] => int(0)["denies"] => int(0)["gold_per_min"] => int(1799)["xp_per_min"] => int(0)["gold_spent"] => int(0)["hero_damage"] => int(0)["tower_damage"] => int(0)["hero_healing"] => int(0)["level"] => int(0)
    }[3] => array(23) {
        ["account_id"] => int(4294967295)["player_slot"] => int(3)["hero_id"] => int(0)["item_0"] => int(0)["item_1"] => int(0)["item_2"] => int(0)["item_3"] => int(0)["item_4"] => int(0)["item_5"] => int(0)["kills"] => int(0)["deaths"] => int(0)["assists"] => int(0)["leaver_status"] => int(1)["gold"] => int(0)["last_hits"] => int(0)["denies"] => int(0)["gold_per_min"] => int(1799)["xp_per_min"] => int(0)["gold_spent"] => int(0)["hero_damage"] => int(0)["tower_damage"] => int(0)["hero_healing"] => int(0)["level"] => int(0)
    }[4] => array(23) {
        ["account_id"] => int(126161349)["player_slot"] => int(4)["hero_id"] => int(0)["item_0"] => int(0)["item_1"] => int(0)["item_2"] => int(0)["item_3"] => int(0)["item_4"] => int(0)["item_5"] => int(0)["kills"] => int(0)["deaths"] => int(0)["assists"] => int(0)["leaver_status"] => int(1)["gold"] => int(0)["last_hits"] => int(0)["denies"] => int(0)["gold_per_min"] => int(1799)["xp_per_min"] => int(0)["gold_spent"] => int(0)["hero_damage"] => int(0)["tower_damage"] => int(0)["hero_healing"] => int(0)["level"] => int(0)
    }[5] => array(23) {
        ["account_id"] => int(4294967295)["player_slot"] => int(128)["hero_id"] => int(0)["item_0"] => int(0)["item_1"] => int(0)["item_2"] => int(0)["item_3"] => int(0)["item_4"] => int(0)["item_5"] => int(0)["kills"] => int(0)["deaths"] => int(0)["assists"] => int(0)["leaver_status"] => int(1)["gold"] => int(0)["last_hits"] => int(0)["denies"] => int(0)["gold_per_min"] => int(2500)["xp_per_min"] => int(0)["gold_spent"] => int(0)["hero_damage"] => int(0)["tower_damage"] => int(0)["hero_healing"] => int(0)["level"] => int(0)
    }[6] => array(23) {
        ["account_id"] => int(4294967295)["player_slot"] => int(129)["hero_id"] => int(0)["item_0"] => int(0)["item_1"] => int(0)["item_2"] => int(0)["item_3"] => int(0)["item_4"] => int(0)["item_5"] => int(0)["kills"] => int(0)["deaths"] => int(0)["assists"] => int(0)["leaver_status"] => int(3)["gold"] => int(0)["last_hits"] => int(0)["denies"] => int(0)["gold_per_min"] => int(1799)["xp_per_min"] => int(0)["gold_spent"] => int(0)["hero_damage"] => int(0)["tower_damage"] => int(0)["hero_healing"] => int(0)["level"] => int(0)
    }[7] => array(23) {
        ["account_id"] => int(4294967295)["player_slot"] => int(130)["hero_id"] => int(0)["item_0"] => int(0)["item_1"] => int(0)["item_2"] => int(0)["item_3"] => int(0)["item_4"] => int(0)["item_5"] => int(0)["kills"] => int(0)["deaths"] => int(0)["assists"] => int(0)["leaver_status"] => int(1)["gold"] => int(0)["last_hits"] => int(0)["denies"] => int(0)["gold_per_min"] => int(2500)["xp_per_min"] => int(0)["gold_spent"] => int(0)["hero_damage"] => int(0)["tower_damage"] => int(0)["hero_healing"] => int(0)["level"] => int(0)
    }[8] => array(23) {
        ["account_id"] => int(4294967295)["player_slot"] => int(131)["hero_id"] => int(0)["item_0"] => int(0)["item_1"] => int(0)["item_2"] => int(0)["item_3"] => int(0)["item_4"] => int(0)["item_5"] => int(0)["kills"] => int(0)["deaths"] => int(0)["assists"] => int(0)["leaver_status"] => int(1)["gold"] => int(0)["last_hits"] => int(0)["denies"] => int(0)["gold_per_min"] => int(2500)["xp_per_min"] => int(0)["gold_spent"] => int(0)["hero_damage"] => int(0)["tower_damage"] => int(0)["hero_healing"] => int(0)["level"] => int(0)
    }[9] => array(23) {
        ["account_id"] => int(113794304)["player_slot"] => int(132)["hero_id"] => int(0)["item_0"] => int(0)["item_1"] => int(0)["item_2"] => int(0)["item_3"] => int(0)["item_4"] => int(0)["item_5"] => int(0)["kills"] => int(0)["deaths"] => int(0)["assists"] => int(0)["leaver_status"] => int(1)["gold"] => int(0)["last_hits"] => int(0)["denies"] => int(0)["gold_per_min"] => int(2500)["xp_per_min"] => int(0)["gold_spent"] => int(0)["hero_damage"] => int(0)["tower_damage"] => int(0)["hero_healing"] => int(0)["level"] => int(0)
    }
}

What i'm trying to achieve is earthing for the array with a specific account_id in order to get the values for kills, deaths and assists for that player. This is what I tried:
function searchForPlayer($id, $array) {
    foreach ($array as $key => $val) {
        if ($val['account_id'] === $id) {
            return $key;
        }
    }
    return null;
}

$player = searchForPlayer($accountid, $players);

However it returns null every time. I'm new to php so would not be surprised if I'm doing something totally wrong. Thanks!

A: function searchForPlayer($id, $array) {
    foreach ($array as $key => $val) {
        if ($val['account_id'] == $id) {
           return $key;
        }
    }
    return null;
}

EDIT: Based in you edit your array structure, you can call the method for each element in the main array.
function mainSearchForPlayer($id, $mainArray) {
    foreach($array as $k => $val) {
      $result = searchForPlayer($id, $val);
      if($result) break;
    }
    return $result;
}

And then call:
$player = mainSearchForPlayer($accountid, $array);

=== in php compare by type too this mean if you pass '1' and your id in array is 1 , never  be equals
otherwise you can check the types by this way:
var_dump($accountid);

and if this is a string value , you can parse to int:
$accountid = intval($accountid)

A: Try this recursive function:
function array_searchRecursive($needle, $haystack, $path=array()) {
    foreach( $haystack as $key => $val ) {
        if( is_array($val) &&  $sub = array_searchRecursive($needle, $val, $path)) {
            $path = array_merge($path, array($key), $sub);
            return $path;
        } elseif($val == $needle) {
            $path[] = $key;
            return $path;
        }
    }
    return false;
}


text:
Q: Other Near Inverses in Mathematics As a young mathematician, one learns that the derivative and integral are kind of like inverse operations, but not quite. The two fundamental theorems of calculus require some additional assumptions to go through. Moreover, the maps $f \mapsto f'$ and $f \mapsto F$ (where $F(x) = \int_a^x f(t) dt$ for some fixed $a$) both fail to be injective and surjective on many function spaces. Yet, it remains a useful intuition to think of integration and differentiation as opposite, if not inverse, operations.
Are there other examples of this near inverse behavior in mathematics? Is there a more general phenomenon like this that integration and differentiation are just examples of?


text:
Q: C# : Using statement and this keyword While wanting to use using statement, I came across a scenario that I don't understand :
private void RoomMealHistory_Click(object sender, EventArgs e)
    {
        MealRoomPlanning fMealRoomPlanning = new MealRoomPlanning(true);
        fMealRoomPlanning .MdiParent = this;
        fMealRoomPlanning.Show();
    }

This code works correctly and my window is a MdiChild.
However, the following code does not work :
private void RoomMealHistory_Click(object sender, EventArgs e)
    {
        using (MealRoomPlanning fMealRoomPlanning = new MealRoomPlanning(true))
        {
            MdiParent = this;
            fMealRoomPlanning.Show();
        }
    }

ArgumentException: 'A form cannot be an MDI child and an MDI parent at the same time.
I also tried to replace this with this.ParentForm doesn't work anymore.
Is there a problem with the scope of this?

A: In your first snippet, you set the MdiParent-Property of fMealRoomPlanning.
In your second snippet, you set MdiParent of your own class instance (this.MdiParent).
You should set it on the object you are using:
private void RoomMealHistory_Click(object sender, EventArgs e)
    {
        using (MealRoomPlanning fMealRoomPlanning = new MealRoomPlanning(true))
        {
            fMealRoomPlanning.MdiParent = this;
            fMealRoomPlanning.Show();
        }
    }

That's why many style-checks recommend using the this-Qualifier although it is redundant. This makes it more clear if you set a local, global or class variable.

A: Finally I have just understood that Using is not necessary for non-modal Form.

When a non modal form is closed, the Dispose will automatically be called by WinForms.

Unlike Forms opened with ShowDialog for which the Dispose is not called automatically.

A: Try Changing the 2nd Code, After creating object for MealRoomPlanning class
change MdiParent = this;    to  fMealRoomPlanning.MdiParent = this;
private void RoomMealHistory_Click(object sender, EventArgs e)
{
    using (MealRoomPlanning fMealRoomPlanning = new MealRoomPlanning(true))
    {
        fMealRoomPlanning.MdiParent = this;
        fMealRoomPlanning.Show();
    }
}

A: Try changing MdiParent = this to fMealRoomPlanning.MdiParent = this


text:
Q: gperftools/tcmalloc 2.8 - running out of memory We are migrating from gperftools/tcmalloc 2.0 to 2.8. But some of our test cases fail with "out of memory" error. We use Cent OS 6.5.
This happens with a posix_memalign() call requesting for 32536008 bytes with 64bit alignment.
I didn't use any specific options with configure while installing gperftools.
Has anyone faced something similar with tcmalloc 2.8 ?
Thanks,
Pramod

A: This is caused by bug. Bug is fixed in recently released 2.8.1 version. Please upgrade.


text:
Q: I need help with this translation problem (pre-calc) I am having trouble understanding what I have to do with translation problems. I don't see anything in my textbook about it, and I can't find any resources online about it. Any help would be appreciated. Thanks.
Here is the problem:
The graph of $g(x)$ contains the point $(−5,6)$. Write a formula for a translation of $g$ whose graph contains the point:
$(a) \ \  (-4, 6)$ then $y = $ ?
$(b) \ \ (-5, 8)$ then $y = $ ?

A: Just to put what nsanger said into an answer, a translation of a function $g(x)$ will have the form $g(x) + c$ which is a vertical shift or the form $g(x + c)$ which is a horizontal shift.
So we see that the graph of $g(x)$ has the point $(-5, 6)$ and for $(a)$ we want the graph of $g(x)$ to have $(-4, 6)$.  So we are moving the $x$-coordinate $1$ unit to the right and so we are looking at a horizontal shift.  One tricky thing about horizontal shifts is that they are sometimes "reversed of what you might expect.  We can see that the difference between $-4$ and $-5$ is $+1$ so we might think that the shift is $g(x+1)$ but this actually shifts everything left, we want a shift right, which would be $g(x-1)$.  (One way to remember this, is to think that you are solving inside the parenthesis for $0$ so the first one gives $x+1=0 \Rightarrow x = -1$ so we are shifting left by $1$, while the second gives $x-1=0 \Rightarrow x =+1$ which is a shift right by $1$ which is what we wanted. In general, $g(x + c)$ moves the graph left $c$ units while $g(x - c)$ moves the graph right $c$ units (for positve $c$).
Now, for $(b)$ we see that the $x$-coordinate has not changed, but the $y$-coordinate has moved up by $2$.  So this is a vertical shift up $2$ units.  Vertical shifts act as we would expect, i.e. $g(x) + c$ moves the graph up $c$ units, but $g(x) - c$ moves the graph down $c$ units (for positive $c$).  So we can see that the translation we want is $g(x) + 2$.


text:
Q: How to write to Firebase table only if its greater than current value in table I need to update the table level value in Firebase score table only if the table value is less than the value currently being posted to update. So the KeyOfLevel value never decreases.
Since the client side involved too much calls to fetch and check. I need to do this in rules tab of Firebase. And I don't exactly know how to write those rules.
Eg:
score:
{
    "1234567890":
    {
        CoinsKey: 1000,
        KeyOfLevel: 5
    }
}

where 123456789 is the user ID.

A: You might want to write security rules like this.
{
   "rules": {
      "score": {
        "$userId": {
           "KeyOfLevel": {
              ".validate": "!data.exists() || data.val() < newData.val()"
           }
         }
      }
   }
}

In place of .validate you can also use .write


text:
Q: Extract specific values from a excel/csv table to form another table in Python I have an excel sheet with the below table.
Sort,Realm,Subrealm,Kingdom,Subkingdom,Phylum,Subphylum,Class,Subclass,Order,Suborder,Family
1,,,Virus,,Negarnaviricota,Haploviricotina,Chunqiuviricetes,,Muvirales,,Qinviridae
2,,,Virus,,Negarnaviricota,Haploviricotina,Milneviricetes,,Serpentovirales,,Aspiviridae
3,,,Virus,,Negarnaviricota,Haploviricotina,Monjiviricetes,,Jingchuvirales,,Chuviridae
4,,,Virus,,Negarnaviricota,Polyploviricotina,Ellioviricetes,,Bunyavirales,,Phasmaviridae
5,,,Virus,,,,,,Caudovirales,,Ackermannviridae
6,,,Virus,,,,,,Caudovirales,,Myoviridae
7,,,Virus,,,,,,Caudovirales,,Siphoviridae

I would like to extract data in the expected result format.
Sort,Name,Rank,Parent
1,Negarnaviricota,Phylum,Virus
1,Haploviricotina,Subphylum,Negarnaviricota
4,Polyploviricotina,Subphylum,Negarnaviricota
1,Chunqiuviricetes,Class,Haploviricotina
2,Milneviricetes,Class,Haploviricotina
3,Monjiviricetes,Class,Haploviricotina
4,Ellioviricetes,Class,Polyploviricotina
1,Muvirales,Order,Chunqiuviricetes
2,Serpentovirales,Order,Milneviricetes
3,Jingchuvirales,Order,Monjiviricetes
4,Bunyavirales,Order,Ellioviricetes
5,Caudovirales,Order,Virus
1,Qinviridae,Family,Muvirales
2,Aspiviridae,Family,Serpentovirales
3,Chuviridae,Family,Jingchuvirales
4,Phasmaviridae,Family,Bunyavirales
5,Ackermannviridae,Family,Caudovirales
6,Myoviridae,Family,Caudovirales
7,Siphoviridae,Family,Caudovirales

Description of Extracted Columns:

*

*Sort - Number associated with the unique name being extracted

*Name - Unique names from each column that has a name

*Rank - Header of the column where the name is extracted from

*Parent - Last non-blank value in the preceding cells

first_row = ['Realm', 'Subrealm', 'Kingdom', 'Subkingdom', 'Phylum', 'Subphylum', 'Class', 'Subclass', 'Order', 'Suborder', 'Family', 'Subfamily', 'Genus', 'Subgenus', 'Species']

df1 = pd.read_csv('ictv-msl-2018-v1.csv', index_col='Sort')
print('Writing to CSV File')
with open('dp1.csv', 'w', newline="") as tbl_writer1:
    c2 = csv.writer(tbl_writer1)
    c2.writerow(['Name', 'Rank'])
    for list_item in first_row:
        for item in df1[list_item].unique():
            row_content = [item, list_item]
            c2.writerow(row_content)

with open('ictv-msl-2018-v1.csv', 'r',) as inp1, open('dp1.csv', 'r') as inp2, open('dp2.csv', 'w', newline="") as out1:
    msl_tbl = csv.DictReader(inp1)
    tbl_data = list(msl_tbl)
    c3 = csv.writer(out1)
    for row in csv.reader(inp2):
        if row[0] != 'nan':
            c3.writerow(row)
        else:
            print('Deleted Row:', row)

df2 = pd.read_csv('dp2.csv')
print(tbl_data[0]['Species'])
print(len(df2), len(df2.columns))
for i in range(len(df2)):
    for j in range(len(df2.columns)):
        print(df2.get_values()[i][j], i, j)

Can someone please advise how I can extract all four of the below columns? The above code only extracts Name,Rank
Sort,Name,Rank,Parent

A: Using your original input data as input.csv:
import csv

with open('input.csv',newline='') as fin:
        r = csv.reader(fin)
        header = next(r)
        names = {}
        for row in r:
            parent = None
            for idx,content in enumerate(row):
                if idx == 0:                   # First column is sort.
                    sort = content
                    continue
                if not content:                # Skip blanks.
                    continue
                if parent is None:             # Record the first non-blank content as parent.
                    parent = content
                    continue

                # Remaining content is names.
                # Record name the first time it is seen,
                # then update parent.
                data = sort,content,header[idx],parent
                if content not in names:
                    names[content] = data
                parent = content

def sortkey(data):
    sort,name,rank,parent = data
    return header.index(rank),int(sort)

with open('output.csv','w',newline='') as fout:
    w = csv.writer(fout)
    w.writerow('Sort Name Rank Parent'.split())
    for data in sorted(names.values(),key=sortkey):
        w.writerow(data)

Output:
Sort,Name,Rank,Parent
1,Negarnaviricota,Phylum,Virus
1,Haploviricotina,Subphylum,Negarnaviricota
4,Polyploviricotina,Subphylum,Negarnaviricota
1,Chunqiuviricetes,Class,Haploviricotina
2,Milneviricetes,Class,Haploviricotina
3,Monjiviricetes,Class,Haploviricotina
4,Ellioviricetes,Class,Polyploviricotina
1,Muvirales,Order,Chunqiuviricetes
2,Serpentovirales,Order,Milneviricetes
3,Jingchuvirales,Order,Monjiviricetes
4,Bunyavirales,Order,Ellioviricetes
5,Caudovirales,Order,Virus
1,Qinviridae,Family,Muvirales
2,Aspiviridae,Family,Serpentovirales
3,Chuviridae,Family,Jingchuvirales
4,Phasmaviridae,Family,Bunyavirales
5,Ackermannviridae,Family,Caudovirales
6,Myoviridae,Family,Caudovirales
7,Siphoviridae,Family,Caudovirales


text:
Q: DATAADAPTERS AND NULLS I am trying to pass a null to DataAdapter.Fill. My SQL statement accepts nulls but I get a return that nulls are not acceptable.
JUEGO.etreDataSetTableAdapters.CountyTableAdapter etreDataSetCountyTableAdapter = new          JUEGO.etreDataSetTableAdapters.CountyTableAdapter();
        etreDataSetCountyTableAdapter.Fill(etreDataSet.County, null);
        CollectionViewSource CViewSource = ((CollectionViewSource)(this.FindResource("CViewSource")));
        CViewSource.View.MoveCurrentToFirst();

the CountryTableAdapter has the SQL Statement below behind it.
SELECT DISTINCT CCODE FROM  HH_Match WHERE  (@DCODE IS NULL OR DCODE = @DCODE)

but when I pass Null like above it returns a massage that nulls are not allowed. I am working in Visual Studio (C#) 2012. Thanks in advance for the help

A: You have to configure the TableAdapter manually so that it accepts null.
Therefore click on Parameters in the query property. Select the parameter you want to make optionally (in this case you have only one parameter). On the right side you'll find AllowDbNull. Set this to True and you've arrived.


text:
Q: Read with PubsubIO with custom coder I can read PubSub messages from a topic using PubsubIO as follows:
pipeline.apply("read", PubsubIO.readMessages().fromTopic(options.getPubsubReadTopic()))
.apply( /* rest of the pipeline that works on PubSubMessage records */ )

The data inside the PubSub messages is wrapped in our custom wrappers, and is not easy to work with. I would like to create class CustomPubsubIO and use it in a similar manner:
pipeline.apply("read", CustomPubsubIO.readTyped<MyType>().fromTopic(options.getPubsubReadTopic()))
.apply( /* rest of the pipeline that works on MyType records */ )

I was able to create a custom CustomCoder<MyType>, but I am having trouble creating PubsubIO.Read<MyType> with it. PubsubIO.Read is abstract in PubsubIO, and is used with @AutoValue, seems like I cannot extend it directly
What is the right way of creating a Read<> with custom coder?

A: Do you have any specific reason to create your custom type of PubsubIO.Read? Otherwise, you can just use PubsubIO.readMessages() and combine a DoFn to transform output PubsubMessage to whatever you want. The API supporting a custom coder and a custom parse function was removed two years ago since using a DoFn seems to be a clearer and semantically equivalent way of generating custom types.

A: OK, I was able to do it kinda. I had to put my CustomPubsubIO class in package org.apache.beam.sdk.io.gcp.pubsub because AutoValue_PubsubIO_Read is package-protected. So I am not sure this solution will work in future (looks more like a hack)
Anyway, here is the simplified code:
package org.apache.beam.sdk.io.gcp.pubsub;

import org.apache.beam.sdk.io.gcp.pubsub.PubsubIO.Read;
import org.apache.beam.sdk.transforms.SimpleFunction;

public class ExtraPubsubIO {

  public static <T> Read<T> read() {
    return new AutoValue_PubsubIO_Read.Builder<T>()
        .setPubsubClientFactory(PubsubJsonClient.FACTORY)
        .setCoder(new CustomTypeInPubSubCoder<>())
        .setParseFn(new CustomTypeUnwrapFn<>())
        .setNeedsAttributes(false)
        .build();
  }

  private static class CustomTypeUnwrapFn<T> extends SimpleFunction<PubsubMessage, T> {

    @Override
    public T apply(PubsubMessage input) {
      return CustomTypeUnwrapper.unwrap(input);
    }
  }
}

And then use it in the pipeline like this:
pipeline.apply("Read PubSub messages", ExtraPubsubIO.<String>read().fromTopic(options.getPubsubReadTopic()))
        .apply("Write File(s)", TextIO.write()...
        .run()


text:
Q: Ubuntu 18.04 uses different amount of memory on different machines I have a 4GB machine, and when launching Ubuntu 18.04 (gnome) on this machine, it uses 1.4GB of ram just after booting.
I tried the same ISO on another machine with 8GB, and it uses 3.6GB of ram just after booting.
Why Ubuntu is having such behavior? Does Ubuntu do that to improve performance?
Thanks in advance.

A: You could get a hint of what is happening with memory in those systems with
top -o %MEM

With that command you will get all processes sorted by memory usage. Maybe the additionnal memory is used for buffering ?


text:
Q: How to convert json array to variables in php from android post method I have developed an android app. It sending json array of string to php. I didn't get the data in php server. And i want to insert the data into mysql. The android app using json post method. below shows the code.
MainActivity .java
 import android.app.Activity;
 import android.net.ConnectivityManager;
 import android.net.NetworkInfo;
 import android.os.AsyncTask;
 import android.support.v7.app.AppCompatActivity;
 import android.os.Bundle;
 import android.util.Log;
 import android.view.View;
 import android.widget.Button;
 import android.widget.EditText;
 import android.widget.TextView;
 import android.widget.Toast;

 import org.apache.http.HttpResponse;
 import org.apache.http.client.HttpClient;
 import org.apache.http.client.methods.HttpPost;
 import org.apache.http.entity.StringEntity;
 import org.apache.http.impl.client.DefaultHttpClient;
 import org.json.JSONObject;

 import java.io.BufferedReader;
 import java.io.IOException;
 import java.io.InputStream;
 import java.io.InputStreamReader;
 import java.net.HttpURLConnection;
 import java.net.URL;

 import com.acs.filesharing.Person;

 public class MainActivity extends AppCompatActivity implements View.OnClickListener{

TextView tvIsConnected;
EditText etName,etCountry,etTwitter;
Button btnPost;
Person person;

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

    tvIsConnected = (TextView) findViewById(R.id.tvIsConnected);
    etName = (EditText) findViewById(R.id.etName);
    etCountry = (EditText) findViewById(R.id.etCountry);
    etTwitter = (EditText) findViewById(R.id.etTwitter);
    btnPost = (Button) findViewById(R.id.btnPost);

    // check if you are connected or not
    if(isConnected()){
        tvIsConnected.setBackgroundColor(0xFF00CC00);
        tvIsConnected.setText("You are conncted");
    }
    else{
        tvIsConnected.setText("You are NOT conncted");
    }

    // add click listener to Button "POST"
              btnPost.setOnClickListener(this);

}

public static String POST(String url, Person person){
    InputStream inputStream = null;
    String result = "";
    try {

        // 1. create HttpClient
        HttpClient httpclient = new DefaultHttpClient();

        // 2. make POST request to the given URL
        HttpPost httpPost = new HttpPost(url);

        String json = "";

        // 3. build jsonObject
        JSONObject jsonObject = new JSONObject();
        jsonObject.accumulate("name", person.getName());
        jsonObject.accumulate("country", person.getCountry());
        jsonObject.accumulate("twitter", person.getTwitter());

        // 4. convert JSONObject to JSON to String
        json = jsonObject.toString();

        // ** Alternative way to convert Person object to JSON string usin Jackson Lib
        // ObjectMapper mapper = new ObjectMapper();
        // json = mapper.writeValueAsString(person);

        // 5. set json to StringEntity
        StringEntity se = new StringEntity(json);

        // 6. set httpPost Entity
        httpPost.setEntity(se);

        // 7. Set some headers to inform server about the type of the content
        httpPost.setHeader("Accept", "application/json");
        httpPost.setHeader("Content-type", "application/json");

        // 8. Execute POST request to the given URL
        HttpResponse httpResponse = httpclient.execute(httpPost);

        // 9. receive response as inputStream
        inputStream = httpResponse.getEntity().getContent();

        // 10. convert inputstream to string
        if(inputStream != null)
            result = convertInputStreamToString(inputStream);
        else
            result = "Did not work!";

    } catch (Exception e) {
        Log.d("InputStream", e.getLocalizedMessage());
    }

    // 11. return result
    return result;
}

private static String convertInputStreamToString(InputStream inputStream) throws IOException {

    BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(inputStream));
    String line = "";
    String result = "";
    while((line = bufferedReader.readLine()) != null)
        result += line;

    inputStream.close();
    return result;

}

private boolean isConnected() {

    ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Activity.CONNECTIVITY_SERVICE);
    NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
    if (networkInfo != null && networkInfo.isConnected())
        return true;
    else
        return false;
}

@Override
public void onClick(View v) {
    switch(v.getId()){
        case R.id.btnPost:
            if(!validate())
                Toast.makeText(getBaseContext(), "Enter some data!", Toast.LENGTH_LONG).show();
            // call AsynTask to perform network operation on separate thread

            new HttpAsyncTask().execute("http://192.168.1.3/work/filesharing/1.php");
            break;
    }

}

private boolean validate() {

    if(etName.getText().toString().trim().equals(""))
        return false;
    else if(etCountry.getText().toString().trim().equals(""))
        return false;
    else if(etTwitter.getText().toString().trim().equals(""))
        return false;
    else
        return true;
}

private class HttpAsyncTask extends AsyncTask<String, Void, String> {

    String etName1= etName.getText().toString();
    String etCountry1=etCountry.getText().toString();
    String etTwitter1=etTwitter.getText().toString();

    @Override
    protected String doInBackground(String... urls) {

        person = new Person();
        person.setName(etName1);
        person.setCountry(etCountry1);
        person.setTwitter(etTwitter1);

        return POST(urls[0],person);

    }
    // onPostExecute displays the results of the AsyncTask.
    @Override
    protected void onPostExecute(String result) {
        Toast.makeText(getBaseContext(), "Data Sent!", Toast.LENGTH_LONG).show();
    }
}
 }

Person.java
 public class Person {

private String name;
private String country;
private String twitter;

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public String getCountry() {
    return country;
}

public void setCountry(String country) {
    this.country = country;
}

public String getTwitter() {
    return twitter;
}

public void setTwitter(String twitter) {
    this.twitter = twitter;
}
 }

1.php
 <?php
 $con=mysqli_connect("localhost","admin","","test");
 if (mysqli_connect_errno($con))
 {
    echo '{"query_result":"ERROR"}';
 }
  $arr = array();
  while($record = mysql_fetch_array($result)){
  $name = $record['name'];
  }
  $arr = array();
  while($record = mysql_fetch_array($result)){
  $name = $record['name'];
  }
   $result = mysqli_query($con,"INSERT INTO user (fullname)
      VALUES ('$name')");

 if($result == true) {
     echo '{"query_result":"SUCCESS"}';
 }
 else{
     echo '{"query_result":"FAILURE"}';
 }
 mysqli_close($con);
  ?>

I want to insert submit data into mysql. Please help me.


text:
Q: Problems getting return value from C library wrapped in FFI in Ruby using Python ctypes as example EDIT: Documentation for the relevant library methods!
Full disclosure - I know next to nothing about C/C++ and literally nothing about pointers and buffers and all that fun stuff. Apologies if this is a stupid question, but I've been working on this for hours and haven't got very far at all.
So I have an external C library that I'm referencing from a Ruby script. There's a bunch of different functions which I need to access, and I've got some simple ones working, but I'm struggling with a more complicated function that I need to work.
The good part - I have working example code in Python.
The challenge I'm facing is around the whole buffer side of things using FFI - I've not found a lot of relevant examples on how to make this work, and I'm struggling a bit.
Here's the function I want to replicate in Ruby using FFI:
def getActiveID32():
    """
    Will return a tuple consisting number of bits
    read and actual data. Minimum 8 byte of data will
    be returned.
    """
    rawData = ""
    buffer_size = ctypes.c_short(32);
    pcproxlib.GetActiveID32.restype = ctypes.c_short
    # create a buffer of given size to pass it
    # to get the raw data.
    raw_data_tmp = (ctypes.c_ubyte * buffer_size.value)()
    #as per documentation 250 millisecond sleep is required
    # to get the raw data.
    time.sleep(250/1000.0)
    nbBits = pcproxlib.GetActiveID32(raw_data_tmp , buffer_size)
    bytes_to_read = int((nbBits + 7) / 8) ;
    # will read at least 8 bytes
    if bytes_to_read < 8:
        bytes_to_read = 8

    for i in range(0 , bytes_to_read):
        temp_buf = "%02X " % raw_data_tmp[i]
        rawData = temp_buf + rawData
    return (nbBits , rawData)

Here's the example code that I have working for the simple functions (eg BeepNow but not for this more complicated function, getActiveID32.
Included is the code I've been playing with, but that is clearly too simplified, and doesn't work.
require 'ffi'

module PCProxLib
  extend FFI::Library
  ffi_lib File.expand_path('lib/32/libhidapi-hidraw.so.0')
  ffi_lib File.expand_path('lib/32/libpcProxAPI.so')
  attach_function :usbConnect, [], :short
  attach_function :getPartNumberString, [], :string
  attach_function :getActiveID32, [:string, :int], :int
  attach_function :getActiveID, [], :int
  attach_function :BeepNow, [:int, :bool], :bool
end

puts PCProxLib.usbConnect()

puts PCProxLib.BeepNow(3, false)

sleep 0.25
buffer = ""
puts PCProxLib.getActiveID32(buffer, 64)
puts buffer

Thanks heaps for any help :)
EDIT:
Based on @matt's comment, I've revised the code to the following:
require 'ffi'

module PCProxLib
  extend FFI::Library
  ffi_lib File.expand_path('lib/32/libhidapi-hidraw.so.0')
  ffi_lib File.expand_path('lib/32/libpcProxAPI.so')
  attach_function :usbConnect, [], :short
  attach_function :USBDisconnect, [], :short
  attach_function :getActiveID32, [:pointer, :int], :int
end

PCProxLib.usbConnect()

puts PCProxLib.getPartNumberString() // verifying connection to reader

def read_card
  sleep 0.5
  buffer = FFI::MemoryPointer.new(:uint8, 32)
  bits_written = PCProxLib.getActiveID32(buffer, 32)
  puts bits_written
  puts buffer.read_bytes(32)
end

20.times { read_card }

PCProxLib.USBDisconnect()

When I scan a card (while the code is looping), the bits_written value jumps from 0 to 32, which seems good. However the buffer.read_bytes(32) value is always null.
I've tried some other MemoryPointer methods (like read, read_string etc but get the same results.
If I try .inspecting the buffer.read_bytes(32), I get:
"\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"

...which is interesting? This is the same, whether I scan a card or not.

A: It looks like the function getActiveID32 has a signature that looks something like
int getActiveID32(uint8_t *buffer, int size)

and you would use it by first creating a buffer for it to write into, and then passing a pointer to that buffer and its size as arguments when you call it, something like:
// Define BUFFER_SIZE first.
uint8_t *buffer = malloc(BUFFER_SIZE);
int bits_written = getActiveID32(buffer, BUFFER_SIZE);
// There are now bits_written bits in buffer for you to use.
// You will need to call free on buffer when you are finished.

With Ruby's FFI you can do this with a Pointer. First declare the function to accept a pointer (a string is like a pointer, but in this case we need to use a pointer directly):
attach_function :getActiveID32, [:pointer, :int], :int

Now when you want to call it, you need to first create a MemoryPointer of the desired size, and pass it as the parameter to the function. FFI will then convert this into a pointer to the allocated memory when calling the C function.
# Assuming you want a 32 byte buffer.
buffer = FFI::MemoryPointer.new(:uint8, 32)
bits_written = PCProxLib.getActiveID32(buffer, 32)

Now buffer will contain the data written by the function. You can access this data using the methods on MemoryPointer, for example to copy that data into a Ruby (binary) string you can use buffer.read_bytes(32).
MemoryPointer will also handle freeing the allocated memory when it is garbage collected.


text:
Q: What does "Muslim clockmakers" mean in "He (Trump) vowed to take back the country from Muslim clockmakers? Today's (Sept. 19) New Yorker carries an article titled "Poll: Guy who asked Trump Muslim question leads G.O.P. race," which quoted Donald Trump's assertion - "If you look back over the past seven years, no one has called Obama a foreign-born Muslim more often than I have."
The article wraps up with the following lines:

"Trump's comments did little to slow the momentum of Muslim Question
  Guy, who drew four thousand people at his first official campaign
  rally in Concord, New Hampshire, where he vowed to take back the
  country from Muslim clockmakers."
  http://www.newyorker.com/humor/borowitz-report/poll-guy-who-asked-trump-muslim-question-leads-g-o-p-race?

What does "Muslim clockmakers" specifically mean? Is there any particular reason for being clockmakers? Why not any other trades, say smith, mill owners, merchants, or farmers?

A: Please read the entire article, especially the line at the end which states

Get news satire from The Borowitz Report delivered to your inbox.

The article is satirical (and by satirical, I include non-factual, made-up, or, well, untrue, but intended to be so obviously untrue that nobody is fooled), and "Muslim Clockmakers" is a reference to the 14-year-old student arrested for bringing a homemade (well, repackaged; he didn't actually make it) digital clock to school.
The "quote" from Trump is fabricated.


text:
Q: Why do I get different terms in same document in Lucene? I have an sentence-based index where every document stores the content and a field for every token. The content field is named content and stores the whole sentence as String, the token fields are named token0, token1, ... tonken_n-1 containing each token as a String.
When I used the code sample in the Apache Migration guide to get all unique terms for each field in the example sample "This index is sentence-based.",
for(String field : fields) {
   Terms terms = fields.terms(field);
   TermsEnum termsEnum = terms.iterator(null);
   BytesRef text;
   while((text = termsEnum.next()) != null) {
     System.out.println("field=" + field + "; text=" + text.utf8ToString());
   }
}

sentence-based is recognized as term in the field token3, but in the content field only sentence and based based is recognized.
It seems like fields.terms(field) uses a different Analyzer for each field.
I have no clue why I get different terms when applying fields.terms("content").
I want to get sentence-based as a term out of the content field instead of sentence and based.
I hope there is an explanation for this phenomenon.

A: It sounds like the content field is being analyzed and the tokenN fields aren't. Analysis happens at index time, so what you need to do is revisit your indexing code and find out why content and token fields are being analyzed differently.
If you want the content field to be analyzed, just differently from what you have now, then okay. Do that! SimpleAnalyzer may be a good place to start.


text:
Q: Using == when comparing objects Recently in a job interview I was asked this following question (for Java):
Given:
String s1 = "abc";
String s2 = "abc";

What is the return value of
(s1 == s2)

I answered with it would return false because they are two different objects and == is a memory address comparison rather than a value comparison, and that one would need to use .equals() to compare String objects. I was however told that although the .equals(0 methodology was right, the statement nonetheless returns true. I was wondering if someone could explain this to me as to why it is true but why we are still taught in school to use equals()?

A: String constants are interned by your JVM (this is required by the spec as per here):

All literal strings and string-valued constant expressions are interned. String literals are defined in §3.10.5 of the Java Language Specification

This means that the compiler has already created an object representing the string "abc", and sets both s1 and s2 to point to the same interned object.

A: java will intern both strings, since they both have the same value only one actual string instance will exist in memory - that's why == will return true - both references point to the same instance.
String interning is an optimization technique to minimize the number of string instances that have to be held in memory. String literals or strings that are the values of constant expressions, are interned so as to share unique instances. Think flyweight pattern.

A: Since you are not actually creating new instances of String objects for either one of these, they are sharing the same memory space. If it were
String s1 = new String("abc");
 String s2 = new String("abc");
the result would be false.

A: The reason is strings are interned in Java. String interning is a method of storing only one copy of each distinct string value which is immutable. Interning string makes some string processing tasks more efficient. The distinct values are stored in a string intern pool.
(From wiki)

A: You're right that == uses memory address. However when the java compiler notices that you're using the same string literal multiple times in the same program, it won't create the same string multiple times in memory. Instead both s1 and s2 in your example will point to the same memory. This is called string interning.
So that's why == will return true in this case. However if you read s2 from a file or user input, the string will not automatically interned. So now it no longer points to the same memory. Therefor == would now return false, while equals returns true. And that's why you shouldn't use ==.

A: Quick and dirty answer: Java optimizes strings so if it encounters the same string twice it will reuse the same object (which is safe because String is immutable).
However, there is no guarantee.
What usually happens is that it works for a long time, and then you get a nasty bug that takes forever to figure out because someone changed the class loading context and your == no longer works.

A: You should continue to use equals() when testing string equality.  Java makes no guarantees about identity testing for strings unless they are interned.
The reason the s1 == s2 in your example is because the compiler is simply optimizing 2 literal references in a scope it can predict.


text:
Q: Rails - how to validate f.select field? I have simple select field
f.select(:name, [["- Choose Name -", 0]] + People.all.map{ |c| [c.name, c.id] })

How can I validate, if some name was selected?
I tried this rule:
  validates :name, :presence => {:message => 'Name cannot be blank.'}

But if I send form without choosing the name, the form is sent...
So I would like to ask you, how can I validate the select field?

A: In your example, people are selecting a name, they're selecting the name - Choose Name - with id 0.
If you want to give an option that doesn't correspond to a real choice then you have two options:
f.select(:name, People.all.map{ |c| [c.name, c.id] }, :include_blank => "- Choose Name -")

f.select(:name, People.all.map{ |c| [c.name, c.id] }, :prompt => "- Choose Name -")

These are basically identical. Both will display an option at the top of the select which won't result in a value being set. However, the prompt version will only display this extra option if there isn't a current value selected, i.e. if used on an edit form it won't let the user clear their selection by setting it back to nil
Note that the include_blank method is very similar to the following code, except lots more readable:
f.select(:name, [["- Choose Name -", nil]] + People.all.map{ |c| [c.name, c.id] })


text:
Q: Trouble retrieving numbers using IMPORTXML does anyone know how to grab the # of networks (one at a time in each cell) from a list on this page? After trial and error, I think =IMPORTXML("https://www.peeringdb.com/fac/167","//div[@data-filter-value='BGP.Exchange' and @'participants']") should be most "correct," but the formula isn't working...What did I do wrong? Thanks in advance for any help.

A: try:
=QUERY(IMPORTXML(A1, "//div[@class='scrollable']/div"),
 "select Col3 where Col3 is not null")

A: Try
=importxml($A$1,"//div[@data-filter-value='"&trim(A2)&"']/../..//div[@class='participants']")

Another solution
=arrayformula(vlookup(trim(A2),trim(importxml(A1,"//div[@class='scrollable']//div")),3,0))


text:
Q: what does "not even related to..." mean? I read a sentence:

Not even related to my leukemia my cardiologist had me undergo an MRI to assure that I did not have arterial issues.

How am I to understand the first half of this sentence?

A: "Not even related to", in this context, means "nothing to do with". Your cardiologist wanted you to have an MRI scan to see if you have any problems with your arteries (blood circulation). It had nothing to do with (not related to) the fact that you have leukemia.


text:
Q: Add CSS only to administrator's wordpress dashboard I am using WordPress.
Is there any way to add CSS on administrator's dashboard and not take effect on other users' dashboards?
I tried that but worked for all users
    function custom_css() {
  echo '<style>
    #my_element{display:none;}
  </style>';
}

A: Put your css rules / class in a specific css files (say "admin.css").
Then in your functions file use this code.
add_action( 'admin_enqueue_scripts', 'custom_styles_for_admin' );
function custom_styles_for_admin(){
   if( current_user_can('manage_options') ){
      wp_register_style( 'custom_wp_admin_css', get_template_directory_uri() . '/admin.css', false, '1.0.0' );
      wp_enqueue_style( 'custom_wp_admin_css' );
   }
}

Hope this helps.


text:
Q: passing a function with type parameter as argument I want to create a function g that takes a function f as a parameter, where f has a type parameter. I can't get a signature for g that compiles. One attempt is like this:
scala> def mock1[A](): A = null.asInstanceOf[A] // STUB
mock1: [A]()A

scala> def mock2[A](): A = null.asInstanceOf[A] // STUB
mock2: [A]()A

scala> def g0(f: [A]() => A): Int = f[Int]()
<console>:1: error: identifier expected but '[' found.
       def g0(f: [A]() => A): Int = f[Int]()
                 ^

I can get it to work if I wrap the function that takes a type parameter in a trait, like so:
scala> trait FWrapper { def f[A](): A }
defined trait FWrapper

scala> class mock1wrapper extends FWrapper { def f[A]() = mock1[A]() }
defined class mock1wrapper

scala> class mock2wrapper extends FWrapper { def f[A]() = mock2[A]() }
defined class mock2wrapper

scala> def g(wrapper: FWrapper): Int = wrapper.f[Int]()
g: (wrapper: FWrapper)Int

scala> g(new mock1wrapper)
res8: Int = 0

Is there a way I can accomplish this without introducing the wrapper class?

A: Scala does (currently) not have support for polymorphic function values. You have two options:

*

*Stick with your wrapper trait (probably easiest to understand)

*Use polymorphic function values from Shapeless (fancy, but maybe a bit complicated)

A: How about this:
  def mock[A](): A = null.asInstanceOf[A]

  def g[A](f:() => A): A = f()

  g(mock[Int])


text:
Q: Strange corruption saving from Textpad 5 within Windows 7-64 VirtualBox VM to shared folder with Mac host I have a fairly new Window-7 64bit install running in Virtual Box on a MacBook Pro.  I'm using TextPad 5 within that environment to edit source files that live on a shared folder that is on the Mac Host.  When I save some of these source files, the saved file ends up with some amount of the end of the file repeated one or more times.  For example, a file that has this at the end:
    ...
    return ttp;
    };

would, once saved, open up with:
   ...
   return ttp;
   };

};

It is definitely a problem with how the file gets written as opposed to how it's read, because I can see this now matter what app I use to open the file with (NotePad & Word in Windows 7, TextWrangler back in the Mac).
I've tried saving as ANSI and UTF-8, and with or without the 'Write Unicode and UTF-8 BOM' checked in TextPad preferences.  It doesn't happen with all files though I can't see any pattern about which files do or don't have the problem.  It doesn't happen with files written to the Windows 7 c:\ drive.  And so far it doesn't happen from other applications saving files, only TextPad.
Any ideas?
My versions:

*

*Textpad 5.4.2

*Windows 7 Professional 64-bit, fully up to date

*VirtualBox 4.0.8 r71778

*OSX 10.6.7

A: This really sounds like a bug in TextPad - I can't think of anything VirtualBox would be doing that would cause it behave this way. The way Shared Folders work, it basically maps a fake network drive to your Windows 7 guest. If it was VirtualBox introducing the strange behavior you should see it manifested in all other apps.
I have seen a number of programs misbehave when saving files before, primarily in how they basically just overwrite the contents of the existing file without actually resetting the file length, or zero'ing out the bytes at the end. What this means is that if you "shorten" your file by removing a few characters or lines, you get the exact behavior described above. You could certainly perform a few tests to really nail down the source of the problem, and use that to get the authors to fix the bugs:

*

*Can you replicate the behavior using Save-As instead of just Save?

*Can you replicate the behavior by making the file shorter? longer?

*Can you replicate the behavior on other network drives? or just Shared Folders features?

*Could any other "filters" be impacting the save operation, e.g. anti-virus, post-build steps, source control, etc.

As a demonstration, using PowerShell - here is how you can replicate the same behavior you are seeing. I started by taking the opening paragraph of A Tale of Two Cities and saving it as tale.txt
$text = gc tale.txt
$fs = [System.IO.File]::OpenWrite("tale.txt")
$sw = New-Object System.IO.StreamWriter($fs)
$sw.Write($text.Replace("the",""))
$sw.Dispose()

You can see that all 15 instances of "the" words have been replaced by the empty string as intended, with the unintended consequence of the last 45 bytes of the original file remaining, thus repeating the phrase "in the superlative degree of comparison only." twice at the end of the file - similar to the situation you describe above.
For completeness, the simple solution to the bad-code example above is to not use the OpenWrite method and instead call the static WriteAllText method on the File class.


text:
Q: Can't get addEventListener() working without adding onclick event as an attribute in button tag This code works if I use an onclick event, but my online lesson says I can't use one, but the code does not work without it. I need to find another to collect the data.
HTML:
<!DOCTYPE html>

        <input name="data" id="data" placeholder="Enter text" type="text">
        <button type="submit" id="submit">Click</button>

Replace this text.

JavaScript:
document.getElementById("submit").addEventListener("click", collect);

function collect() {
    var info = document.getElementById("data").value;
    document.getElementById("replace").innerHTML = info;
}

A: Chances are your javascript is running before the page has loaded.  If the element with the id "submit" does not yet exist when you add the event listener, then obviously there won't be a DOM node with a listener on it.  Then, after the listener has been "added", a DOM node is created without an event listener.
So, you just need to run the javascript after page load:
window.onload = function () {
    document.getElementById("submit").addEventListener("click", collect);
    function collect() {
        var info = document.getElementById("data").value;
        document.getElementById("replace").innerHTML = info;
    }
}

Or put the script at the end (or do both):
<!DOCTYPE html>

        <input name="data" id="data" placeholder="Enter text" type="text">
        <button type="submit" id="submit">Click</button>

Replace this text.

A: Use this jquery script
$(document).ready(function(){
    $("submit").click(function(){
       var info = document.getElementById("data").value;
       document.getElementById("replace").innerHTML = info;
     });
});


text:
Q: How to link.so into a Visual Studio ndk dynamic shared library I want to use tess-two api in my ndk dynamic shared library.
I try to add libtess.so and liblept.so in
Project->Properties->Linker->Input->Library Dependencies

and add this lines:
[path]\libtess.so
[path]\liblept.so

But in this case i can't use tesseract includes.
I also try to compile tess-two and it's dependencies using some visual studio dynamic shared library projects (tess, lebpt, jpeg, png) but it can't compile jpeg and png libraries and gives several errors!
So main question is can i link a/some .so file(s) into a Visual Studio ndk dynamic shared library without having any source code of those .so files?


text:
Q: Sharing object between files Just say i have a file (file A) that does some work for me with reactivity and stores multiple object in a array . How can I share that object with multiple files lets just say file B and file C.
I am using metoerJs by the way thanks.

A: You can simply export the shared object so that other files could import them:
File foo.js:
const arr = {};

arr.push(123);

export { arr };

Then import in file bar.js:
import { arr } from './foo.js';

This is pretty simple, but there is something you should know. It look like you are using arr to store some of your app data, arr is declared inside foo.js not in a function that means arr will be stored in RAM and not be garbage-collected until your app re-run. That my cause you some problems:

*

*If arr is a big array of objects, it will cost you quite a lot of RAM.

*If your app is in production, re-deploy the app will reset the value of arr
So be careful when using this approach.


text:
Q: Unable to determine if any bash script is still running without modifying or renaming script We come across various customer bash scripts that could be doing anything. I don't care what it does but I need a simple way of determining whether the .sh script has finished or if it's still doing something which could be many minutes. The scripts cannot be modified, renamed or moved. We also need to be able to output anything that the script outputs to stdout; so we can't > null either.
I've found various posts about this but no solution is working. I tried creating a simple test.sh script that just contains echo "Hello World" and a for do loop so that the script never stops but I cannot find a working solution that tells me yes, the script is still running. Solution needs to be as simple as possible, such as a one liner. I tried something simple like
if $? -eq 0 then script finished successfully

but $? will always return some number but this won't tell you if it's finished running or not.
pgrep -l ./test.sh or pgrep -x ./test.sh

was posted as a solution for others but this doesn't work for me. It just goes to the command prompt and not printing any output.
The test.sh script I created doesn't show up as a process either. Seems to just show -bash and that's it. Need this working for Unix/Linux.
What else can I do to determine that a script is still running and hasn't returned to the command prompt?
UPDATE: Maybe this explains my problem better. When you open an ssh terminal session and run a script that may take 2 mins or 20 mins to finish you know it's done when you see the command prompt again. So you don't type the next command until you see the prompt. Easy.
But how can you do the same thing without any human assistance? How can I tell Linux to

*

*From a windows pc, open an SSH session to a remote pc and

*run ./script.sh and

*run the command whoami ONLY when 2) has completed successfully?

All this without writing and executing a separate script, or making changes to the script in step 2)? In other words only from a command prompt. So you can still use multiple linux commands separated by ; or if possible, write a script on the command line without saving it and then executing this command (pressing ENTER)? It's kind of hard to explain this but hopefully this makes more sense now.


text:
Q: Background-Image in  element Can someone help me to find my Problem ?
I have a  and will give him a background-image within a  tag.
Here is my example:

Background-Color didn't work to.. :-( My Example is a JavaScript String, thats the reason why I'm escaping the URL
Thank's for help :-)

A: You are escaping your quote marks and have transposed the second quote mark and bracket.
In CSS:
url('foo')   /* is technically fine but broken on IE/Mac */
url(foo)     /* is fine */
url('foo)'   /* is not fine */
url(\'foo\') /* is not fine */

And as Ross points out in a comment, your src attribute is missing. I imagine that setting a background-image on an image with a translucent background will work, but if you don't have a content image, don't use an  element (and don't hide any content images you do have in in background-image properties).

A: you dont even need the quote marks.
background:url(./images/system/button/close/close.png)

use a div if you can

A: Don't understand why you are escaping the quotes.

Does that work?
And are you sure about the . in the URL?

A: background-color:red; is being superseded by background:.
Combine your backgrounds. You can then refine it further by removing the quotes in the URL() of the background and the period from the URL. if it is relative to the location of the page it is on just remove the backslash.

Last if you need to have an alt attribute its contents will show up since there is no source. Use a transparent image if you add the alt.

A: Well, even if it's weird to use the  tag for this. (it's not its purpose, use src or a div with background...)
Here, it's working


text:
Q: Possible ways to migrate data from MS Access to SQL Server 2008 Express I have database in MS Access in which new table is generated to store the records of each day. I want to transfer the data from the current day table to SQL Server Table.
In SQL server I have only one table and Data will append everyday.
What are the possible ways to achieve this functionality.
Thanks

A: There are many ways you can do this.The one is Import Export Wizard which is listed below:
1) Using Import-Export wizard: This will do is get the data from source (for you will be Access) and put it in Destination database ( which will be SQL Server)
You can call this package through SQL Agent ( you can make it run every day, weekly, monthly)
Import and Export wizard
http://www.packtpub.com/article/transferring-data-ms-access-2003-to-sql-server-2008

A: I would explore creating a Linked Server to Access, and create a stored procedure to load the data, which you could schedule with the Windows Task Scheduler and sqlcmd.

A: Taken from MSDN post
http://social.msdn.microsoft.com/forums/sqlserver/en-US/015d8295-a57a-4dc9-b3e2-6da1cfe8ab6d/convert-an-access-db-to-sqlexpress
Access has a tool called the Upsize Wizard built directly into the product to help you do this. A second alternative is the SQL Server Migration Assistant for Access, which you can learn about here http://technet.microsoft.com/en-us/library/hh313039.aspx.
Download link below
http://www.microsoft.com/en-in/download/details.aspx?id=28763


text:
Q: generate JSON from json schema dynamically I need to read data from database and send it to some MQ in JSON format.
I am using java 8,spring boot.
My current process  --
Read Data from DB --- > Map to POJO --- >Convert to JSON using object mapper (Jackson )
Problem with above is my Pojo classes need to be changed if JSON structure changes.
How can I avoid it?
Below is the JSON schema that I have. Suppose if some field gets added to this schema. How can I avoid the code change?
Can I make it dynamic? Eg. lets say some fields get added to fname,lname or address. How can I avoid the code change?
{
    "name":   {
                "fname" :  {
                             "displayName":"FirstName",
                             "dataType":"String"
                           }
                "lname"  : {
                             "displayName":"LastName",
                             "dataType":"String"
                           }
               },
    "address": {
                   "displayName":"Address",
                   "dataType":"String"
               }
  }

A: *

*Add GSON Dependency

*To make it prettyPrinting use GsonBuilder()->
  GsonBuilder().setPrettyPrinting().create();

*toJson(Object)
<dependency>
    <groupId>com.google.code.gson</groupId>
    <artifactId>gson</artifactId>
    <version>2.8.5</version>
</dependency>

Gson gson = new GsonBuilder().setPrettyPrinting().create();
Person person = newPerson();
String jsonString = gson.toJson(person);
System.out.println(jsonString);

private static Person newPerson() {
 List<String> hobbies = Arrays.asList("Cricket", "Guitar", "Coin Collection");
 Map<String, String> languages = new HashMap<>();
 languages.put("French", "Beginner");
 languages.put("German", "Intermediate");
 languages.put("Spanish", "Advanced");
 Person person = new Person("Max", 22, hobbies, languages);
 return person;
}


text:
Q: Can anyone help me fetch a data from a web service with the retrofit? I am trying to fetch some data from a web service to my android app. I am doing that with a retrofit but I can't get a specific string(joke) value based on id.
I fetch data from this URL: http://api.icndb.com/jokes/random/3.
When I enter an id as an integer in my app EditText I want with this id retrieve a joke with specific id from web service I mentioned above.
For example when I enter 179 as id in my app EditText and click "Start Retrofit" button I want to get this String value from web service "Chuck Norris? favourite cut of meat is the roundhouse." This string value I want to show as a toast message in my app.
I have already prepared my app code but I need some correction in interface @Query and @GET method and especially in Callback interface success method
where I want to show a fetched data.
My app has next classes: MainActivity.class, activity_main.xml, Joke.class(I used a POJO to get this class from JSON), JokeInterface.
I have already entered a internet permission in a manifest and  "implementation 'com.squareup.retrofit:retrofit:1.9.0'" in my build.gradle as a dependency.
I put a comment in MainActivity.class and JokeInterface.class where I think that need to enter some code to accomplish my task.
Here is my code:
activity_main:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@android:color/holo_blue_bright"
    android:padding="20dp"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/textView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="19dp"
        android:textSize="20sp"
        android:textColor="@android:color/black"
        android:text="Joke Id" />

    <EditText
        android:id="@+id/etEnterId"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="57dp"
        android:gravity="center"
        android:ems="10"
        android:hint="Enter id"
        android:inputType="number" />

    <Button
        android:id="@+id/btnStartRetrofit"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="188dp"
        android:text="Start Retrofit" />
</RelativeLayout>

MainActivity.class:
package com.example.dezox.restwebservis;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.example.dezox.restwebservis.model.Joke;

import java.util.List;

import retrofit.RestAdapter;
import retrofit.Callback;
import retrofit.RetrofitError;
import retrofit.client.Response;

public class MainActivity extends AppCompatActivity {

    private EditText etEnterId;
    private Button btnStartRetrofit;
    private JokeInterface jokeInterface;
    private Callback<Joke> call;

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

        initWidgets();
        setupListener();
        setupRestAdapter();
    }

    private void initWidgets() {
        etEnterId = findViewById(R.id.etEnterId);
        btnStartRetrofit = findViewById(R.id.btnStartRetrofit);
    }

    private void setupListener() {

        btnStartRetrofit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (etEnterId.getText().length() > 0){
                    int id = Integer.parseInt(etEnterId.getText().toString());
                    getJokeMethod(id);
                }

            }
        });
    }

    private void getJokeMethod(int id) {
        jokeInterface.getJoke(id, call);
    }

    private void setupRestAdapter(){
        RestAdapter restAdapter = new RestAdapter.Builder().setEndpoint(JokeInterface.ENDPOINT_URL).build();
        jokeInterface = restAdapter.create(JokeInterface.class);

        call = new Callback<Joke>() {
            @Override
            public void success(Joke joke, Response response) {
                StringBuilder builder = new StringBuilder();
                builder.append(joke.getType()+"\n");
 /*NOTE:
 Here I need some code for a showing the string data in a toast message*/

                Toast.makeText(getApplicationContext(), builder, Toast.LENGTH_LONG).show();
            }

            @Override
            public void failure(RetrofitError error) {

            }
        };

    }

}

Joke.class:(POJO)
package com.example.dezox.restwebservis.model;

import java.util.List;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

public class Joke {

    @SerializedName("type")
    @Expose
    private String type;
    @SerializedName("value")
    @Expose
    private List<Value> value = null;

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

    public List<Value> getValue() {
        return value;
    }

    public void setValue(List<Value> value) {
        this.value = value;
    }

}

    class Value {

    @SerializedName("id")
    @Expose
    private Integer id;
    @SerializedName("joke")
    @Expose
    private String joke;
    @SerializedName("categories")
    @Expose
    private List<String> categories = null;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getJoke() {
        return joke;
    }

    public void setJoke(String joke) {
        this.joke = joke;
    }

    public List<String> getCategories() {
        return categories;
    }

    public void setCategories(List<String> categories) {
        this.categories = categories;
    }

}

JokeInterface.class:
package com.example.dezox.restwebservis;

import com.example.dezox.restwebservis.model.Joke;

import retrofit.Callback;
import retrofit.http.GET;
import retrofit.http.Query;

public interface JokeInterface {

    public static final String ENDPOINT_URL = "http://api.icndb.com/";

    @GET("/")

    void getJoke(@Query("") int id, Callback<Joke> callback);

/*NOTE:
Here I need some code in GET and Query in order to fetch a string
joke with specific id.*/

        }

A: Now I found out, the url you are calling returned list of jokes.
"http://api.icndb.com/jokes/random/3" means - you are getting 3 object of random jokes. So if you call like "http://api.icndb.com/jokes/random/179", then you will get list of 179 random jokes. In this case 3 and 179 are not ids, they meant to be object count.
If you want only one joke at a time with specific id, you can call like "http://api.icndb.com/jokes/179", this will give you output like -
{ "type": "success", "value": { "id": 179, "joke": "Chuck Norris? favourite cut of meat is the roundhouse.", "categories": [] } }

and the "value" in "Joke" (POJO class) will not be list anymore,
@SerializedName("value")
@Expose
private Value value;

call as,
@GET("jokes/{id}")
void getJoke(@Path("id") int id, Callback<Joke> callback);

and you can show the returned joke value like,
 @Override
        public void success(Joke joke, Response response) {
            Toast.makeText(getApplicationContext(), joke.getValue().getJoke(), Toast.LENGTH_LONG).show();
        }

Hopes this help!


text:
Q: URL Redirection untrusted Site Can anybody tell me how can validate this URL in this line ?
return Redirect(returnUrl);

As this is giving me a security error "URL Redirection untrusted Site" from the Security Scanning tool

A: You simply need to test that the URL is a local URL before performing the redirection as a malformed url could redirect your users to another site (like a phishing site).  As your code currently stands, this URL:
http://www.yoursite.com/account/login?returnUrl=www.myfakesite.com

will redirect you to www.myfakesite.com once you login
By adding this conditional check below, you can ensure you never redirect outside of your current application
if(!string.IsNullOrEmpty(returnUrl) && Url.IsLocalUrl(returnUrl)){
    //check for empty return url and that it is a local url
    return Redirect(returnUrl);
}
else{
     //wherever you want people to default going to if they
     //log in without a return url or one that is not a local url.
     return RedirectToAction("action", "controller");
}

EDIT
The Url helper assembly is located in System.Web.Mvc.  However, in a controller, the UrlHelper is already setup and ready to go - meaning the controller instantiates the UrlHelper "automatically".  In order to use this outside of a controller, you need access to the current RequestContext in order to setup the UrlHelper.
   var helper = new UrlHelper(HttpContext.Current.Request.RequestContext);
   return helper.IsLocalUrl("testUrl");

Note - I have no idea how the security scanning software is determining that this could be a "URL redirection untrusted site" - but it is probably just sending a bad url and seeing if the application is redirecting to it.  This should correct that, but without more information on how the security scan works, I cannot guarantee.


text:
Q: How to copy an image to the clipboard from a file using command line? I'd like to write a script to take an image file, scale it 50% and put it on the clipboard so it can be pasted easily. The bit I'm stuck on is how to place an image on the clipboard.
I know of xclip, but AFAICS that only deals with text. Is it possible to have an image on the clipboard without the application that generated it sitting around? - Sorry I'm not sure of the internals of how the clipboard works!
EDIT
Thanks to Florian's answer below I was able to achieve what I wanted, which was to take a screenshot and automatically scale it to a max of 600px wide (e.g. for pasting into an email). The further problem I faced was that Thunderbird won't accept image/png from the clipboard. I got round this by converting it to text/html with a data url. Here's my code in case anyone finds it useful:
#!/bin/bash
TMP=/tmp/screenshot.png
function screenshotfail {
  notify-send -u low -i image "Screenshot failed."
  exit
}
# Take screenshot
gnome-screenshot -a -b -p -f "$TMP" || screenshotfail
# Ensure it's max 600px wide
mogrify -resize '>600x' "$TMP" || screenshotfail
# optimise the png if optipng is installed.
which optipng >/dev/null && optipng "$TMP"

# Copy to clipboard.
#
# This is what does not work for Thunderbird:
#   xclip -selection clipboard -t image/png <"$TMP" || screenshotfail
# But this does:
echo "<img src='data:image/png;base64,"$(base64 -w0 "$TMP")"' />" | \
  xclip -selection clipboard -t text/html || screenshotfail

# Remove the temp file.
rm -f "$TMP"

# Notify user.
notify-send -u low -i image "600px screenshot copied to clipboard"

A: Use the -t option to specify the content type, like
xclip -selection clipboard -t image/png -i example.png


text:
Q: .toggle() doesn't work but adds overflow: hidden

$(document).ready(function() {

  $('.post__action.post__circle.share').each(function() {
    $(this).click(function() {
      $(this).closest('ul').next('.share-button').toggle('scale', 800);
    })
  });

});
body {
  background: #eee;
  font-family: Helvetica, sans-serif;
  font-size: 13px;
  color: #000;
  margin: 0;
  padding: 0;
  -moz-osx-font-smoothing: grayscale;
  -webkit-font-smoothing: antialiased;
  font-smoothing: antialiased;
}

a {
  text-decoration: none;
  color: ;
}

.material-icons {
  vertical-align: middle;
}

p {
  margin: 0;
  text-align: justify;
}

blockquote {
  padding-top: 0px!important;
  border-left: 1px solid #eee;
  padding-left: 10px;
  margin: 0px 10px;
  padding-bottom: 0px!important;
}

b,
strong {
  font-weight: normal;
  color: #333;
}

img {
  opacity: 1;
  border: none;
  text-decoration: none;
  max-width: 100%;
}

small {
  font-size: calc(13px - 1px);
}

big {
  font-size: calc(13px + 1px);
}

/* POSTs */

#posts {
  width: 100%;
  height: auto;
  margin-bottom: 100px;
  margin-left: 50px;
}

.entry {
  position: relative;
  float: left;
  width: 300px;
  height: auto;
  margin: 10px;
  padding: 10px;
  background: #fff;
  text-align: center;
  border-radius: 10px;
}

.post-text,
.post-photo,
.post-photoset,
.post-quote,
.post-link,
.post-chat,
.post-video,
.post-audio,
.post-answer {
  width: 290px;
  max-height: 250px;
  min-height: 250px;
  overflow: hidden;
}

.post-info {
  margin-top: 10px;
}

.post-info .note-count {
  margin: 0 0.5rem 0.75rem 0;
  padding: 0.6rem;
  font-weight: 700;
  color: #fff;
  background: pink;
  border-radius: 1.125rem;
  border: 3px solid pink;
}

/* Actions */

.post__actions {
  display: inline-block;
  margin: 0;
  padding: 0;
  vertical-align: middle;
}

.post__action>* {
  cursor: pointer;
  margin: 0 auto;
  line-height: 2.2rem;
}

.post__action:last-child {
  margin-right: 0;
}

@media (min-width: 769px) {
  .post__action>* {
    line-height: inherit;
  }
}

/* Post Circles */

.post__circle {
  background: pink;
  min-width: 2.25rem;
  height: 2.25rem;
  margin: 0 0.5rem 0.25rem 0;
  border: 3px solid pink;
  border-radius: 1.125rem;
  line-height: 2.5rem;
  color: #fff;
  text-align: center;
  display: inline-block;
  vertical-align: middle;
}

.post__circle i {
  line-height: inherit;
}

.share-button {
  margin: 5px auto;
  width: calc(2.25rem*4);
  height: 2.25rem;
  line-height: 2.25rem;
  background: #eee;
  border-radius: 10px;
}

.share-button a {
  color: pink;
  font-size: 20px;
  margin: 5px;
  vertical-align: middle;
  -webkit-transition: 0.5s ease;
  -moz-transition: 0.5s ease;
  -ms-transition: 0.5s ease;
  -o-transition: 0.5s ease;
  transition: 0.5s ease;
}

.share-button a:hover {
  color: blue;
}

.tags {
  margin: 10px;
}

.post-info span {
  font-weight: 700;
  margin: 5px;
}

.tags a {
  background: none;
  color: pink;
  border: 2px solid pink;
  margin: 5px;
  padding: 5px;
  border-radius: 1.125rem;
  -webkit-transition: 0.3s ease;
  -moz-transition: 0.3s ease;
  -ms-transition: 0.3s ease;
  -o-transition: 0.3s ease;
  transition: 0.3s ease;
}

.tags a:hover {
  background: pink;
  color: #fff;
}

.notes {
  overflow: auto;
  max-height: 300px;
  border: 2px solid pink;
  border-radius: 1.125rem;
}

ol.notes {
  list-style-type: none;
  font-style: normal;
}

ol.notes li.note {
  padding: 5px;
  display: inline-block;
  float: left;
}

.notes_loading,
.more_notes_link {
  font-weight: bold;
  float: left;
  text-align: left!important;
  text-transform: lowercase;
}

.notes img {
  width: 30px;
  border-radius: 0.5rem;
}

ol.notes li.note span.action {
  display: none!important;
}

ol.notes li.note .answer_content {
  font-weight: normal;
}

/* AUDIO */

.player {
  display: block;
  margin: auto;
  width: 40px;
  background: #fafafa;
  height: 40px;
  border-radius: 5px;
  overflow: hidden;
}

.audio_d {
  margin: 10px 0px;
  text-align: center;
  color: #222;
  font-size: 9px;
  text-transform: uppercase;
  letter-spacing: 1px;
}

.tumblr_audio_player {
  width: 30px;
  margin: 5px;
  height: 30px;
  border-radius: 5px;
  overflow: hidden;
}

.question {
  padding: 7px;
  margin-left: 2px;
  background: blue;
  color: #fff;
  text-align: left;
  border-radius: 5px;
}

.question img {
  width: 32px;
  height: 32px;
  margin-right: 7px;
  display: block;
  border-radius: 3px;
  float: left;
}

.asker {
  text-transform: uppercase;
  font-size: 7.5px;
  letter-spacing: 1px;
}
<link href='https://fonts.googleapis.com/icon?family=Material+Icons' rel='stylesheet' type='text/css'>
<link href="//maxcdn.bootstrapcdn.com/font-awesome/4.1.0/css/font-awesome.min.css" rel="stylesheet" type="text/css">

1 feedback

<svg width="100%" height="100%" viewBox="0 0 21 21" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" fill="#fff"><path d="M5.01092527,5.99908429 L16.0088498,5.99908429 L16.136,9.508 L20.836,4.752 L16.136,0.083 L16.1360004,3.01110845 L2.09985349,3.01110845 C1.50585349,3.01110845 0.979248041,3.44726568 0.979248041,4.45007306 L0.979248041,10.9999998 L3.98376463,8.30993634 L3.98376463,6.89801007 C3.98376463,6.20867902 4.71892527,5.99908429 5.01092527,5.99908429 Z"></path><path d="M17.1420002,13.2800293 C17.1420002,13.5720293 17.022957,14.0490723 16.730957,14.0490723 L4.92919922,14.0490723 L4.92919922,11 L0.5,15.806 L4.92919922,20.5103758 L5.00469971,16.9990234 L18.9700928,16.9990234 C19.5640928,16.9990234 19.9453125,16.4010001 19.9453125,15.8060001 L19.9453125,9.5324707 L17.142,12.203"></path></svg>

share

mail_outline

0 feedback

<svg width="100%" height="100%" viewBox="0 0 21 21" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" fill="#fff"><path d="M5.01092527,5.99908429 L16.0088498,5.99908429 L16.136,9.508 L20.836,4.752 L16.136,0.083 L16.1360004,3.01110845 L2.09985349,3.01110845 C1.50585349,3.01110845 0.979248041,3.44726568 0.979248041,4.45007306 L0.979248041,10.9999998 L3.98376463,8.30993634 L3.98376463,6.89801007 C3.98376463,6.20867902 4.71892527,5.99908429 5.01092527,5.99908429 Z"></path><path d="M17.1420002,13.2800293 C17.1420002,13.5720293 17.022957,14.0490723 16.730957,14.0490723 L4.92919922,14.0490723 L4.92919922,11 L0.5,15.806 L4.92919922,20.5103758 L5.00469971,16.9990234 L18.9700928,16.9990234 C19.5640928,16.9990234 19.9453125,16.4010001 19.9453125,15.8060001 L19.9453125,9.5324707 L17.142,12.203"></path></svg>

share

mail_outline

0 feedback

<svg width="100%" height="100%" viewBox="0 0 21 21" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" fill="#fff"><path d="M5.01092527,5.99908429 L16.0088498,5.99908429 L16.136,9.508 L20.836,4.752 L16.136,0.083 L16.1360004,3.01110845 L2.09985349,3.01110845 C1.50585349,3.01110845 0.979248041,3.44726568 0.979248041,4.45007306 L0.979248041,10.9999998 L3.98376463,8.30993634 L3.98376463,6.89801007 C3.98376463,6.20867902 4.71892527,5.99908429 5.01092527,5.99908429 Z"></path><path d="M17.1420002,13.2800293 C17.1420002,13.5720293 17.022957,14.0490723 16.730957,14.0490723 L4.92919922,14.0490723 L4.92919922,11 L0.5,15.806 L4.92919922,20.5103758 L5.00469971,16.9990234 L18.9700928,16.9990234 C19.5640928,16.9990234 19.9453125,16.4010001 19.9453125,15.8060001 L19.9453125,9.5324707 L17.142,12.203"></path></svg>

share

mail_outline

5 feedback

<svg width="100%" height="100%" viewBox="0 0 21 21" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" fill="#fff"><path d="M5.01092527,5.99908429 L16.0088498,5.99908429 L16.136,9.508 L20.836,4.752 L16.136,0.083 L16.1360004,3.01110845 L2.09985349,3.01110845 C1.50585349,3.01110845 0.979248041,3.44726568 0.979248041,4.45007306 L0.979248041,10.9999998 L3.98376463,8.30993634 L3.98376463,6.89801007 C3.98376463,6.20867902 4.71892527,5.99908429 5.01092527,5.99908429 Z"></path><path d="M17.1420002,13.2800293 C17.1420002,13.5720293 17.022957,14.0490723 16.730957,14.0490723 L4.92919922,14.0490723 L4.92919922,11 L0.5,15.806 L4.92919922,20.5103758 L5.00469971,16.9990234 L18.9700928,16.9990234 C19.5640928,16.9990234 19.9453125,16.4010001 19.9453125,15.8060001 L19.9453125,9.5324707 L17.142,12.203"></path></svg>

share

mail_outline

0 feedback

<svg width="100%" height="100%" viewBox="0 0 21 21" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" fill="#fff"><path d="M5.01092527,5.99908429 L16.0088498,5.99908429 L16.136,9.508 L20.836,4.752 L16.136,0.083 L16.1360004,3.01110845 L2.09985349,3.01110845 C1.50585349,3.01110845 0.979248041,3.44726568 0.979248041,4.45007306 L0.979248041,10.9999998 L3.98376463,8.30993634 L3.98376463,6.89801007 C3.98376463,6.20867902 4.71892527,5.99908429 5.01092527,5.99908429 Z"></path><path d="M17.1420002,13.2800293 C17.1420002,13.5720293 17.022957,14.0490723 16.730957,14.0490723 L4.92919922,14.0490723 L4.92919922,11 L0.5,15.806 L4.92919922,20.5103758 L5.00469971,16.9990234 L18.9700928,16.9990234 C19.5640928,16.9990234 19.9453125,16.4010001 19.9453125,15.8060001 L19.9453125,9.5324707 L17.142,12.203"></path></svg>

share

mail_outline

I'm trying to toggle a single 'share' div when clicking on an li above. I had to use this because there are multiple similar divs and different 'share' divs for each one of them. This is the code I've used so far :
$(document).ready(function(){

    $('.post__action.post__circle.share').each(function() {
        $(this).click(function() {
            $(this).closest('ul').next('.share-button').toggle('scale', 800);
        })
    });

});

But the div share-button isn't toggling, instead (in the dev tools) an overflow: hidden style is added inline. I have no idea why it's doing that. The div is hidden by default and there is no overflow indication in the style sheet.
Here is the website. It's the share button on each post.
Thanks for the help!
(sorry the snippet's html is very long, I did it very quickly for you to be able to see it)

A: I have solved the issue by replacing toggle with a condition and show/hide functions. But the div was covered by the other posts, I added masonry. Now my problem is that, it seems masonry is working with a one click delay. Here's the example to make it clearer :

$(document).ready(function() {

var $masonry = $('#posts').masonry({
  itemSelector: '.entry',
});

  $('.post__action.post__circle.share').each(function() {
   var canShare = false;
    $(this).click(function() {
     if (canShare == true){
        $(this).closest('ul').nextAll().first('.share-button').hide(800);
        canShare = !canShare;
     } else {
       $(this).closest('ul').nextAll().first('.share-button').show(800);
        canShare = !canShare;
      }
      $masonry.masonry();
    })
  });

});
body {
  background: #eee;
  font-family: Helvetica, sans-serif;
  font-size: 13px;
  color: #000;
  margin: 0;
  padding: 0;
  -moz-osx-font-smoothing: grayscale;
  -webkit-font-smoothing: antialiased;
  font-smoothing: antialiased;
}

a {
  text-decoration: none;
  color: ;
}

.material-icons {
  vertical-align: middle;
}

p {
  margin: 0;
  text-align: justify;
}

blockquote {
  padding-top: 0px!important;
  border-left: 1px solid #eee;
  padding-left: 10px;
  margin: 0px 10px;
  padding-bottom: 0px!important;
}

b,
strong {
  font-weight: normal;
  color: #333;
}

img {
  opacity: 1;
  border: none;
  text-decoration: none;
  max-width: 100%;
}

small {
  font-size: calc(13px - 1px);
}

big {
  font-size: calc(13px + 1px);
}

/* POSTs */

#posts {
  width: 100%;
  height: auto;
  margin-bottom: 100px;
  margin-left: 50px;
}

.entry {
  position: relative;
  float: left;
  width: 300px;
  height: auto;
  margin: 10px;
  padding: 10px;
  background: #fff;
  text-align: center;
  border-radius: 10px;
}

.post-text,
.post-photo,
.post-photoset,
.post-quote,
.post-link,
.post-chat,
.post-video,
.post-audio,
.post-answer {
  width: 290px;
  max-height: 250px;
  min-height: 250px;
  overflow: hidden;
}

.post-info {
  margin-top: 10px;
}

.post-info .note-count {
  margin: 0 0.5rem 0.75rem 0;
  padding: 0.6rem;
  font-weight: 700;
  color: #fff;
  background: pink;
  border-radius: 1.125rem;
  border: 3px solid pink;
}

/* Actions */

.post__actions {
  display: inline-block;
  margin: 0;
  padding: 0;
  vertical-align: middle;
}

.post__action>* {
  cursor: pointer;
  margin: 0 auto;
  line-height: 2.2rem;
}

.post__action:last-child {
  margin-right: 0;
}

@media (min-width: 769px) {
  .post__action>* {
    line-height: inherit;
  }
}

/* Post Circles */

.post__circle {
  background: pink;
  min-width: 2.25rem;
  height: 2.25rem;
  margin: 0 0.5rem 0.25rem 0;
  border: 3px solid pink;
  border-radius: 1.125rem;
  line-height: 2.5rem;
  color: #fff;
  text-align: center;
  display: inline-block;
  vertical-align: middle;
}

.post__circle i {
  line-height: inherit;
}

.share-button {
  margin: 5px auto;
  width: calc(2.25rem*4);
  height: 2.25rem;
  line-height: 2.25rem;
  background: #eee;
  border-radius: 10px;
  display:none;
}

.share-button a {
  color: pink;
  font-size: 20px;
  margin: 5px;
  vertical-align: middle;
  -webkit-transition: 0.5s ease;
  -moz-transition: 0.5s ease;
  -ms-transition: 0.5s ease;
  -o-transition: 0.5s ease;
  transition: 0.5s ease;
}

.share-button a:hover {
  color: blue;
}

.tags {
  margin: 10px;
}

.post-info span {
  font-weight: 700;
  margin: 5px;
}

.tags a {
  background: none;
  color: pink;
  border: 2px solid pink;
  margin: 5px;
  padding: 5px;
  border-radius: 1.125rem;
  -webkit-transition: 0.3s ease;
  -moz-transition: 0.3s ease;
  -ms-transition: 0.3s ease;
  -o-transition: 0.3s ease;
  transition: 0.3s ease;
}

.tags a:hover {
  background: pink;
  color: #fff;
}

.notes {
  overflow: auto;
  max-height: 300px;
  border: 2px solid pink;
  border-radius: 1.125rem;
}

ol.notes {
  list-style-type: none;
  font-style: normal;
}

ol.notes li.note {
  padding: 5px;
  display: inline-block;
  float: left;
}

.notes_loading,
.more_notes_link {
  font-weight: bold;
  float: left;
  text-align: left!important;
  text-transform: lowercase;
}

.notes img {
  width: 30px;
  border-radius: 0.5rem;
}

ol.notes li.note span.action {
  display: none!important;
}

ol.notes li.note .answer_content {
  font-weight: normal;
}

/* AUDIO */

.player {
  display: block;
  margin: auto;
  width: 40px;
  background: #fafafa;
  height: 40px;
  border-radius: 5px;
  overflow: hidden;
}

.audio_d {
  margin: 10px 0px;
  text-align: center;
  color: #222;
  font-size: 9px;
  text-transform: uppercase;
  letter-spacing: 1px;
}

.tumblr_audio_player {
  width: 30px;
  margin: 5px;
  height: 30px;
  border-radius: 5px;
  overflow: hidden;
}

.question {
  padding: 7px;
  margin-left: 2px;
  background: blue;
  color: #fff;
  text-align: left;
  border-radius: 5px;
}

.question img {
  width: 32px;
  height: 32px;
  margin-right: 7px;
  display: block;
  border-radius: 3px;
  float: left;
}

.asker {
  text-transform: uppercase;
  font-size: 7.5px;
  letter-spacing: 1px;
}

<link href='https://fonts.googleapis.com/icon?family=Material+Icons' rel='stylesheet' type='text/css'>
<link href="//maxcdn.bootstrapcdn.com/font-awesome/4.1.0/css/font-awesome.min.css" rel="stylesheet" type="text/css">

1 feedback

<svg width="100%" height="100%" viewBox="0 0 21 21" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" fill="#fff"><path d="M5.01092527,5.99908429 L16.0088498,5.99908429 L16.136,9.508 L20.836,4.752 L16.136,0.083 L16.1360004,3.01110845 L2.09985349,3.01110845 C1.50585349,3.01110845 0.979248041,3.44726568 0.979248041,4.45007306 L0.979248041,10.9999998 L3.98376463,8.30993634 L3.98376463,6.89801007 C3.98376463,6.20867902 4.71892527,5.99908429 5.01092527,5.99908429 Z"></path><path d="M17.1420002,13.2800293 C17.1420002,13.5720293 17.022957,14.0490723 16.730957,14.0490723 L4.92919922,14.0490723 L4.92919922,11 L0.5,15.806 L4.92919922,20.5103758 L5.00469971,16.9990234 L18.9700928,16.9990234 C19.5640928,16.9990234 19.9453125,16.4010001 19.9453125,15.8060001 L19.9453125,9.5324707 L17.142,12.203"></path></svg>

share

mail_outline

0 feedback

<svg width="100%" height="100%" viewBox="0 0 21 21" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" fill="#fff"><path d="M5.01092527,5.99908429 L16.0088498,5.99908429 L16.136,9.508 L20.836,4.752 L16.136,0.083 L16.1360004,3.01110845 L2.09985349,3.01110845 C1.50585349,3.01110845 0.979248041,3.44726568 0.979248041,4.45007306 L0.979248041,10.9999998 L3.98376463,8.30993634 L3.98376463,6.89801007 C3.98376463,6.20867902 4.71892527,5.99908429 5.01092527,5.99908429 Z"></path><path d="M17.1420002,13.2800293 C17.1420002,13.5720293 17.022957,14.0490723 16.730957,14.0490723 L4.92919922,14.0490723 L4.92919922,11 L0.5,15.806 L4.92919922,20.5103758 L5.00469971,16.9990234 L18.9700928,16.9990234 C19.5640928,16.9990234 19.9453125,16.4010001 19.9453125,15.8060001 L19.9453125,9.5324707 L17.142,12.203"></path></svg>

share

mail_outline

0 feedback

<svg width="100%" height="100%" viewBox="0 0 21 21" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" fill="#fff"><path d="M5.01092527,5.99908429 L16.0088498,5.99908429 L16.136,9.508 L20.836,4.752 L16.136,0.083 L16.1360004,3.01110845 L2.09985349,3.01110845 C1.50585349,3.01110845 0.979248041,3.44726568 0.979248041,4.45007306 L0.979248041,10.9999998 L3.98376463,8.30993634 L3.98376463,6.89801007 C3.98376463,6.20867902 4.71892527,5.99908429 5.01092527,5.99908429 Z"></path><path d="M17.1420002,13.2800293 C17.1420002,13.5720293 17.022957,14.0490723 16.730957,14.0490723 L4.92919922,14.0490723 L4.92919922,11 L0.5,15.806 L4.92919922,20.5103758 L5.00469971,16.9990234 L18.9700928,16.9990234 C19.5640928,16.9990234 19.9453125,16.4010001 19.9453125,15.8060001 L19.9453125,9.5324707 L17.142,12.203"></path></svg>

share

mail_outline

5 feedback

<svg width="100%" height="100%" viewBox="0 0 21 21" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" fill="#fff"><path d="M5.01092527,5.99908429 L16.0088498,5.99908429 L16.136,9.508 L20.836,4.752 L16.136,0.083 L16.1360004,3.01110845 L2.09985349,3.01110845 C1.50585349,3.01110845 0.979248041,3.44726568 0.979248041,4.45007306 L0.979248041,10.9999998 L3.98376463,8.30993634 L3.98376463,6.89801007 C3.98376463,6.20867902 4.71892527,5.99908429 5.01092527,5.99908429 Z"></path><path d="M17.1420002,13.2800293 C17.1420002,13.5720293 17.022957,14.0490723 16.730957,14.0490723 L4.92919922,14.0490723 L4.92919922,11 L0.5,15.806 L4.92919922,20.5103758 L5.00469971,16.9990234 L18.9700928,16.9990234 C19.5640928,16.9990234 19.9453125,16.4010001 19.9453125,15.8060001 L19.9453125,9.5324707 L17.142,12.203"></path></svg>

share

mail_outline

0 feedback

<svg width="100%" height="100%" viewBox="0 0 21 21" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" fill="#fff"><path d="M5.01092527,5.99908429 L16.0088498,5.99908429 L16.136,9.508 L20.836,4.752 L16.136,0.083 L16.1360004,3.01110845 L2.09985349,3.01110845 C1.50585349,3.01110845 0.979248041,3.44726568 0.979248041,4.45007306 L0.979248041,10.9999998 L3.98376463,8.30993634 L3.98376463,6.89801007 C3.98376463,6.20867902 4.71892527,5.99908429 5.01092527,5.99908429 Z"></path><path d="M17.1420002,13.2800293 C17.1420002,13.5720293 17.022957,14.0490723 16.730957,14.0490723 L4.92919922,14.0490723 L4.92919922,11 L0.5,15.806 L4.92919922,20.5103758 L5.00469971,16.9990234 L18.9700928,16.9990234 C19.5640928,16.9990234 19.9453125,16.4010001 19.9453125,15.8060001 L19.9453125,9.5324707 L17.142,12.203"></path></svg>

share

mail_outline

Or jsfiddle
Does anyone know why this is happening? And how to fix it? Thank you!