text:
Q: Search in Pandas DataFrame I have two dataframes as below:
import pandas as pd
raw_data = {
        'employee_id': ['4444', '5555', '6666','7777','8888'],
        'first_name': ['aa', 'Jason', 'Tina', 'Jake', 'Amy'],
        'last_name': ['Miller', 'Millers', 'Ali', 'Milner', 'Cooze'],
        'age': [42, 42, 36, 24, 73],
}
df1 = pd.DataFrame(raw_data, columns = ['employee_id','first_name', 'last_name', 'age'])

raw_data1 = {'employee_id': ['4444', '5555', '6666','7777'],
    'ip': ['192.168.1.101', '192.168.1.102','192.168.1.103','192.168.1.104'],

}

df2 = pd.DataFrame(raw_data1, columns = ['employee_id', 'ip'])

I have to search (compare) df2['employee_id'] in df1 and if values are the same, add df2['ip'] to df1 as:
print df2['ip'].where(df2['employee_id']==df1['employee_id'])

But this isn't the right method:
ValueError: Can only compare identically-labeled Series objects

any suggestion for this issue would be appreciated.

A: Use merge
In [1286]: df1.merge(df2, on='employee_id')
Out[1286]:
  employee_id first_name last_name  age             ip
0        4444         aa    Miller   42  192.168.1.101
1        5555      Jason   Millers   42  192.168.1.102
2        6666       Tina       Ali   36  192.168.1.103
3        7777       Jake    Milner   24  192.168.1.104

A: This is an updated answer as someone deleted the post with what I thought was the better solution.
on = "employee_id"
df3 = df1.set_index(on).join(df2.set_index(on)).fillna("IP missing")
df3["ip"].to_dict()

employee_id first_name  last_name   age ip
4444        aa          Miller      42  192.168.1.101
5555        Jason       Millers     42  192.168.1.102
6666        Tina        Ali         36  192.168.1.103
7777        Jake        Milner      24  192.168.1.104
8888        Amy         Cooze       73  IP missing

{'4444': '192.168.1.101',
'5555': '192.168.1.102',
'6666': '192.168.1.103',
'7777': '192.168.1.104',
'8888': 'IP missing'}

Previous answer:
pd.merge(df1,df2,on="employee_id")

https://pandas.pydata.org/pandas-docs/stable/merging.html#database-style-dataframe-joining-merging

pd.merge(left, right, how='inner', on=None, left_on=None,
  right_on=None,
           left_index=False, right_index=False, sort=True,
           suffixes=('_x', '_y'), copy=True, indicator=False)

Gives
    employee_id first_name  last_name   age ip
0   4444    aa      Miller  42  192.168.1.101
1   5555    Jason   Millers 42  192.168.1.102
2   6666    Tina    Ali 36  192.168.1.103
3   7777    Jake    Milner  24  192.168.1.104

And possibly you want something like this:
pd.merge(df1,df2,on="employee_id").set_index("employee_id")["ip"].to_dict()

{'4444': '192.168.1.101',
 '5555': '192.168.1.102',
 '6666': '192.168.1.103',
 '7777': '192.168.1.104'}


text:
Q: Возможно ли осуществить раздачу  интернета с помощью wi-fi адаптера asus n-10 в Xubuntu 12.04? Хочу приобрести wi-fi адаптер асус н-10 вот такой: Wireless-N150 PCI Express Adapter. Если верить описанию на оф.сайте, то под виндой легко реализовать программную точку доступа. Но у меня ПК с убунту на борту, хочу через него раздавать интернет по квартире.Вопрос: реально ли это сделать и как? Рассмотрю все варианты.
A: Первая ссылка в гугле - HowTo: WiFi Access Point средствами Ubuntu.
A: Конечно можно. Это делается утилитами hostapd, dnsmasq и wpa_supplicant. Раньше это делалось с помощью wireless_tools, но он умеет делать только без шифрования.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Cannot run pyLDAvis. Getting Error : ImportError: cannot import name PCoA I have created LDA model using gensim. Now, I wanted to visualise it using pyLDAvis library but getting :
ImportError: cannot import name PCoA

Can anyone help me with this or suggest some alternatives.
Thanks in advance.

A: The name of this function changed from the 0.2.x (alpha) to 0.4.x (beta) branch of scikit-bio. You can either use the function with the old name by installing scikit-bio 0.2.3, or modify your code to use the new function name. I recommend the latter as this interface is stabilizing, so making the change now will allow you to continue to get access to the latest features.
There are two pieces involved in updating your PCoA call for 0.4.1. You'll need to adapt your import and function calls to use the new name (pcoa - all lowercase now, see changelog note on this here), and then change how you interact with the results, as the OrdinationResults object has been improved between these releases. First, your import should now look like:
from skbio.stats.ordination import pcoa

Then, you can review the changelog description of what's changed with the OrdinationResults object here.
If you do just want to stick with 0.2.3, either of the following should work for installation:
pip install scikit-bio==0.2.3
conda install scikit-bio==0.2.3

On a related note, see our API stability docs to see how you can learn about what features are stable/experimental/deprecated in scikit-bio.

A: You must check the scikit-bio python package. It must be < than 0.4.x. From the version 0.4.x, the method has a different name.
You have to install the right version in the following way:

sudo pip install scikit-bio==0.2.X

Cheers


text:
Q: Check if object is instanceof a protected class Say I am using a Java library that has the following method
public static SomeInterface foo();

The interface SomeInterface has multiple implementations, some of which are protected within the library's package. One of these implementation is TheProtectedClass
What would be the best way to check if the object returned by foo() is an instance of TheProtectedClass?
My current plan is to create an Utils class that lives within my project but in the same package as the protected class. This Utils can refer to TheProtectedClass since it is in the same package and thus it can check if an object is instanceof TheProtectedClass.
Any other ideas?
EDIT: Some people are asking "why" so here is more context.
I am using jOOQ and in some part of my code, I want to know if the Field instance that I have is an instance of Lower.
Currently, I use field.getName().equals("lower") but this isn't as robust as I'd like it to be.
I realize that since Lower is a protected class, it isn't part of the API and that it can change but I am ok with that.

A: Class.forName("TheProtectedClass").isAssignableFrom(foo())

although it is a bad idea for many reasons. You're breaking the encapsulation and the abstraction here. If it's package-private, you shouldn't have to concern with it outside. If it's protected, you should explicitly inherit from it and use the API provided by class for this case.
The less obvious but more correct solution is to get an instance of TheProtectedClass, and compare it by
guaranteedTPCInstance.getClass().isAssignableFrom(foo())

, while still being kind of hacky, at least is more portable and OOPy IMO.
As to your idea of creating a class in the same package as TheProtectedClass to avoid being package-private - it's a viable solution, but a) it breaks the basic principle of encapsulation and the programming contract of the TPC class; packaging is done by library/class authors for a reason - to prevent irresponsible data access and using private API or undocumented proprietary methods, b) it's not always possible (and shouldn't be possible in case of properly designed library classes), since those classes can be not only package-private, but final or effectively final (anonymous inner classes etc) - for the reasons described by Bloch in EJ 2nd, "favor composition over inheritance" item, see also Good reasons to prohibit inheritance in Java? Use of final class in Java etc c) you can't do it with some Java library classes, as you can't define your class to be and use e.g. java.lang package. As such, the only "portable" solution is through reflection and through what I described.
tl;dr The fact you can piggyback another package by mimicking its package definition is an obvious C-style deficiency of Java's syntax (allowing programmer to do what he shouldn't be able to normally do; same goes with some specific reflection methods); hacks made this way are neither maintainable nor safe.
NOTE: If you you expect to do something in a internal implementation-dependent and, at the same time, portable and maintainable (e.g. impervious to implementation changes/class name changes etc) way, you're obviously expecting the impossible.

A: It appears that the best solution is to create a package in your project that has the same package as the package-private class and either expose TheProtectedClass.class as a Class<?> or simply add a simple method that checks if your Object is instanceof TheProtectedClass.
This does not require reflection, it is fast and relatively safe (compilation will break if the package-private class changes name).


text:
Q: When I want to import AppCompatActivity it says it cannot resolved? When I want to import appcompatActivity it says it cannot resolved but i have sync my gradle and it had been successful , what is the problem ?
the version is :
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
androidTestCompile('com.android.support.test.espresso:espresso-core:2.0', {
    exclude group: 'com.android.support', module: 'support-annotations'
})
compile 'com.android.support:appcompat-v7:21.0.3'
testCompile 'junit:junit:4.12'
}


text:
Q: NFC Can I send NdefMessage via button pressed? In Android API level 10, NfcAdapter has a method enableForegroundNdefPush(),
and the description is
You must explicitly call this method every time the activity is resumed,
and you must call disableForegroundNdefPush(Activity) before your activity
completes onPause().

So enableForegroundNdefPush() can only be called onResume()?
But I want to send NdefMessage when a button is pressed
How can i do ?


text:
Q: Combine Multiple MySQL Queries on the Same Table Into One How do you make multiple queries on the same table, selecting different columns?
If it helps at all... All of the queries have a common column in the select part of the SQL statement. They all select the ID, then followed by something specific.
So every query needs the ID and either of the following: post_name, post_title, or post_excerpt.
Also if it helps to simplify things. I'm trying to search for broad matches and exact matches in these columns.
So in my example, I will be looking for: "floor finish", "floor", or "finish" in the following columns: post_name, post_title, and post_excerpt. All within the same table.
I've attempted to accomplish this with UNION.
Here are my queries:
Array
(
    [broad] => Array
        (
            [floor] => Array
                (
                    [slugs] => SELECT `ID`, `post_name` FROM tps_3_posts WHERE `post_status` = 'publish' AND `post_name` LIKE '%floor%'
                    [titles] => SELECT `ID`, `post_title` FROM tps_3_posts WHERE `post_status` = 'publish' AND `post_title` LIKE '%floor%'
                    [excerpts] => SELECT `ID`, `post_excerpt` FROM tps_3_posts WHERE `post_status` = 'publish' AND `post_excerpt` LIKE '%floor%'
                )

            [finish] => Array
                (
                    [slugs] => SELECT `ID`, `post_name` FROM tps_3_posts WHERE `post_status` = 'publish' AND `post_name` LIKE '%finish%'
                    [titles] => SELECT `ID`, `post_title` FROM tps_3_posts WHERE `post_status` = 'publish' AND `post_title` LIKE '%finish%'
                    [excerpts] => SELECT `ID`, `post_excerpt` FROM tps_3_posts WHERE `post_status` = 'publish' AND `post_excerpt` LIKE '%finish%'
                )

        )

    [exact] => Array
        (
            [slugs] => SELECT `ID`, `post_name` FROM tps_3_posts WHERE `post_status` = 'publish' AND `post_name` LIKE '%floor-finish%'
            [titles] => SELECT `ID`, `post_title` FROM tps_3_posts WHERE `post_status` = 'publish' AND `post_title` LIKE '%floor finish%'
            [excerpts] => SELECT `ID`, `post_excerpt` FROM tps_3_posts WHERE `post_status` = 'publish' AND `post_excerpt` LIKE '%floor finish%'
        )

    [combined] => ( SELECT `ID`, `post_name` FROM tps_3_posts WHERE `post_status` = 'publish' AND `post_name` LIKE '%floor-finish%' ) UNION ( SELECT `ID`, `post_name` FROM tps_3_posts WHERE `post_status` = 'publish' AND `post_name` LIKE '%floor%' ) UNION ( SELECT `ID`, `post_name` FROM tps_3_posts WHERE `post_status` = 'publish' AND `post_name` LIKE '%finish%' ) UNION ( SELECT `ID`, `post_title` FROM tps_3_posts WHERE `post_status` = 'publish' AND `post_title` LIKE '%floor finish%' ) UNION ( SELECT `ID`, `post_title` FROM tps_3_posts WHERE `post_status` = 'publish' AND `post_title` LIKE '%floor%' ) UNION ( SELECT `ID`, `post_title` FROM tps_3_posts WHERE `post_status` = 'publish' AND `post_title` LIKE '%finish%' ) UNION ( SELECT `ID`, `post_excerpt` FROM tps_3_posts WHERE `post_status` = 'publish' AND `post_excerpt` LIKE '%floor finish%' ) UNION ( SELECT `ID`, `post_excerpt` FROM tps_3_posts WHERE `post_status` = 'publish' AND `post_excerpt` LIKE '%floor%' ) UNION ( SELECT `ID`, `post_excerpt` FROM tps_3_posts WHERE `post_status` = 'publish' AND `post_excerpt` LIKE '%finish%' )
)

However, the above result is interesting. I appear to get all the correct results except the key of each result value (which is supposed to be the name of the column) always remains the same. It's always post_name even though the value assigned to it might be a post_title or post_excerpt.
So every result has an ID and post_name. Basically they keys are wrong but the values appear to be accurate.
I also tried something like this:
Array
        (
            [broad] => Array
                (
                    [floor] => SELECT `ID`, `post_name`, `post_title`, `post_excerpt` FROM tps_3_posts WHERE `post_status` = 'publish' AND ( `post_name` LIKE '%floor%' OR `post_title` LIKE '%floor%' OR `post_excerpt` LIKE '%floor' )
                    [finish] => SELECT `ID`, `post_name`, `post_title`, `post_excerpt` FROM tps_3_posts WHERE `post_status` = 'publish' AND ( `post_name` LIKE '%finish%' OR `post_title` LIKE '%finish%' OR `post_excerpt` LIKE '%finish%' )
                )

            [exact] => SELECT `ID`, `post_name`, `post_title`, `post_excerpt` FROM tps_3_posts WHERE `post_status` = 'publish' AND ( `post_name` LIKE '%floor-finish%' OR `post_title` LIKE '%floor finish%' OR `post_excerpt` LIKE '%floor finish%' )
            [combined] => SELECT `ID`, `post_name`, `post_title`, `post_excerpt` FROM tps_3_posts WHERE `post_status` = 'publish' AND ( `post_name` LIKE '%floor-finish%' OR `post_title` LIKE '%floor finish%' OR `post_excerpt` LIKE '%floor finish%' ) UNION (SELECT `ID`, `post_name`, `post_title`, `post_excerpt` FROM tps_3_posts WHERE `post_status` = 'publish' AND ( `post_name` LIKE '%floor%' OR `post_title` LIKE '%floor%' OR `post_excerpt` LIKE '%floor%' )) UNION (SELECT `ID`, `post_name`, `post_title`, `post_excerpt` FROM tps_3_posts WHERE `post_status` = 'publish' AND ( `post_name` LIKE '%finish%' OR `post_title` LIKE '%finish%' OR `post_excerpt` LIKE '%finish%' ))
        )

)

This is more along the lines of what I'm trying to accomplish. I would like each result to have ID, post_excerpt, post_slug, and post_title. If there's no match, display they key with an empty value, or just completely don't even display the key.
The problem with the second attempt is that it's only requiring a match in one of the three desired columns. So if it matched in the post_excerpt and no where else, it will still pull values from the post_title and post_name. Thus making the results inaccurate.
I've read several what appear to be similar questions however most don't have real solid clear answers... OR ... The questions/answers are more geared to multiple queries on SEPARATE tables.
Any guidance or advice on combining multiple MySQL queries on the same table?
BY THE WAY... I am using the "combined" in both my examples as my final query to send to the database.
So just one more time... If there's no match in a column, display they key as null or just completely omit the key from the results entirely.

A: You're getting the wrong "key" because of the UNION statement in your query.  You have different key names, but compatible column types between the three different columns your unioned queries.  Rather than throw an error, the database engine is just picking the column name from the first query and using that for all of them:
id | post_name # <= column name in first query
1  | "my post"

UNION

id | post_title # <= column name is different, but type is compatible, so UNION succeeds
1  | "my post title"

UNION

id | post_excerpt # <= ditto
1  | "my post excerpt"

would result in:
id | post_name # <= column name from first query
1  | "my post"
1  | "my post title"
1  | "my post excerpt"

which is what you are experiencing.
Instead, you could do something like:
id | post_name | post_title | post_excerpt
1  | "my post" | null       | null        # <= deliberately select nulls for these columns in this query

UNION

id | post_name | post_title      | post_excerpt
1  | null      | "my post title" | null

UNION

id | post_name | post_title | post_excerpt
1  | null      | null       | "my post excerpt"

Which would give you results like:
id | post_name | post_title      | post_excerpt
1  | "my post" | null            | null
1  | null      | "my post title" | null
1  | null      | null            | "my post excerpt"

With your table, a very basic version of this might look like:
SELECT ID, post_name, null AS post_title, null AS post_excerpt FROM tps_3_posts

UNION

SELECT ID, null AS post_name, post_title, null AS post_excerpt FROM tps_3_posts

UNION

SELECT ID, null AS post_name, null AS post_title, post_excerpt FROM tps_3_posts

which might be more usable for what you are trying to do.  Here's a SQLFiddle if you want to see it in action.

A: As I understood in second case the problem is that only matched column should have value and others should be null. For this case you can use IF/ELSE or WHEN statement in SELECT. The idea is you select actual value is value of this column corresponds to expected value and null otherwise.
Another potential solution is you can write e.g.
SELECT `ID`, `post_name`, `post_title`, 'post_excerpt'

So you select string value that were criteria in WHERE statement and can use this value later to understand what this row belongs to.


text:
Q: Index different type of documents using Solr I need to index different type of JSON documents, each JSON document can be in any format, may have nested JSON objects(don't have the control). Once the indexing is done should be able to search. Since we don't have the control on JSON document schema or format decided to go with schemaless option. Got stuck with the following issues:

*

*All the values are getting converted to list because of the configurations  in the updateProcessor 'AddSchemaFieldsUpdateProcessorFactory'.
*
*Ex: String datatype is mapped to text_general, it's set multiValued = true.
*If I define the field in the managed-schema, then it's fine.
*Input: {"firstname":"ASGASGKSAJHAJS"} Output: {"firstname":["ASGASGKSAJHAJS"]}

*All nested documents are converting to flat structure
{"firstname":"ASGASGKSAJHAJS", "address":{"addressLine1":"4216 jshakjfhajh"}}is getting converted to
{"firstname":"ASGASGKSAJHAJS", "address.addressLine1":"4216 jshakjfhajh"}
I'm trying to index blindly any type(ex: JSON format) of document. When I search expecting the response in the format same as the request(at the time of indexing) with minimal Solr config changes. For now, I'm dealing with JSON only, next requirement to index PDF. For my use case, Solr is the right choice or should I look at the other options?
I'm new to Solr, gone through the documentation & articles, don't find any simplest way to overcome the above issues. Any guidance would be appreciated.


text:
Q: How to get a reference to the underlying data type of a Data Template in WPF Here's my situation:
I have a Data Template set up which contains a ToggleButton (its purpose is to represent the underlying type as a button the user can interact with).
My whole usercontrol is a stackpanel that scrolls as new buttons are added to it.  Every time a new button is added, it is hosted by a ContentControl and then added to the stack panel's children.  Something like this:
var newButton = new DataType();
var host = new ContentControl {content = newButton};
stackPanel.Children.Add(host);

Where DataType is the type that the DataTemplate is looking for.
This DataType class has a property which I need access to in the code behind.
When a user clicks on one of these toggle buttons, I want to be able to get a reference to the DataType object that the button represents, and I cannot figure out how to do this.  Is it possible?
Any help would be greatly appreciated.

A: If you're handling a click event of some sort, you probably have a handler like
private void HandleClick(object sender, EventArgs e)
{
  ....

Sender is going to be your control.  You can cast the object to whatever it is, and then access its DataContext, which you can also cast to your "DataType".  If the visual relationship is more compelex, you may need to walk the visual tree more, but you should be able to do this.  With a code-behind approach, this is a common way I've seen to get at things that are in data templates and thus can't be named and manipulated directly.


text:
Q: Devise User Profile link in Navbar I have the following code for the nav-bar in my application, using Devise for user authentication.

            <%= link_to root_path do %>
             Home
            <% end %>

            <%= link_to current_user do %>
             Portfolio
            <% end %>

            <%= link_to help_path do %>
             Help
            <% end %>

            <%= link_to(destroy_user_session_path, :method=>'delete') do %>
             Logout
            <% end %>

It works fine on the home page and the user profile page, but when I go to the other pages, such as the Projects or Help page( both of which have before_filter :authenticate_user! in their controllers ), it throws the following error
     NoMethodError in Projects#index
     undefined method `find_by_remember_token' for #<Class:0x3ec18d0>

It says that the offending code is this part:
    <%= link_to current_user do %>

Which I use to link the user to his/her profile. Any ideas how to fix this error?
Update:
It seems like the problem solved itself after adding
    @user = current_user

to the page's respective controllers.

A: Try to check if user signed in.
<%= link_to if_user_signed_in?, current_user %>


text:
Q: Is there an STL string class that properly handles Unicode? I know all about std::string and std::wstring but they don't seem to fully pay attention to extended character encoding of UTF-8 and UTF-16 (On windows at least).  There is also no support for UTF-32.
So does anyone know of cross-platform drop-in replacement classes that provide full UTF-8, UTF-16 and UTF-32 support?

A: Well in C++0x there  are classes std::u32string and std::u16string. GCC already partially supports them, so you can already use them, but streams support for unicode is not yet done Unicode support in C++0x.

A: It's not STL, but if you want proper Unicode in C++, then you should take a look at ICU.

A: There is no support of UTF-8 on the STL. As an alternative youo can use boost codecvt:
//...
// My encoding type
typedef wchar_t ucs4_t;

std::locale old_locale;
std::locale utf8_locale(old_locale,new utf8_codecvt_facet<ucs4_t>);

// Set a New global locale
std::locale::global(utf8_locale);

// Send the UCS-4 data out, converting to UTF-8
{
    std::wstringstream oss;
    oss.imbue(utf8_locale);
    std::copy(ucs4_data.begin(),ucs4_data.end(),
        std::ostream_iterator<ucs4_t,ucs4_t>(oss));

    std::wcout << oss.str() << std::endl;
}

A: For UTF-8 support, there is the Glib::ustring class. It is modeled after std::string but is utf-8 aware,e.g. when you are scanning the string with an iterator. It also has some restrictions, e.g. the iterator is always const, as replacing a character can change the length of the string and so it can invalidate other iterators.
ustring does not automatically converts other encodings to utf-8, Glib library has various conversion functions  for this. You can validate whether the string is a valid utf-8 though.
And also, ustring and std::string are interchangeable, i.e. ustring has a cast operator to std::string so you can pass a ustring as a parameter where an std::string is expected, and vice versa of course, as ustring can be constructed from std::string.

A: Qt has QString which uses UTF-16 internally, but has methods for converting to or from std::wstring, UTF-8, Latin1 or locale encoding. There is also the QTextCodec class which can convert QStrings to or from basically anything. But using Qt for just strings seems like an overkill to me.

A: And let's not forget the lightweight, very user-friendly, header-only UTF-8 library UTF8-CPP. Not a drop-in replacement, but can easily be used in conjunction with std::string and has no external dependencies.

A: Also look at http://grigory.info/UTF8Strings.About.html it is UTF8 native.


text:
Q: Pandas melt with n columns and order control (counter) I have a dataset in wide format where the x and y ordinates for a line are in separate columns. The example below has only 4 ordinate pairs, but the actual dataset has a few dozen. There is a column with the number of ordinates (n in the example below).
How can I melt this dataframe with so many xn, yn columns? Can I do this without explicitly calling ('x1', 'y1', 'x2', 'y2', 'x3', 'y3', 'x4', 'y4' ... 'xn', 'yn')? I need to track the order, such that the (x1,y1) pair is counter 1; (x2,y2) is counter 2; etc.
idx = [1, 2, 3]
colA = [10, 5, 12]
n = [3, 2, 4]
x1 = [0, 1, 7]
y1 = [4, 0, 4]
x2 = [3, 2, 8]
y2 = [5, 1, 5]
x3 = [4, np.nan, 10]
y3 = [3,np.nan, 3]
x4 = [np.nan, np.nan, 11]
y4 = [np.nan, np.nan, 3]

df = pd.DataFrame(list(zip(idx, colA, n,
                           x1, y1, x2, y2, x3, y3, x4, y4
                          )),
                  columns =['idx', 'colA', 'n',
                            'x1', 'y1', 'x2', 'y2',
                            'x3', 'y3', 'x4', 'y4'
                           ])
display(df)

idx
colA
n
x1
y1
x2
y2
x3
y3
x4
y4

1
10
3
0
4
3
5
4.0
3.0
NaN
NaN

2
5
2
1
0
2
1
NaN
NaN
NaN
NaN

3
12
4
7
4
8
5
10.0
3.0
11.0
3.0

Desired Output

idx
colA
counter
x
y

1
10
1
0
4

1
10
2
3
5

1
10
3
4
3

2
5
1
1
0

2
5
2
2
1

3
12
1
7
4

3
12
2
8
5

3
12
3
10
3

3
12
4
11
3

A: Let us try wide_to_long
out = pd.wide_to_long(df,['x','y'],i=['idx','colA','n'],j='cnt').dropna().reset_index()
Out[8]:
   idx  colA  n  cnt     x    y
0   1    10  3     1   0.0  4.0
1   1    10  3     2   3.0  5.0
2   1    10  3     3   4.0  3.0
3   2     5  2     1   1.0  0.0
4   2     5  2     2   2.0  1.0
5   3    12  4     1   7.0  4.0
6   3    12  4     2   8.0  5.0
7   3    12  4     3  10.0  3.0
8   3    12  4     4  11.0  3.0

A: wide_to_long solves this easily; pivot_longer from pyjanitor is an alternative :
# pip install pyjanitor
import janitor
import pandas as pd
df.pivot_longer(index = ['idx', 'colA', 'n'],
                names_to = (".value", "counter"),
                names_pattern=r"(.)(.)",
                sort_by_appearance = True).dropna()

    idx  colA  n counter     x    y
0     1    10  3       1   0.0  4.0
1     1    10  3       2   3.0  5.0
2     1    10  3       3   4.0  3.0
4     2     5  2       1   1.0  0.0
5     2     5  2       2   2.0  1.0
8     3    12  4       1   7.0  4.0
9     3    12  4       2   8.0  5.0
10    3    12  4       3  10.0  3.0
11    3    12  4       4  11.0  3.0

the .value in names_to signifies that those parts of the column names should be retained, while the rest of the column names is loaded into counter. names_pattern is a regular expression of capture groups that signifies to names_to which parts of the column go to which.


text:
Q: Does TeX/LaTeX give a headstart with other programming languages? I've seen many programmers here at tex.se, and I'd like to know how they view TeX/LaTeX as a programming language in relation to other languages, and whether it would boost my progress as a beginner using other (non-typesetting related) languages, that is of course in an abstract or semantic sense.

A: If you're looking to acquire good programming practices, TeX may not be the best choice, as others have mentioned (the expl3 package aims to correct this, but I don't have personal experience with it). However, if used judiciously, TeX can be a good programming language for learning the foundations of computer science.
The mathematical study of computer programs is couched in the language of Lambda Calculus. TeX lends itself naturally to implementing Combinatory Logic, which is an equivalent formulation of Lambda Calculus. Combinatory Logic's primitives are the operators

*

*I, the identify operator, which operates on the next token, transforming it to itself. I's defining formula is (I x) = x. In TeX
\def\I#1{#1}

*K, the constant-function generator, which operates on the next token, x, transforming it to an operator that always returns x. K's defining formula is (K x y) = x. In TeX,
\def\K#1#2{#1}

*S, the application operator, whose defining formula is (S x y z) = (x z (y z)). In TeX,
\def\S#1#2#3{#1#2{#2#3}}

As such, TeX's closest relatives in the world of computer languages are the family of functional languages, such as Lisp and Haskell, since they are modeled after Lambda Calculus.
However, even in this capacity, TeX is not without its quirks, for instance an empty line will automatically insert a \par token into the input stream (but you can avoid this particular problem by starting your scripts with \endlinechar=-1\relax).

By the way, chapter 5 of the book mentioned in Boris's answer is an introduction to doing Lambda Calculus in TeX.

A: This is more of a long comment rather than an answer.
TeX is an excellent source of learning programming. It tells you how not to write code! One of the basic tenets of programming is that you should write code that is easy to read by others. I find that a lot of TeX code, especially TeX macro code written during the early days of TeX, is impossible to read. Part of the reason is the idiosyncrasies of TeX, the macro language. But a bigger reason is the horrible macro naming convention used by macro authors, especially using @ in the middle of variable names.
As an example, consider the macro \overset and \underset that are part of the amsmath package.  They are defined as
 \newcommand{\overset}[2]{\binrel@{#2}%
  \binrel@@{\mathop{\kern\z@#2}\limits^{#1}}}
\newcommand{\underset}[2]{\binrel@{#2}%
  \binrel@@{\mathop{\kern\z@#2}\limits_{#1}}}

where the helper macros \binrel@ and \binrel@@ are defined in amsbsy.sty:
\def\binrel@#1{\begingroup
  \setboxz@h{\thinmuskip0mu
    \medmuskip\m@ne mu\thickmuskip\@ne mu
    \setbox\tw@\hbox{$#1\m@th$}\kern-\wd\tw@
    ${}#1{}\m@th$}%
  \edef\@tempa{\endgroup\let\noexpand\binrel@@
    \ifdim\wdz@<\z@ \mathbin
    \else\ifdim\wdz@>\z@ \mathrel
    \else \relax\fi\fi}%
  \@tempa
}
\let\binrel@@\relax

The above code would have been much easier to read, if the two macros were named \checkmathbinrel and \usemathbinrel (or something similar). Then, one could read the code to understand the intent of the macros.
Note: I do not mean to criticize the authors who wrote the code. I understand that the code was written at a time when computational efficiency was more important than readability.
Modern TeX code, whether written in LaTeX3 style or in ConTeXt style is much easier to read. For example, this is how the same macros are defined in ConTeXt:
\def\math_binrel_apply#1%
  {\begingroup
   \setbox\scratchbox\hbox
     {\thinmuskip   0mu
      \medmuskip   -1mu
      \thickmuskip -1mu
      \setbox\scratchbox\hbox{$#1\mathsurround\zeropoint$}%
      \kern-\wd\scratchbox
      ${}#1{}\mathsurround\zeropoint$}%
   \ifdim\wd\scratchbox<\zeropoint
     \endgroup
     \expandafter\mathbin
   \else\ifdim\wd\scratchbox>\zeropoint
     \endgroup
     \expandafter\expandafter\expandafter\mathrel
   \else
     \endgroup
     \expandafter\expandafter\expandafter\firstofoneargument
   \fi\fi}

\unexpanded\def\overset#1#2%
  {\math_binrel_apply{#2}{\mathop{\kern\zeropoint#2}\limits\normalsuperscript{#1}}}

\unexpanded\def\underset#1#2%
  {\math_binrel_apply{#2}{\mathop{\kern\zeropoint#2}\limits\normalsubscript  {#1}}}

Notice that proper indenting and expressive variable names make the code much easier1 to understand (perhaps at the cost of efficiency).
So, if you read a lot of TeX code, you will come across the same macro written in different styles. You can compare the two implementations to understand how to write readable code.

1: The \edef\@tempa{\endgroup ...} \@tempa trick, or the {\begingroup ... \engroup \expandafter ... \fi} trick are standard part of TeX programming.)

A: (This is another long comment along the lines of Aditya's answer.)
Yes, it can help you understand other languages (in a theoretical sense).
And for all the reasons that Ryan gives.
In mathematics, we're always on the look-out for the counterexample, the outlier, the slightly-odd-thing-that-still-satisfies-the-definition.  Indeed, we have whole books whose titles are "Counterexamples in X" which are among the "must have" books on people's shelves.  We believe that to truly understand a concept, you have to take it to its extreme and examine what happens there - it's not enough to understand the safe, cosy examples that motivated the concept.  So we learn about the empty set, discrete metric spaces, non-Hausdorff manifolds, non-separable Banach spaces, the field-with-one-element (aka F_un), and many, many similar things.  We do so not because we seriously want to study them, but because if we really want to understand what the statement "S^3 is a smooth manifold" means, we also need to know about the weird examples.
If all you ever want to do is learn one programming language and never be curious as to why it works the way it does, then don't bother looking at TeX.  Regard it as Magic and forget about it.  But if you truly want to understand what programming is about, and learn what it can really do, then you really should look at TeX because there is nothing quite like it.
Where I'd start is by looking at TeX from the point of view of its purpose (I'm extrapolating back here, I've no real knowledge about its beginnings).  It is a programming language embedded into a document typesetting language, and the latter is the dominant part.  So the programming language has to hide itself most of the time, which is one reason why spaces and new lines are more significant than in other languages: they are significant in the document typesetting part.
The other main unique feature of TeX is that most of its users are not programmers, and would never wish to be.  So, again, its design takes that into account.  A writer would expect \emph{hello} to "do what it says on the tin", and \alpha to mean "I want an alpha character right here", so expansion - rather than function calls - is closer to what the average user expects.
(But I'm no expert, and definitely not a programmer.  So maybe my view is tainted by my programmatic development.)

A: The answers so far have been fairly negative, but let me try to offer a little bit of positive spin on this. I have, in the past, tried to teach a variety of people a little bit of HTML. If they already used LaTeX, then they were already familiar with the idea of a markup language. This made things much easier. Then you can just say "Look, <i>…</i> just works like \textit{…} does. (I say LaTeX specifically, because that's what people I've talked to use. I don't know if plain TeX or ConTeXt users are any different…)
And then you can use the idea of using titlesec or a similar package to modify the title font as a way of introducing the separation of form and content that the divide between HTML and CSS is supposed to effect. (Obviously, in both cases the separation is far from complete, but still…)
So while HTML is also a fairly specific language (arguably not a programming language at all) but a familiarity with LaTeX does help in learning it.
What doing this has taught me is that most people who use LaTeX use it very badly: \section*{\it 4. Conclusion} for example. It seems like LaTeX offers so many different ways of intervening, at different levels, to produce the same or similar output. So you don't get the corrective of seeing your "program" fail often enough that you are forced into the right kind of practices. For example, python forces you to indent properly. (I actually hate semantic whitespace, but it does at least instill a good practice when beginning).

A: In 2004 Victor Eijkhout taught a course of Computer Science based on TeX as a programming language.  This year he published the course notes (see http://www.lulu.com/product/paperback/the-computer-science-of-tex-and-latex/18798879).  I recently bought this book and I am going to write a review for TUGboat.  My initial impression from this book is that TeX as a language indeed gives you a valuable insight in many aspects of CompSci and programming.

A: Latex, in my opinion, could be used as a very rich primer for understanding declarative programming. You layout the structure and content of a document declartively and have it rendered to eps or pdf. Even though the language has differences to mobile application frameworks such as as the Android/IOS sdk or web application development using html, css and javascript it presents the coder with the same paradigm of thought used within these contexts.
An appreciation for programming design principles, such as Separation Of Concerns which encourages modular reuse of code blocks is also an advantage of LaTex programming when separating books into chapters, chapters into sections etc.
In short there are many advantages of using this language but again context important. Programming a document layout is not the same as building an application, there are similar concepts employed in both.

A: This is an interesting question.
I agree with Peter's comment - LaTeX is not a good medium for learning about programming in general, but proficiency in other languages will help you understand LaTeX better. A good language for self-study and experimentation is Python.
The bad news is that working with a concise, flexible, powerful language such as Python will make you realize how incredibly verbose, arcane and crippling programming in TeX and LaTeX actually is. It has been said about Perl that it 'makes simple things simple and hard things possible'. About TeX, it would be fair to say that it makes simple things hard, and hard things virtually impossible.
The good news is that there now is LuaTeX, which allows you to implement all the heavy-lifting inside your own macros in Lua, which is similar to Python in spirit and also in syntax. LuaTeX means that, if you decide to study Lua, you will be rewarded with very real and immediate benefits for your work in TeX and LaTeX.

A: My not-oft-enough-expressed opinion is that TeX is a terrible programming language and that anyone learning to program is well advised to avoid learning anything from it.  In fact, it is much more helpful to have experience programming in order to write TeX than the opposite.  Various points major and minor come to mind:

*

*When writing TeX, one has to pay entirely too much attention to the exact characters in the code, up to and including newlines (!) and individual spaces (!!), which both affect its behavior subtly.  This means that lots of effort goes into doing something which isn't even algorithmic.

*Speaking of the input format, because of catcodes, it is entirely fluid.  The example in this answer is extremely interesting, in sort of the same way that an okapi is interesting.  So even if you think you know TeX's syntax, you (probably) only know the syntax of the plain TeX format.  Or of LaTeX.  Or of ConTeXt.

*TeX is a macro language.  That means that by design, its code is self-modifying, which is up there with the goto statement in terms of damage to program structure for the reasons given by Dijkstra in that article.

*However!  TeX is not a macro language, because its directives ultimately expand to typesetting primitives.  This fact is prominently advertised in the TeXbook in describing TeX's modes of operation as the "eyes", the "mouth", and the "stomach"; it's the mouth that's the macro language.  The aforementioned issues with input format are the "eyes"; the typesetting part is the "stomach".  Except, of course, when it is not just the typesetting, for example the execution of \def directives.

*If you read this site, you'll occasionally hear people talking about "fully expandable"; by this they mean code that is processed only in the mouth (as macros).  It is not really known why this distinction exists, but as with many aspects of TeX, it may just be an artifact of its age.  This is not a good advertisement for learning a programming language, all other things being equal.

*TeX doesn't actually have programming constructs like variables or loops or conditionals.  It does have registers and the \loop...\repeat construct (which works by a clever manipulation of self-modifying code) and it does have a fixed number of builtin \if's, but in general you will find yourself writing an ad-hoc, informally specified, and bug-ridden implementation of half of Common Lisp (or, since I don't actually know Lisp, perhaps I should say "of half of C").  Don't think you'll learn anything this way, other than bad habits.  Unless you already know the structures you're trying to invent you will end up with spaghetti code.

*The constructs that do exist are mostly not expandable, despite the fact that the part of TeX that constitutes a programming language is by definition the purely expandable part.  The fact that some of them are expandable leads to very obscure tactics, such as the one described in this question and its answers.  It is probably not reasonable to ask programmers to worry about the code branches of an if statement actually interfering with the branching code itself.

*TeX has no concept of functions, which is one of the few things that imperative and functional languages agree on.  Its macros do absorb "arguments", but because of the tricky expansion issues inherent in the macro language, those arguments are not always what is written in the code.  And even if they are what's written, because of the tricky argument-grabbing issues they are still not always what (you think) is written.

*Strangely, despite the crucial importance of things such as braces to the functioning of TeX, and despite the fact that it is a Turing-complete language, and further despite the fact that the exact format of its input is crucial to its functioning, there is no native way to easily do something like determine (expandably, of course) if the next character is a brace!  See Bruno Le Floch's comment to this answer.  This is actually a good lesson on the difference between "Turing-complete" and "can do anything", so in that sense, is a valuable part of one's programming education.

*It has no debugging facilities to speak of.  It does provide the ability to trace code, but this can't be controlled finely and doesn't always reveal crucial facts like "What values do all those variables have right now?".  Assuming you can tell what the variables are, that is, since they are probably macros just like the "functions".
Essentially, programming in TeX is an endless parade of frustration over minutiae concerning code format, multiple rounds of parsing and subsequent (possibly partial) execution, and poorly defined program state.  Although it's true that "only perl can parse Perl", at least this is true of Perl because of the overwhelming plethora of programming styles and facilities it makes available (including, yes, the ability to modify its own syntax).  In TeX you can have a hard time getting it to do addition.


text:
Q: iPhone Quartz curve jaggy and has dark border I've got a weird issue with quartz. The first time I run the piece of code below, the line will be drawn like the line to the right in the image. The second time (and every time after) these lines are executed, the line will look like the line to the left. Why does it look like that? It's all jaggy and seems to have a dark border. If you'd draw the curve with opacity, it would be rather bright the first time, and very dark the second.
CGContextSetRGBFillColor(context, 0.0,0.0,0.0,0.0);
CGContextClearRect(context, CGRectMake( 0, 0, 320, 480));
CGContextSetRGBFillColor(context, 0, 0, 0, 0);
CGContextSetBlendMode(context, kCGBlendModeNormal);
CGContextSetRGBStrokeColor(context, 1.0, 1.0, 1.0, 1.0);
CGContextSetLineWidth(context, 4.0);

CGContextMoveToPoint(context, p1.x, p1.y);
CGContextAddCurveToPoint(context, cp1.x, cp1.y, cp2.x, cp2.y, p2.x, p2.y);

CGContextDrawPath(context, kCGPathStroke);

(source: pici.se)

A: antialiasing OFF?
also, you might want to make sure the x and y values are rounded as the Quartz Framework doesn't handle well the half point.


text:
Q: Problem getting excanvas to use getContext in IE8 I am trying to implement excanvas in order to ensure canvas tags work in IE8 as well as all the other browsers we use here.  I am having an issue getting getContext to work in IE8.  I have read about the need to us the G_vmlCanvasManager.initElement routine when dynamically creating canvas objects in the DOM, however I cannot even get statically created objects to work in IE8.  I can tell the canvas is create properly because the border appears.  All other browsers have no issues. Here is the code:
<div align="right">
<canvas id="myCanvas" width="200" height="100" style="border:1px solid #c3c3c3;">
Your browser does not support the canvas element.
</canvas>

<script type="text/javascript">

var c=document.getElementById("myCanvas");
if (typeof window.G_vmlCanvasManager!="undefined") {
    c=window.G_vmlCanvasManager.initElement(c);
    var cxt=c.getContext("2d");
   }else
    var cxt=c.getContext("2d");

cxt.fillStyle="#FF0000";
cxt.fillRect(0,0,150,75);

</script>
</div>

Thanks for any help you can give.

A: window.onload or onLoad="drawSomething()" should work, same thing
    <head>
    <!--[if lt IE 9]>
        <script type="text/javascript" src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
        <script type="text/javascript" src="/assets/site/excanvas.min.js"></script>
    <![endif]-->
    </head>

    <figure id="logo" class="body">
        <canvas id="logo-canvas" width="490" height="135"></canvas>
        <script src="canvas.js" type="text/javascript"></script>
        <script type="text/javascript">
        window.onload = function() {
            var c=document.getElementById("logo-canvas");
            var cxt=c.getContext("2d");
            drawLogo( cxt );
        }
        </script>
    </figure><!-- /#logo -->';

A: Found a work around.  Put code in header with an onload trigger and works fine now


text:
Q: PHP REGEX separate by different criteria I'm trying to separate some strings by different criteria but I can't get the desired results.
Here are 3 examples:
$ppl[0] = "Balko, Vlado     \"Panelбk\" (2008) {Byt na tretom (#1.55)}";
$ppl[1] = "'Abd Al-Hamid, Ja'far    A Two Hour Delay (2001)";
$ppl[2] = "'t Hoen, Frans       De reьnie (1963) (TV)";

I'm currently using this for the last 2:
$pattern = '#,|\t|\(#'

But I will get and empty space.
result:
Array ( [0] => 'Abd Al-Hamid [1] => Ja'far [2] => A Two Hour Delay [3] => 2001) )
Array ( [0] => 't Hoen [1] => Frans [2] => [3] => De reünie [4] => 1963) [5] => TV) )

As for the 1st expression I used another pattern but I still get empty spaces. Any ideas?
EDIT:
Thanks this helped indeed. I tried using a modified version on the first string:
$pattern4 = '#[",\t]+|[{}]+|[()]+#';

However I still get an empty space:
Array ( [0] => Balko [1] => Vlado [2] => Panelák [3] => [4] => 2008 [5] => [6] => Byt na tretom [7] => #1.55 [8] => [9] => )

What should I do? I think that the " and the brackets are causing the problem but I don't know how to fix it.

A: I would surmise you have two tabs as separator in your second and third example string. (Can't see that here, the SO editor converts them into spaces).
But you could adapt your regex slightly in that case:
 $pattern = '#,|\t+|\(#'

Or simpler even:
 $pattern = '#[,\t(]+#'

And the alternatve, btw, would be just applying array_filter() on the result arrays to remove the empty entries.


text:
Q: Replace a line in a text file if it matches a pattern I'm trying to loop a specific file and see if any line contains a certain word or text and I want to replace the whole line. I am not sure how I am suppose to do it.
Right now this what I have:
@echo off
setlocal enabledelayedexpansion

FOR /F "usebackq delims=" %%G IN ("C:\folder\myfile.properties") DO (
  Set Line="transaction.sic.lettreEnvironnementBackend"
   IF %%G == %Line% (
      replace that line with new text
   )
)

pause
endlocal

A: @echo off
setlocal enabledelayedexpansion

Set "Line=transaction.sic.lettreEnvironnementBackend"
(
FOR /F "usebackq delims=" %%G IN ("C:\folder\myfile.properties") DO (
   IF "%%G"=="%Line%" (
      echo replacement line
   ) else (echo %%G)
)
)>replacement_filename

pause
endlocal

Note that the replacement filename should not be the source filename. Once tested, move the replacement file to the original filename if required.
Note also that the instruction will exactly match the contents of line - there's no allowance for any other characters on the line.
The syntax SET "var=value" (where value may be empty) is used to ensure that any stray trailing spaces are NOT included in the value assigned.

A: Also easy in PowerShell.
Get-Content .\OutputFile.txt |
    % { if ($_ -eq 'Warning message') { 'NEW WARNING' } else { $_ } }


text:
Q: PHP- How do I search through an HTML document and extract certain strings in php? I have an html document that I saved as a .txt file. I want to extract each string following /user/ and make a comma-separated list of all the extracted strings.
So every time there's a "/user/boy34" in this txt file, I would like to extract the "boy34" part. Im really new to PHP but I've been reading about the preg_match_all() function and I think that's what I need to use.
Here's what I've come up so far but it doesn't work:
<?php
$str = file_get_contents("comment.txt");
preg_match_all ('/^(user\/)\/[A-Z0-9][A-Z0-9_-]+\"$/i', $str, $preg);
print_r ($preg);
?>

The output I get from this is:
Array ( [0] => Array ( ) [1] => Array ( ) )

Can somebody please help me?

A: Using ^ in a regex means that it will only match if the entire line begins with your subject. Also, the $ at the end means the line must also end right after the match. So you will never find anything, unless the entire line is nothing but /user/boy34. Also, you probably need the m flag for multiline mode.
You should also use the shortcuts, like \w (word characters, A-Za-z0-9_)
Try out this regex pattern: /"\/user\/(\w+)"/im
If you post an example of your HTML, I can actually test this out and get you a working regex pattern.
--- UPDATE ---
I tested using this HTML:

and the regex mentioned above, and I got it to work in this very simple test. I used this site to test: http://www.spaweditor.com/scripts/regex/index.php
Here were my results:
Array
(
    [0] => Array
        (
            [0] => "/user/boy30"
            [1] => "/user/boy31"
            [2] => "/user/boy32"
        )

    [1] => Array
        (
            [0] => boy30
            [1] => boy31
            [2] => boy32
        )

)

--- Regex Explanation ---

*

*/ Required to start any regex pattern

*" Looks for a double-quote character

*\/user\/ Searches for /user/ (the forward-slashes needed to be escaped)

*( Anything between parenthesis will be grouped together in your results (leaving the parenthesis out will not break the regex, it will still find the matches, but this allows us to extract "boy32" up front.)

*

*\w+ Searches for 1 or more (+ means "1 or more") word characters (equivalent to [a-zA-Z0-9_])

*) Ends the grouping started before

*" Looks for another double-quote character

*/ Required at the end of any regex pattern, and before any flags

*

*i Flag: Case-Insensitive Mode

*m Flag: Multi-Line Mode (normally, line-breaks will terminate expressions, this allows the pattern to match even over multiple lines)

A: You can use XPath. Check this thread out - Execute a XQuery with PHP. Hope that helps.


text:
Q: How to Fix Header's Problem of Appendix in LaTeX? How to enter the header of appendix in order to it doesn't hit the margin page?
I have this code on LaTeX:
\documentclass[a4paper,12pt,oneside]{book}
\usepackage[left=3cm,right=2cm,top=2cm,bottom=2cm]{geometry}
\usepackage{lipsum}
\usepackage[toc,page]{appendix}
\renewcommand{\appendixtocname}{Lampiran}
\renewcommand{\appendixpagename}{Lampiran}

\begin{document}
    \begin{appendices}
        \chapter{Penurunan dari perkiraan solusi analitik untuk opsi Asia dengan volatilitas stokastik}
        \lipsum
    \end{appendices}
\end{document}

This is the output:

A: In the book and report classes the chapter command can take an optional argument:
\chapter[<toc-header-title>]{<title>}

where the optional toc-header-title is put into the ToC and the page header while title is used as the chapter's title in the body of the document; typically toc-header-title is a shortened version of title. If the optional argument is not used then title is used for all three places. Similarly for the lower level divisions like \section etc.
I don't know the language you are using so I cannot suggest a shortened version of your appendix title that would make sense.
If you need three different versions for the ToC, header and body
the memoir class (a superset of report and book) extends this by providing two optional argumants:
\chapter[<toc-title>][<head-title>]{<title>}

No optional argument title used in all three places
One optional argument toc-title used for the ToC and header
Two optional arguments toc-title used for the ToC and head-title used for the header.
In all cases title is used as the chapter's title in the body of the document.
Similarly for \section and below.


text:
Q: Shift row vector values How can I shift the entries of a vector c like this:
c = [1; 2; 0];
x = [1; 2; 3];

y(1:3) = rightshift(c', 0:2) * x;

% Should produce:
% y(1) = [1; 2; 0]' * x;
% y(2) = [0; 1; 2]' * x;
% y(3) = [0; 0; 1]' * x;

to produce the output vector y?

A: With toeplitz -
N = numel(c);
y = triu(toeplitz(c,0:N-1).')*x

Or with mod & bsxfun -
N = numel(c)
y = triu(c((mod(bsxfun(@minus,[0:N-1]',0:N-1),N)+1).'))*x

Or with just bsxfun -
N = numel(c);
c_ext = [zeros(N-1,1) ; c(:)]
y = c_ext(bsxfun(@plus,[N:-1:1]',[0:N-1]))*x

A: That's essentially a convolution:
y = conv(c(end:-1:1), x);
y = y(end-numel(c)+1:end);


text:
Q: htmlagilitypack c# - input form, wait, and load output generated on server I just have one simple question, before I put hours of work in this and finding out it can't be done:
By HTML-agility pack (selenium and stuff isn't working for me) I want to input some text on this userform:
https://wordsmith.org/anagram/animation.html
then click the button, wait till gif is generated, and then download gif.
Is this possible or should I look for other solution? Sadly enough I'm not allowed to input other browser on my work-computer (the one i'm building the code on) so selenium and stuff isn't working for me.


text:
Q: Designing a mongodb/meteor availability schema I'm trying to build a small site where people can book users for day-long gigs. I am using the accounts package from meteor and my plan is to attach the following:
user.availability: [
                     {
                       status: n, //where n is 0-# of status types (5 atm) : single char rather than float
                       date: ddmmyyy, //string as well, no need for time as its day long
                       job_id: {Job}
                     }, ...
                   ]

Job just has information like where,what,when.
There are 5 states: neutral, available, explicitly unavailable, booked, hold. Users are naturally neutral and explicitly have to state availability. They choose between the first three states: n,a,u and are only allowed to set availability max two weeks into the future. Job "givers" are the ones that set the other two availability states. A neutral state to me means they don't need a record in the db (user.availability array).
This style sets me up for the following query:
db.users.find({ availability: { status: 'a', date: { $in: search_dates_array }});

And when a user logs in/accesses the site, I can wipe any availability settings they have for dates prior to the current date. Inactive users are pruned on a much longer interval.
I see this solution as beneficial in that it stores minimal amounts of information, requires little maintenance that can be triggered by specific events, and is easy to query. But I'm not 100% sure if this is the correct way to leverage mongodb's strengths. I would appreciate any help on this and if someone could point me to a (relatively) easy to digest article on optimizing mongodb schemas, that'd be awesome.
Thank you.

A: I would create a separate collection for the availability. If you use MomentJS for the dates, you can have them stored in human readable form, and they are easily searchable/sortable. Extending the user collection is not always the best idea, especially if your sub-elements are arrays of data that will need to be queried and filtered.
You could use the fullcalendar package for displaying the (day long) events - it will do a lot of the work for you in being able to display month/week/day views as required, and you can colour code the bookings as you like. https://atmospherejs.com/fullcalendar/fullcalendar


text:
Q: Git - maintain multiple versions I have a git repository with a web project. I want to customize this web project for different customers.
For example i have two customers c1 and c2. So i create two git branches: c1 and c2.
Every version has the same base system but different features. If i want to add a new feature or fix a bug in one branch there is no problem. But what if i want to change something that concern both branches. This results in a large amount of merge conflicts.
Can someone show me a better solution for my problem?

A: I like GitHub feature Fork for solving such problems, main idea is to have separate repositories and copying commits using Pull Request or in some other way, with such approach both repositories will have common base and then will evolve as separate repositories.
To use same approach it is not necessary to use GitHub, you can just create several git repositories and then add additional remote, instead of Pull Request you can just use cherry-pick for copy commit from one repository to another. This approach will not help with solving conflicts in some better way.
Also you should think about modular way for development of common parts as separate modules, this can be done with submodules or with some other approach related to your programming language for example in Java you can develop module separately and then use it from other projects using dependency management functionality of Maven, Gradle or Ivy.


text:
Q: kernel expression using numpy I have a laplace kernel which is written as k(x1,x2) = exp(-0.5||x1-x2||)
I write it as
k = np.exp( - 0.5 * np.sqrt ( np.dot (x1,x1) + np.dot (x2,x2) - 2 * np.dot(x1,x2)))

Is this correct?
Also if I the kernel is k(x1,x2) = exp(-0.5 ||x1-x2||^2), I write it as
k = np.exp (-0.5 * (np.dot(x1,x1) + np.dot(x2,x2)- 2 * np.dot(x1,x2)))

Is this correct?

A: You can directly calculate the norm of an array by using :
numpy.linalg.norm(x)
import numpy as np
k = np.exp(-0.5 * np.linalg.norm(x1-x2))


text:
Q: I need to install opencv and use it via java in Maven+IntelliJ (on Windows and macOS/OSX). I need to install opencv and use it via java in Maven+IntelliJ (on Windows and macOS/OSX). What is the "standard" or easy way?

A: I googled extensively and did look at How to use OpenCV with IntelliJ IDEA 12.
Here is what worked for me and it looks simple enough. Please comment if there is a "better" and/or "standard" way. Wish list: I would like to be able to remove opencv easily from my computer if not needed anymore (some of my laptops run out of disk space).
The following is done on macOS Sierra (10.12.1)
Step1: download and install opencv via command-line (i.e. Terminal on macOS/OSX): see http://docs.opencv.org/2.4/doc/tutorials/introduction/linux_install/linux_install.html
UPDATE 17-Nov-2016: http://docs.opencv.org/3.0-beta/doc/tutorials/introduction/linux_install/linux_install.html
$ mkdir ~/dev/lib/opencv/github_opencv_161101
$ cd ~/dev/lib/opencv/github_opencv_161101
$ git clone https://github.com/opencv/opencv.git

I used ~/dev/lib/opencv/github_opencv_161101 as my install directory, so I could remove it easily if needed, and to remind myself when I installed it.
Step 2: build. Note, the last command below $ sudo make install will copy all libs to /usr/local. However, I tried to install opencv via at least two other ways (via brew and http://opencv.org/platforms/android.html), so I am not sure which libraries are which in /usr/local.
$ cd opencv
$ mkdir release
$ cd release
$ cmake -D CMAKE_BUILD_TYPE=RELEASE -D CMAKE_INSTALL_PREFIX=/usr/local ..
$ make
$ sudo make install

Notes on used tools: You also need JavaSDK installed. My cmake is
$ cmake -version
cmake version 3.6.2

If you do not have cmake installed, use brew (or install from http://brew.sh/ )
$ brew install cmake

You may also need to install Command Line Tools not working - OS X El Capitan/ macOS-sierra via
$ xcode-select --install

Step 3: Running HelloCV.java in IntelliJ. Start IntelliJ. Create New Project. Select Maven

Continue until you get

Enable auto-import!
Create new class HelloCV and type (from https://github.com/opencv-java/opencv-java-tutorials/blob/master/docs/source/02-first-java-application-with-opencv.rst):
public class HelloCV {
    public static void main(String[] args){
            System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
            Mat mat = Mat.eye(3, 3, CvType.CV_8UC1);
            System.out.println("mat = " + mat.dump());
    }
}

You should get something like:

Now, finally the payload ;-) Select File->Project Structure:

Select Libraries (or Global libraries), and add java library:

From https://stackoverflow.com/a/24853043/1006226: Navigate to ~/dev/lib/opencv/github_opencv_161101/opencv/release/bin in my case, or ~/path_to_your_dir/opencv/release/bin.

You can now compile and run your HelloCV.java:
import org.opencv.core.Core;
import org.opencv.core.CvType;
import org.opencv.core.Mat;

public class HelloCV {
    public static void main(String[] args){
        System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
        Mat mat = Mat.eye(3, 3, CvType.CV_8UC1);
        System.out.println("mat = " + mat.dump());
    }
}

But you will get the following runtime error:
Exception in thread "main" java.lang.UnsatisfiedLinkError: no opencv_java310 in java.library.path
    at java.lang.ClassLoader.loadLibrary(ClassLoader.java:1864)
    at java.lang.Runtime.loadLibrary0(Runtime.java:870)
    at java.lang.System.loadLibrary(System.java:1122)
    at org.dak.HelloCV.main(HelloCV.java:9)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:497)
    at com.intellij.rt.execution.application.AppMain.main(AppMain.java:144)

Process finished with exit code 1

Go back to Menu->File->Project Structure, select Libraries and add
~/dev/lib/opencv/github_opencv_161101/opencv/release/lib in my case, or ~/path_to_your_dir/opencv/release/lib

Now, you are linked to the native libs via JNI. Run HelloCV and you should get:
mat = [  1,   0,   0;
   0,   1,   0;
   0,   0,   1]

Process finished with exit code 0


text:
Q: Dojo's dojo/method programmatically? Is there a way to define a dojo/method programmatically, in a JavaScript function? (Instead of defining it through script type="dojo/method" within a declarative widget, for example.)

A: Just override it directly on a widget. For example, if you wrote dojo/method for abc, do it like that:
var myWidget = ...;
myWidget.abc = function(/* args from dojo/method */){
  // the body of dojo/method
};

A: Maybe the best option in your case is extend widget prototype, do it like that:
dojo.require("dijit.OneDijit");
dojo.extend(dijit.OneDijit, {
 newMethod:function(/* method args  */){
 // body of method
 }
});


text:
Q: word in list in tokenized sentence I have a list of words / appliances
appliances = ['tv', 'radio', 'oven', 'speaker']

I also have a sentence, which I have tokenized.
sent = ['We have a radio in the Kitchen']
sent1 = word_tokenize[sent]

I want to say that if appliances are in sent1 then print yes else print no. I did the below but keep getting no as the print.
if any(appliances) in sent1:
    print ('yes')
else:
    print ('no')

Is there a better way of doing this?

A: Try something like this.
appliances = ['tv', 'radio', 'oven', 'speaker']
sent = ['We have a radio in the Kitchen']
sent1 = list(sent[0].split())

if any([app in sent1 for app in appliances]):
    print ('yes')
else:
    print ('no')

Edit based on @tobias_k comments
Use lazy evaluation.
if any(app in sent1 for app in appliances):
    print ('yes')
else:
    print ('no')

Edit : based on @ben121 comment
If you want to see with appliance are in your sentence you could do like this.
[app for app in appliances if app in sent1]


text:
Q: How can I execute remote commands in PHP via ssh? I am trying to execute remote commands from within a php script over ssh, and I want the output from the commands (stdout and stderr) be streamed to the originating host.
I know in Perl and Ruby this is possible.  I could not find any such examples in php.
Code:
$ip = 'kssotest.yakabod.net';
$user = 'tester';
$pass = 'kmoon77';

$connection = ssh2_connect($ip);
ssh2_auth_password($connection,$user,$pass);
$shell = ssh2_shell($connection,"bash");

$cmd = "echo '[start]';your commands here;echo '[end]'";
$output = user_exec($shell,$cmd);

fclose($shell);

function user_exec($shell,$cmd) {
  fwrite($shell,$cmd . "\n");
  $output = "";
  $start = false;
  $start_time = time();
  $max_time = 2; //time in seconds
  while(((time()-$start_time) < $max_time)) {
    $line = fgets($shell);
    if(!strstr($line,$cmd)) {
      if(preg_match('/\[start\]/',$line)) {
        $start = true;
      }elseif(preg_match('/\[end\]/',$line)) {
        return $output;
      }elseif($start){
        $output[] = $line;
      }
    }
  }
}

But when I execute it like this $php remote.php, I get an error:
PHP Fatal error:  Call to undefined function ssh2_connect()
in /home/tester/PHP_SSH2/remote.php on line 6

What is the best way to execute remote commands in PHP via ssh?

A: If you can't add php packages due to red tape, here's a simple class that can do the trick
class ExecuteRemote
{
    private static $host;
    private static $username;
    private static $password;
    private static $error;
    private static $output;

    public static function setup($host, $username=NULL, $password=NULL)
    {
        self::$host = $host;
        self::$username = $username;
        self::$password = $password;
    }

    public static function executeScriptSSH($script)
    {
        // Setup connection string
        $connectionString = self::$host;
        $connectionString = (empty(self::$username) ? $connectionString : self::$username.'@'.$connectionString);

        // Execute script
        $cmd = "ssh $connectionString $script 2>&1";
        self::$output['command'] = $cmd;
        exec($cmd, self::$output, self::$error);

        if (self::$error) {
            throw new Exception ("\nError sshing: ".print_r(self::$output, true));
        }

        return self::$output;
    }
}

A: Did you install the SSH2 package?
http://www.php.net/manual/en/ssh2.installation.php

A: Installing the PECL SSH2 package is a PITA.  Try phpseclib, a pure PHP SSH implementation instead.  Take a look at this post to see why the PECL SSH2 extension should be avoided at all costs:
www.frostjedi.com/phpbb/viewtopic.php?f=46&t=13223

A: With authentification managed by SSH keys it's quite simple :
$cmd = 'ssh user@host script ' . $arguments . ' 2>/dev/null';
$result = shell_exec($cmd);

PHP 5.5

A: at least on ubuntu: the following instructions work:
http://kevin.vanzonneveld.net/techblog/article/make_ssh_connections_with_php/ make_ssh_connections_with_php


text:
Q: Distinct with a group by I need to write a query that filter my data.
In my table i have all the data grouped by val1 but multiple values of val2 witch i have to remove.
My table is something like this:
| id | val1 | val2 | other |
|------------------|-------
| 1  | A1   |  b1  | ...
| 2  | A1   |  b1  | ...
| 3  | A1   |  b2  |

| 4  | A2   |  b1  |

| 5  | A3   |  b1  |
| 6  | A3   |  b1  |
| 7  | A3   |  b2  |

| 8  | A4   |  b1  |
| 9  | A4   |  b3  |
| 10 | A5   |  b1  |

And i need this:
| id | val1 | val2 |
|------------------|
| 1  | A1   |  b1  |
| 3  | A1   |  b2  |
| 4  | A2   |  b1  |
| 5  | A3   |  b1  |
| 7  | A3   |  b2  |
| 8   ...
| 9   ...
| 10  ...

it's a sort of select *,distinct(val2) from table group by val1..

A: You are on the right track using a GROUP BY
Following should return the results as per your question
SELECT MIN(id) AS id, val1, val2
FROM   YourTable
GROUP BY
       val1, val2

Breakdown

*

*Use an aggregate function on the column you don't wish to group on. In our example this is the MIN aggregate function on the id column. This returns the lowest id for each group

*GROUP BY all the columns you want to get a distinct value of


text:
Q: Deleting Pushed Data From Firebase - JavaScript Im creating a membership website (web app) for a university project which im jusing firebase for my database. I've come across a challening of deleting data from the firebaase. So to dive right in:
firebase.auth().onAuthStateChanged(function(user) {
if (user) {
// User is signed in.
//Set Variables
var ref = firebase.database().ref().child("users").child(user.uid);

ref.child("rentingAddresses").on("child_added", function(data){
    //Set Local Variables
    var firstLine = data.child("firstLine").val();
    var secondLine = data.child("secondLine").val();
    var thirdLine = data.child("thirdLine").val();
    var town = data.child("town").val();
    var city = data.child("city").val();
    var county = data.child("county").val();
    var postcode = data.child("postcode").val();
    var status = data.child("propertyStatus").val();
    var i;
    var title = '';
    var address = [firstLine, secondLine, thirdLine, town, city, postcode];
    var maxFields = 100;
    //for loop to loop through array
    for(i = 0; i < address.length; i++){
        //if array value is empty move to the next value
        if(address[i] == ''){
            i++;
        }
        else{
            //if at the end of the array
            if(i == address.length - 1){
                title += address[i].toUpperCase();
            }
            else{
                title += address[i].toUpperCase() + ", ";
            }
        }
    }
    //add values of array to (address) to title heading
        var appendAddress = "

" + title + "

<button class='btn btn-primary btn-block' type='submit' id='' onclick='removeProperty()'>Remove Property</button><button class='btn btn-primary btn-block' type='submit' id='' onclick=''>Go To Property</button>

";
        $('#page-content').append(appendAddress);

}, function(error){
    //error message
    console.log("Error: Couldnt Load Address");
});
} else {
// No user is signed in.
}
});

The code above goes though all the data of the child (rentingAddresses) and stores them into the vairable. I then sore the variables into an array and loop though them to remove the empty ('') variables. I then store all the vairable into another and append it with other code to the webpage.
My problem is I cant find a way to delete the data from the database.
What I am trying to do is, provide the user with a button to delete the address. When they click the button it'll delete the address from the database resuting in deleting it from the webpage aswell.
I have tried so many way and just cant seem to find a solution.
firebase Structure:
ref
--users
---userUID
----rentingAddresses
-----pushKey
------firstLine
------secondLine
------thirdLine
------town
------city
------county
------postcode
-----pushKey
and so on

Please can someone help, give me advice of what im may be doing wrong and a solution.
Thanks in advance


text:
Q: Chaos (and logistic functions); what is it and is it truly chaotic? I'm currently studying discrete dynamic models and I am now reading about the logistic function $x_{n+1} = ax_n(1-x_n)$. Below there is a picture what happens with different values of a:
original image

These are for the points $a = (2.25 ; 3,25 ; 3.50 ; 3.56 ; 3.569 ; 3.75)$
The first picture shows as just a normal, stable fixed point. The second one shows a stable period 2 solution. The third one has a non-stable (?) period 2 solution, but a stable period 4 solution. The one after that has a stable period 8 solution, the one after that has a period 16 solution and the one after that doesn't have a period 32 solution, but chaos!
Now I've only heard about chaos from the jurassic park novel, so I don't know what it entails. What does it mean?
If I've understood it correctly; for values below $a<3.75$, you get solutions of a certain period; whether stable or instable. However, with chaos; your solutions don't have a period?
This explanation probably isn't correct, but it gives me a couple of questions;

*

*What does chaos (in this example) mean? Can you globally predict when there is chaos?

*Purely mathematically, without using graphing calculators or pictures like this one; how could you know you have chaos for certain values of a?

*If you have chaos for a certain point $b$, does that mean all points $>b$ will also have chaos?

*Another question; what does stability and instability imply? I know how to find out if a solution is stable or not, but what does it mean? I used to think stable meant it converges; but how can for example a period 2 solution converge/diverge? It makes a rotation, so how can it converge?

A: For a rigorous answer, you will need to consult chaos theory and calculate e.g. the Lyapounov exponent for the system to show that it is chaotic. There are different aspects and definitions to chaos, e.g., ergodicity, strong K-property, average negative curvature, KAM, etc. Intuititively, but not very accurately, a system is defined as chaotic if it moves away from its starting state at an exponential rate in an unpredictable (quasi-random) manner. If trajectories diverge, you get chaos. This may occur even after long lingering in some apparently 'stable' regime. For example, with concave mirror, the rays may first focus towards each other, but after passing through the focal point, they diverge (NB: a regular concave mirror is not chaotic; I am only using it as a rough analogy here. For it to be chaotic, it would need to have a rough surface so that rays are diffusely reflected.)
There is a nice paperback by Gleich(?) on Chaos that explains this topic in fairly accessible manner.

A: "However, with chaos; your solutions don't have a period?" Not at all. First, let me call them trajectories, rather than solutions. One popular definition of chaos insists upon having periodic trajectories, in fact, it insists that every open interval, no matter how small, contains points that have periodic trajectories. It's just that those periodic trajectories are all unstable.
"If you have chaos for a certain point $b$, does that mean all points $\gt b$ will also have chaos?" I take it by $b$, you mean the parameter $a$. The answer is no. For example, there are values of $a\gt3.75$ where there are stable periodic points of period 3. As $a$ increases, chaos and order come and go, in an intensely complex way that is (to the best of my knowledge) not all that well-understood. The are many images on the web of what's called the bifurcation diagram for the logistic map, where you can see these transitions from order to chaos and back again. There are also images of what's called the Lyapunov exponent for the logistic map; there's chaos where it's positive, order where it's negative, and again the images show the complex behavior as $a$ increases.
"I used to think stable meant it converges; but how can for example a period 2 solution converge/diverge?" To say a period $2$ trajectory (also known as a $2$-cycle) is stable is to say that any trajectory that starts near the $2$-cycle will converge to the $2$-cycle; that is to say, the even-numbered terms in the trajectory will converge to one point in the $2$-cycle, the odd-numbered terms to the other. To say a periodic trajectory is unstable is to say that even trajectories that start arbitrarily near it will diverge from it.

A: Let me record a slightly more formal description of the known properties of the logistic family $f_a (x)= a x(1 - x), a \in [0,4]$ on the domain $[-1, 1]$.

Coexistence phenomena for the logistic map family.
Let us call a parameter $a \in [0,4]$ regular if the associated logistic map $f_a(x) = a x (1 - x)$ has the property that the domain $[-1, 1]$ is covered Lebesgue-almost surely by the basins of a periodic sink; we say that $a \in [0,4]$ is stochastic if the logistic map $f_a$ has the following ``chaotic properties'':

*

*$f_a$ possesses an ergodic, absolutely continuous invariant measure $\mu$.

*The Lyapunov exponent $\lambda := \lim_{n \to \infty} \frac1n \log |(f^n)'(x)|$ exists for $\mu$-a.e. $x \in [-1,1]$ and is positive (note: by Birkhoff we have that $\lambda = \lambda(x)$ is $\mu$-a.e. constant).

The following results are known:

*

*(Lyubich and many others): Almost every $a \in [0,4]$ is either stochastic or regular.

*(Jakobson, Benedicks and Carleson; see also Rychlik): The set of stochastic parameters has positive Lebesgue measure in $[0,4]$.

*Exercise for the reader: the set of regular parameters is open and dense in $[0,4]$.

Let me now answer your question:

Purely mathematically, without using graphing calculators or pictures like this one; how could you know you have chaos for certain values of a?

From the results listed above, the set of stochastic parameters for the logistic map is a positive measure set with a complicated Cantor-like structure. In particular, the 'stochastic' property is extremely structurally unstable: any stochastic parameter $a \in [0,4]$ can be approximated by a sequence $\{ a_n \}$ of regular parameters converging to $a$.
So, unless you get lucky (as you do for example when $a = 4$, so that $f_a$ is conjugate to the tent map), for a given parameter $a \in [0,4]$ it is typically impossible to rigorously verify the stochasticity property, even if you simulate $f_a$ on extremely long timescales and it `looks' like it should be stochastic. All we know is that the set of stochastic parameters has positive Lebesgue measure (and a rigorous lower bound on this Lebesgue measure--  look up the work of Luzzatto and others).

Postscript: Avila and Moreira showed that for almost every stochastic $a \in [0,4]$, the map $f_a$ has exponential decay of correlations in addition to a positive Lyapunov exponent and an absolutely continuous invariant measure.

A: The logistic map is one of the more complex systems exhibiting chaos. A simpler system is the iterated Beta Transform (aka the "tent map"). This system separates out more clearly the effects of attractors vs. the effects of ergodic uniformity.  There are many tracts on the Beta Transform, but the one that I like the best is the one that I wrote, here: https://linas.org/math/solvit.pdf The first chapter places the logistic eqn and beta transform side-by-side, making it clear which parts correspond to which; this helps establish a intuitive feeling for "what's really going on" and "why".  There are other, far more mathematical tracts on the Beta transform; I tried to write a much simpler and more approachable treatment.


text:
Q: jquery waypoint plugin does not work properly In my code does not work $(this) in jquery waypoint function,without $(this) everything works
<script>
    $('.team-member').waypoint(function (){
        $(this).addClass('bgr');
    }, {
        offset: '70%'
    });
</script>

сss
.bgr {
  background: red;
}

Any ideas?

A: The flexible way to work Waypont plugin is to do so
var waypoint = new Waypoint({
  element: document.getElementById('waypoint'),
  handler: function(direction) {
    console.log('Scrolled to waypoint!')
  }
})

Also you can try this one
$('.team-member').waypoint(function (){
  var thisE = $(this)[0]['element'];
  $(thisE).addClass('bgr');
  }, {
    offset: '70%'
});

In your case $(this) refers to waypoint object not to specific dom element thats why your code brakes.Console log $(this) and you will see.
$('.team-member').waypoint(function (){
    console.log( $(this) )
}, {
    offset: '70%'
});


text:
Q: Apply expression to synchronize multiple map extents in QGIS 3 layout using PyQGIS I am using the following code to make a map with multiple map items. I would like to add the synchronization of the maps extents.
How do you apply an expression to the min/max extents of a map item on a layout using PyQGIS 3?
selectedLayers = iface.layerTreeView().selectedLayers()

mapCanvas = iface.mapCanvas()
mapThemesCollection = QgsProject.instance().mapThemeCollection()
mapThemes = mapThemesCollection.mapThemes()

mapRowCount = 2
mapColCount = 6

lrMargins = [10,10]   #set Left/Right Margins
tbMargins = [20,30]   #set Top/Bottom Margins

"""Create a new print layout"""
layoutName = "Multi Map {}x{}".format(mapRowCount,mapColCount)

project = QgsProject.instance()
manager = project.layoutManager()
layouts_list = manager.printLayouts()
for layout in layouts_list:
    if layout.name() == layoutName:
        manager.removeLayout(layout)

layout = QgsPrintLayout(project)
layout.initializeDefaults()
layout.setName(layoutName)
pc = layout.pageCollection()
pc.pages()[0].setPageSize('A3', QgsLayoutItemPage.Landscape)
manager.addLayout(layout)

iMapCanvas =0
mapOriginYMm = tbMargins[0]
mapOriginXMm = lrMargins[0]

for iRow in range(1,mapRowCount+1):
    for iCol in  range(1,mapColCount +1):
        #Remember 0,0 is Top Left..... TL to LR
        try:
            layer = selectedLayers[iMapCanvas]
            item_id = "{} - {}".format(iMapCanvas,layer.name())
            title = layer.name()

        except:
            layer=None
            item_id = str(iMapCanvas)
            title = 'Map {}'.format(iMapCanvas)

        map = QgsLayoutItemMap(layout)
        map.setRect(20, 20, 20, 20)

        map.setExtent(mapCanvas.extent())
        map.setBackgroundEnabled(False)
        map.attemptMove(QgsLayoutPoint(mapOriginXMm,mapOriginYMm,QgsUnitTypes.LayoutMillimeters))
        map.attemptResize(QgsLayoutSize(fraWidth,fraHeight,QgsUnitTypes.LayoutMillimeters))
        map.setId('Map {}'.format(item_id))
        layout.addLayoutItem(map)

        if iMapCanvas == 0:
            exp_ymin = QgsExpression("y_min(map_get( item_variables( {} ), 'map_extent'))".format( map.id()))
            exp_ymax = QgsExpression("y_max(map_get( item_variables( {} ), 'map_extent'))".format( map.id()))
            exp_xmin = QgsExpression("x_min(map_get( item_variables(  {} ), 'map_extent'))".format( map.id()))
            exp_xmax = QgsExpression("x_maxn(map_get( item_variables(  {} ), 'map_extent'))".format( map.id()))
        else:
            # How do I apply the expressions to the map item
            pass

        # add Title
        map_title ="Title - Map {}".format(iMapCanvas)

        if layer is not None:
            map_title = layer.name()
            if layer.name() in mapThemes:
                map.setFollowVisibilityPreset(True)
                map.setFollowVisibilityPresetName(layer.name())

        title = QgsLayoutItemLabel(layout)
        title.setText(map_title)
        title.setFont(QFont('Arial', 14,QFont.Bold))
        title.setId("Title - Map {}".format(iMapCanvas))
        title.adjustSizeToText()
        layout.addLayoutItem(title)
        title.attemptMove(QgsLayoutPoint(mapOriginXMm, mapOriginYMm, QgsUnitTypes.LayoutMillimeters))

        mapOriginXMm += fraWidth
        iMapCanvas += 1

    mapOriginYMm += fraHeight     # Add next row
    mapOriginXMm = lrMargins[0]              # reset to left edge of page

# open the layout
iface.openLayoutDesigner(layout)

A: You need to assign a data defined property.
map.dataDefinedProperties().setProperty(QgsLayoutObject.MapXMin, QgsProperty.fromExpression(exp_xmin))
map.dataDefinedProperties().setProperty(QgsLayoutObject.MapYMin, QgsProperty.fromExpression(exp_ymin))
map.dataDefinedProperties().setProperty(QgsLayoutObject.MapXMax, QgsProperty.fromExpression(exp_xmax))
map.dataDefinedProperties().setProperty(QgsLayoutObject.MapYMax, QgsProperty.fromExpression(exp_ymax))


text:
Q: How to set filename property in BlobStore (Java)? It is possible to rename a file stored in Blobstore? but if this is not possible, how could clone a saved file with another filename?
thanks.

A: Blobstore entities are immutable - once created, they cannot be changed.
You would need to create a new entity and copy the data. Since programmatic access to Blobstore has been deprecated, you should save blobs to Cloud Storage and then access them via Blobstore API: when saving data to Cloud Storage, save the key you get and simply use it with Blobstorage APIs.


text:
Q: Calling function in child container from parent in Angular 2

I'm currently working on an Angular 2 app and I'm trying to call a function within a child component but don't appear to be getting anywhere.
My parent component looks like this:
app.component.ts
@Component({
    selector: 'piano-app',
    styleUrls: ['app/components/app/app.component.css'],
    template: `
        <div id="gameWrapper">
            <note-canvas [keyPressed]="pressed"></note-canvas>
            <piano (key-pressed)="keyPressed($event)"></piano>
        </div>
    `,
    directives: [PianoComponent, NoteCanvasComponent],
})
export class AppComponent {

    public pressed: any;

    // This event is successfully called from PianoComponent
    keyPressed(noteData) {
        console.log(noteData); // {key: 30, keyType: "white"}
        this.pressed = noteData;
    }
}

And child component looks like this:
note-canvas.component.ts
export class NoteCanvasComponent implements OnInit {

    ...

    @Input() keyPressed : any;

    constructor(private element: ElementRef, private noteGenerator: NoteFactory) {
        this.canvas = this.element.nativeElement.querySelector('canvas');
        this.context = this.canvas.getContext('2d');
        this.canvasWidth = 900;
        this.noteFactory = noteGenerator;
    }

    public drawImage() {
        // Draw image based on value of keyPressed data;
    }
}

In an ideal world I'd like to call the drawImage function within the <note-canvas></note-canvas> component (which is an HTML canvas that will draw an image to the canvas).
I can pass the pressed property into the component without any issues but can't find any documentation on how to execute a function.

A: In the parent add a field like
@ViewChild(NoteCanvasComponent) noteCanvas: NoteCanvasComponent;

(initialization after ngAfterViewInit).
Then it's easy to call a method on it
keyPressed(noteData) {
    console.log(noteData); // {key: 30, keyType: "white"}
    this.pressed = noteData;
    noteCanvas.drawImage();
}


text:
Q: Workmanager no se ejecuta tras reiniciar el equipo Tengo un Workmanager ya funcionando de manera periódica de forma correcta cada 15 minutos, pero si reinicio el teléfono ya no se vuelve a ejecutar de forma automática.
WorkManager mWorkManager = WorkManager.getInstance();
PeriodicWorkRequest mRequest = new PeriodicWorkRequest.Builder( workmanager.class, 15, TimeUnit.MINUTES).build();
mWorkManager.getInstance().enqueueUniquePeriodicWork("monitor", ExistingPeriodicWorkPolicy.KEEP,mRequest);

A: Cuando reninicias o apagas tu dispositivo, la aplicaciòn se elimina de del administrador de tareas, lo que debes realizar es lo siguiente:
Tu clase workmanager debe extender de la clase Worker :
public class workmanager extends Worker {
   ...
   ...
}

Pero tambièn debes definir dentro de tu AndroidManifest.xml :

Esto provocara que el WorkManager ejecute su servicio nuevamente después de reiniciar el dispositivo.


text:
Q: Generalize and optimize speech bubble logic in Objective-C I am working on a children's book app and would like to dynamically populate speech bubble(s) for character dialogues on every scene. I got the animation and dialogue working and below is the code for that. I would have multiple pages in my book, every page would have multiple characters and every character would have multiple dialogues. What is the best way to make this a generic approach so I can use it repeatedly. Can I store the dialogues in TEXT/XML file and read and display them dynamically based on following parameters: Page number, Character number, dialogue number?
UIImage *bubble = [[UIImage imageNamed:@"BubbleLefthand.png"]
                               resizableImageWithCapInsets:UIEdgeInsetsMake(15, 21, 15, 21)];
            UIImageView *imgView = [[[UIImageView alloc] initWithImage:bubble] autorelease];
            imgView.frame = CGRectMake(250, 350, 0, 0);
            UILabel  *xlabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 0, 0)];
            xlabel.text = @"This is a dialogue text!!!";

            [imgView addSubview:xlabel];
            [self.view addSubview:imgView];
            [UIView animateWithDuration:0.5
                             animations:^(void) {
                                 imgView.frame = CGRectMake(250, 350, 300, -40);
                                 xlabel.frame = CGRectMake(30, 10, 200, 20);
                             } completion:^(BOOL finished) {
                                 STLog(@"ChildrenBookViewController ==> SPPECH BUBBLE ANIMATION COMPLETE. Switch Case: %d", pageNum);
                             }];

Currently my dialogue shows like attach screenshot.

A: As for organizing the dialogs, organizing by page at the highest level seems fine. You can define background image as an attribute of the page.
At one level below page, I think it is better to define "event". Each event correspond to an action from user, or you may even define an event that automatically follows the previous event.
In each event, you can have different types: show dialogue, hide dialogue, control the background music, control sound effect.

*

*For show/hide dialogue event, dialogue id should be defined (the dialogue can be placed directly here or collected in a separate file), plus the direction of the bubble, and possibly the dimensions. Character id may not may not be useful, unless you use it to change the appearance of the text bubble or font.

*For controlling background music, you can have an attribute specifying whether to play or to stop the currently playing music. The background music to play can also be specified as child node.

*For sound effect, you can specify the track you want to play.
This is some ideas I thought up as I think what features the app can have. I can give more idea if you give a bit more details.

Side issue about display: Make sure the png file has transparent outside edges, and set the UIImageView background color to [UIColor clearColor].


text:
Q: ORA-13249: SDO_NN cannot be evaluated without using index I have two tables called my_nodes and restaurants that contain a name and geoloc data. I need to get a table that for each my_node returns nearest restaurant and distance from node to restaurant.
    select n.node_id, r.r_name , sdo_nn_distance(1) as min_distance from
        (select nodeid as node_id, geoloc  from my_nodes@my_server ) n,
        (select r_name, GEOLOC from restaurants) r
        where sdo_nn   (n.geoloc, r.GEOLOC,   'Unit = MILE sdo_num_res = 1', 1) = 'TRUE'

The query above returns:
    ORA-13249: SDO_NN cannot be evaluated without using index
    ORA-06512: at "MDSYS.MD", line 1723
    ORA-06512: at "MDSYS.MDERR", line 17
    ORA-06512: at "MDSYS.PRVT_IDX", line 9

How to fix it?

A: Got same error message, but without DB-Link. http://www.orafaq.com/forum/t/154844/ helped (replace c and s with your table aliases and spatial_index with your spatial index name):
/*+ LEADING(c) USE_NL(c s) INDEX(s spatial_index)*/

A: from my_nodes@my_server n caused the problem. Running the same query on the server with the schema leads to from my_nodes n works. Creating an index is an option but it will kill performance due to calls across nodes.


text:
Q: Proving a system of equations has only one solution I want to find all critic point of $f(x,y)=xe^y-ye^x$. So I calculated $\nabla f(x,y)=(e^y-ye^x, xe^y-e^x)$ and tried to solve $$\begin{cases}e^y-ye^x=0 \\ xe^y-e^x=0 \end{cases}\qquad \Rightarrow \qquad \begin{cases}(1-xy)=0 \\ xe^y=e^x \end{cases}$$
A trivial solution is  {$x=1, y=1$}.
I'm pretty sure this is the sole solution, but I wasn't able to prove that!

My attempt:
$$\begin{cases}(1-xy)=0 \\ xe^y=e^x \end{cases}\qquad \Rightarrow \qquad \begin{cases}y=\frac{1}{x} \\ y=x-\log{x} \end{cases}$$
I studied the difference $\left|x-\log{x} -\frac{1}{x}\right|$ and I suppose to find one and only one global minimum at $x=1$. $$D\left[\left|x-\log{x} -\frac{1}{x}\right|\right] \quad= \quad \operatorname{sgn}\left(x-\log{x} -\frac{1}{x}\right)\cdot \left(1-\frac{1}{x}+\frac{1}{x^2} \right)$$
The derivative has no stationary points, and $(\lim_{x\to0^+}=-\infty),$ $(\lim_{x\to+\infty}=+\infty)$; thus I must search among critical points. But here I got stuck, since the critical points lie where $\left(x-\log{x}-\frac{1}{x} \right)=0.$ So that's a circular definition...

A: Consider the function $g(x)=x - \ln x - \frac{1}{x}$. If we prove that it is strictly increasing for $x > 0$, then, it cannot have more than one zero. But its derivative, namely
$$ g'(x)= \frac{1}{x^2} - \frac{1}{x} + 1 $$
is always $>0$ for $x > 0$, so we have concluded.


text:
Q: Efficient way to check which array rows fall between the values of two other vectors I have a large numpy array of shape (20, 702000), and I need to find which rows have values that fall between two other arrays. In the following simplified example,
a = np.array([[1,3,4,3,2,4],
              [4,6,2,5,8,6],
              [1,4,8,3,1,9],
              [9,4,2,5,6,5]])

range_low = np.array([0,2,3,2,1,3])
range_high = np.array([2,4,5,4,3,5])

a[0] is the only row that would fit the criteria and fall between range_low and range_high for each number.
I have tried something like,
[np.where(np.logical_and(x > range_low, x < range_high)) for x in a]

and it works, but in such a large array looping takes a very long time. Is there a quicker way to do something like this? Thanks!

A: If i understand the question correctly, you want all row indices that fit the critera?
Then i would suggest this:
np.flatnonzero(((a > range_low) & (a < range_high)).all(axis=1))

If you have numpy version 1.20.0 you can also use the where keyword for numpy.all.

A: Quicker:
[np.where(x) for x in np.logical_and(a > range_low, a < range_high)]

Even quicker, but different format output:
np.where(np.logical_and(a > range_low, a < range_high))

Times:
print(timeit.timeit(lambda: [np.where(np.logical_and(x > range_low, x < range_high)) for x in a], number=100000)) # 1.3141384999999999
print(timeit.timeit(lambda: [np.where(x) for x in np.logical_and(a > range_low, a < range_high)], number=100000)) # 1.0557419000000001
print(timeit.timeit(lambda: np.where(np.logical_and(a > range_low, a < range_high)), number=100000)) # 0.4683885000000001