text:
Q: How to solve the alignment problem when an enumerate list over two pages? \begin{enumerate}
    \item Assuming \( \lim_{n \to \infty} \frac{a_{n+1}}{a_n} = a\) , proof \( \lim_{n \to \infty} \sqrt[n]{a_n} = a\).
    \par \emph{Hint:}
      \( \lim_{n \to \infty} a_n = a  \Rightarrow  \lim_{n \to \infty} (a_1 a_2 \cdots a_n)^{1/n} = a\)

    \item Proof \( \lim_{n \to \infty} \frac{1}{n}(1+\frac{1}{2}+\frac{1}{3}+\cdots+\frac{1}{n}) = 0\).
    \par \emph{Hint:}
      \( \lim_{n \to \infty} a_n = a  \Rightarrow  \lim_{n \to \infty} (a_1 + a_2 +\cdots+ a_n) = a\)

    \item Let \(p(n)\) be the number of prime factors of n, proof \( \lim_{n \to \infty} \frac{p(n)}{n} = 0\).
    \par
    \emph{Proof:} \[n = p_1^{s_1} p_2^{s_2} \cdots p_m^{s_m}, \quad m=p(n)\]
    \[m<s_1+s_2+s_3+\cdots+s_m\]

    Since 2 is the smallest prime number,
    \[2^{s_1+s_2+s_3+\cdots+s_m}<n\]
    thus,
    \[ s_1+s_2+s_3+\cdots+s_m<\frac{\ln{n}}{\ln{2}} \]
    \[ \frac{p(n)}{n} < \frac{\ln{n}}{n \ln{2}} \]
    \item
\end{enumerate}

Thank you for solving my problem below!


text:
Q: Is this "either or" the same as "whether or? Without intelligence, either one's own or another's, true life is impossible.Source
either ones own or another's is the same as "whether one's own or another's?

A: In this context, "whether" would have the same effect as "either." In both cases, the message would be that the statement is true if applied to one's own intelligence, and is also true if applied to another's intelligence.
We would not, however, use "whether or" as an answer to a question of options, as we sometimes do with "either or." For example, if asked: "Do you want the yellow one or the blue one," if you do not care which color you get, you could respond "either or." This is not the case with "whether or."

redpajama_set_name: RedPajamaStackExchange


text:
Q: How do create a Select Option(Dropdown List) by passing the Form Inputs as props to a Component in React? I want to create a reusable form component that renders based on inputs passed as props.
The input fields are initialized as an array of objects as follows:
const userInputs = [
{
        id: "email",
        label: "Email",
        type: "text"
},
{
        id: "username",
        label: "Username",
        type: "text"
},
{
        id: "password",
        label: "Password",
        type: "password"
},
]

I then pass the userInputs as a prop to the User Component that will render the Form as follows:
<NewUser inputs={userInputs}/>

Then the Inputs will be mapped in the User Component as follows
const NewUser = ({ inputs }) => {

return (
<form>
 {inputs.map((input) => (

                          {input.label}
                            <input
                                  id={input.id}
                                  type={input.label}
                             />

                          )
             )
}
</form>
)

}

This renders well, however, I want to add a dropdownlist to the array of inputs. I have tried adding it like other inputs but that fails to render.
I assume this should be the implementation, but I think I am way off.
{
        id: "role",
        label: "Roles",
        type: "select",
        options: ["Admin","Basic"]
}

A: I have used seperate component for individual element tags(ex:input, select) as I think it is a best practice.
https://codesandbox.io/s/stackoverflow-6u05e7?file=/src/formInputs/FormExample.js:455-495


text:
Q: Directadmin Apache server finetuning advice I currently have a dedicated server from which I provide shared hosting for some clients of mine.

Server specs

*

*AMD Athlon(tm) 64 X2 Dual Core Processor 4000+

*4GB DDR RAM

*1x Seagate 1000GB

  And I'm running Apache 2.2.24 on a CentOS 6.0 64-Bit OS.

In my Directadmin control panel I've been receiving notices that my load is too high (it goes over 100 sometimes) and since installing htop I've noticed it is mostly apache (httpd) causing the CPU peaks. These surges last a couple of minutes causing the CPU load to reach +90 %. The memory load is consistent with only 25% used.
I've never really optimized or tweaked an Apache server before and therefore I'm in dire need of advice. What settings should I modify in order to prevent/minimize the CPU load?
Thank you in advance!

A: OK, three key points before I actually get to answering your question:
First, "CPU % Busy" is a crap metric. Ignore it.
If this value is less than 100% your server is under-utilized (the CPU is idle doing nothing).
Second, and similarly, "Load Average" isn't a great metric (though it's better than "CPU % Busy").
Load Average <= number of cores in the server is a good rule of thumb, but if the load average is 10000 and the system is performing well what do you care?
Third, DirectAdmin, cPanel, and all of their ilk are terrible. They're like keeping the training wheels on your bike forever: You'll never learn how to ride if you don't take them off.
You will likely not be able to really optimize your system while using DirectAdmin or any other "control panel" - start planning to get rid of it (or if you can't, at least turn off its nuisance alerting and implement proper monitoring software - something that alerts on performance rather than "Oh hey the server looks a little busy").

Bottom line: If your system is performing well enough to meet your needs don't mess with it.
If it isn't performing well (or you want to mess with it anyway) read the documentation that Lothar pointed you to and make sure you understand what each parameter you're changing does.
(The kind of cookbook cargo-cult system administration that "Linux Stuffs" article you linked to is perpetuating with their suggested values is wrongheaded: Most of the advice is  generally good, but you need to go read the Apache Project's documentation for each of those parameters, thoroughly understand what they do, and determine what the right value is for your environment, otherwise you're not really being a sysadmin, you're just pushing buttons.)
You should also refer to this Server Fault question on capacity planning for web sites for some general guidance - Remember: the only way to know how a machine will perform under load is to test it.


text:
Q: Which matrices commute with A symmetric positive-definite? I have a symmetric positive-definite matrix $A\in R_{n\times n}$.
Its eigenvectors $e_i$ are an orthonormal basis of $R_n$.
Are the $n^2$ matrices $[e_i\,e_j^T]$ a basis of $R_{n\times n}$?

I have noticed an interesting property: $[e_i\,e_j^T]$ commute with $A$ iff $\lambda_i=\lambda_j$
If $A$ does not commute with $[e_a\,e_b^T]$ and $[e_c\,e_d^T]$, can it commute with $\left( [e_a\,e_b^T]+[e_c\,e_d^T] \right)$?
Would the matrices $[\bar{e}_i\,\bar{e}_j^T]$ (eigenvectors with the same eigenvalue) generate the space of all matrices that commute with $A$?

A: First, consider the case in which the $e_i$ are the standard basis vectors. Or equivalently, take $A$ to be the matrix of the transformation relative to the basis of eigenvectors $e_1,\dots,e_n$. With that, $A$ must be a diagonal matrix.  Write
$$
A =
\operatorname{diag}(\overbrace{\lambda_1,\cdots,\lambda_1}^{m_1}, \cdots, \overbrace{\lambda_k,\cdots,\lambda_k}^{m_k})
$$
That is,
$$
A = \pmatrix{\lambda_1 I_{m_1} \\ & \ddots \\ && \lambda_k I_{m_k}}
$$
where $I_m$ is the identity matrix of size $m$.  $A$ commutes with all conformally partitioned block-diagonal matrices, that is, all matrices of the form
$$
B = \pmatrix{B_1\\& \ddots \\ && B_k}
$$
where $B_i$ is $m_i \times m_i$.


text:
Q: What's the relationship between vector and list in Lisp? I was told that there are only atom and list as the basic data structure in Lisp, does this mean vector in Lisp is some type of list? Was vector stored as list in the underlying?

A: What you were told was accurate but might not have been the clearest description.
In Common Lisp, at least:
* (type-of #(3 4 5))
(SIMPLE-VECTOR 3)

* (atom #(3 4 5))
T

An atom is defined as anything which is not a CONS cell -- including vectors, class instances, and so on.  So yes, a vector is officially considered an "atom" in Lisp, which is why you were told what you were told.

A: As everywhere else vector is structure for efficient random access, usually wrapper around array with some extras (auto grow). List is best for sequentical access and fast insertion.


text:
Q: Can I use "needs of the hour" when referring to something plural? Can I say "needs of the hour" in place of "need of the hour" when talking about plural subjects? For example:

These changes are needs of the hour.

A: Technically yes, but it is not as idiomatic as "the need of the hour." Prior precedence stems from "men of the hour" becoming accepted usage over the last century and a half for teams accomplishing extraordinary feats under trying circumstances (mainly war).
Supporting material:
Google NGram search for "men of the hour"


text:
Q: ListView values are all shown false (in Android) I have three textview in rowlayout.xml. However when I run my app all the values except rating is shown as false.
rowlayout.xml:
    <?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" >

    <ImageView
        android:id="@+id/icon"
        android:layout_width="44dp"
        android:layout_height="44dp"
        android:layout_marginLeft="4dp"
        android:layout_marginRight="10dp"
        android:layout_marginTop="4dp"
        android:src="@drawable/ic_launcher" >
        </ImageView>

    <TextView
        android:id="@+id/rating"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_marginLeft="4dp"
        android:layout_marginRight="10dp"
        android:layout_marginTop="4dp"
        android:text="@+id/rating" />

    <TextView
        android:id="@+id/distance"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_toLeftOf="@id/rating"
        android:layout_marginLeft="4dp"
        android:layout_marginRight="10dp"
        android:layout_marginTop="4dp"
        android:text="@+id/distance" />

    <TextView
        android:id="@+id/name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_toRightOf="@+id/icon"
        android:text="@+id/name"
        android:textSize="40sp" />

</RelativeLayout>

and the MainActivity.java class:
package com.SahilSiddesh.far4;
import android.app.ListActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

public class MainActivity extends ListActivity {
  public void onCreate(Bundle icicle) {
    super.onCreate(icicle);
    String[] values = new String[] { "Android", "iPhone", "WindowsMobile",
    "Blackberry", "WebOS", "Ubuntu", "Windows7", "Max OS X",
    "Linux", "OS/2" };
    String[] distance = new String[] {"1","2","3","4","5","6","7","8","9","10"};
    String[] rating = new String[] {"2","2.5", "5", "4.6", "0","1","3","4","5","1"};

    // use your custom layout
    ArrayAdapter<String> adapterValues = new ArrayAdapter<String>(this,
    R.layout.rowlayout, R.id.name, values);
    setListAdapter(adapterValues);

    ArrayAdapter<String> adapterDistance = new ArrayAdapter<String>(this,
        R.layout.rowlayout, R.id.distance, distance);
    setListAdapter(adapterDistance);

    ArrayAdapter<String> adapterRating = new ArrayAdapter<String>(this,
            R.layout.rowlayout, R.id.rating, rating);
    setListAdapter(adapterRating);
      }

      @Override
      protected void onListItemClick(ListView l, View v, int position, long id) {
        String item = (String) getListAdapter().getItem(position);
        Toast.makeText(this, item + " selected", Toast.LENGTH_LONG).show();
      }
    }

A: You implementation is totally wrong, You are setting three different adapter on the list view, so the last one will override the previous one.
And for array use Java POJO class.
class Platform{
     String os;
     String distance;
     String rating;
}

Then create a list or array of Platform class, and pass it to your custom adapter.
You have to use a custom list adapter, please go through this link.

A: You are using 3 adapters for a list, which is wrong.
A list should match with only 1 adapter.
The reason why only rating has text is because you have
   setListAdapter(adapterRating);

as the last setListAdapter.
You should build a custom adapter that takes 3 arrays, inflate rowlayout.xml, and set all text manually in your case.
You can also create a new class that has 3 fields, and create an array of that class, and pass that array into a custom adapter instead of 3 arrays.
Custom adapter

A: What you need to do is to create a custom adapter. Using the base adapter is wrong, check this PDF for more information.


text:
Q: Using environment variables to keep track of processes launched by cron My question:
I have an if statement in perl where I attempt to detect via environment variables at the time of launching the perl script whether it was launched via a cron job or via normal execution through the shell.
Is there any way to set an environment variable in the crontab itself that a program launched by cron would be able to access?
Essentially, I want this in the top of my crontab:
COMPANYCRON=1

* * * * * someperl.pl

And in someperl.pl this if statement:
if ( $ENV{'COMPANYCRON'} eq '1' ) {
    $job_creator = "cron";
}

Is there a way to do this? Or a better approach to keeping track of cron jobs?

A: Some cron daemons (e.g. Vixie cron on Debian/Ubuntu) allows the exact same syntax you wrote in your example. On other systems (RHEL etc.), use something like this in your crontab:
* * * * * export COMPANYCRON=1; someperl.pl


text:
Q: numpy.argsort is giving me strange unordered ints instead of sorted floats I have two arrays of the same size and am multiplying one column by another to an output array using
array3=[]
for x in range(0,array1,shape[0]):
    array3.append(array1[x,5]/array2[x,5])
array_stack=np.hstack(array3).tolist()
array_sort=np.argsort(array_stack)

array_stack gives me a list of size 410 of float values between 1
and 2 which is what I want (1.2,1.5, etc.)  array_sort gives me a
list/array? of size (410,) of ints with values like 402, 75,
etc. (nothing like the floats it should be sorting and also not in any
sorted order)
I've tried replacing np.argsort with .sort() and get the same
output issues
Thoughts?

A: np.argsort documentation states that the function

Returns the indices that would sort an array.

Hence what you see  means that the smallest element of array_stack is array_stack[402], the second smallest is array_stack[75] etc.


text:
Q: Сохранять не все поля в UpdateView Целый день бьюсь с решением одной проблемы.
Имеется добавляющая форма:
class AddingForm(ModelForm):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields['fieldB'].required=False

    class Meta:
        model = Items
        fields = ['fieldA', 'fieldB', 'date']
        labels = {'fieldA': 'полеА:',
                'fieldB': 'полеВ:',
                'date': 'дата:'}
        widgets = {
            'fieldA': forms.TextInput(attrs={'class': 'form-control'}),
            'fieldB': forms.TextInput(attrs={'class': 'form-control'}),
            'date': forms.DateInput(format=('%Y-%m-%d'),
                                            attrs={'type': 'date',
                                                    'class':'form-control'}),
        }

И унаследованная от нее редактирующая форма:
class EditingForm(AddingForm):
    set_new_date = forms.BooleanField(label="Новая дата?", required=False)

Как сделать так, чтобы дата, которую введет пользователь в поле 'date' на редактирующей форме сохранялось в БД только если стоит галочка в set_new_date? Если галочка не стоит в set_new_date, не важно какую дату введет пользователь, надо чтобы в БД она осталась неизменной (то есть какой была изначально).
Вот вьюшечка:
class Edit(UpdateView):
    form_class = EditingForm
    template_name = 'edit.html'
    success_url = reverse_lazy('main')

    def form_valid(self, form):
        order = form.save(commit=False)
        ????
        order.save()
        return super().form_valid(form)

Пока что решила проблему следующим образом:
forms.py:
class EditingForm(AddingForm):
    set_new_date = forms.BooleanField(label="Новая дата?", required=False)
    new_date = forms.CharField(label='Введи новую дату', required=False, widget=forms.DateInput(format=('%Y-%m-%d'),
                                                                                attrs={'type': 'date', 'class':'form-control'}))
    class Meta(AddinWordForm.Meta):
        exclude = ('asking_date',)

views.py
class Edit(UpdateView):
    form_class = EditingForm
    template_name = 'edit.html'
    success_url = reverse_lazy('main')

    def form_valid(self, form):
        order = form.save(commit=False)

        if form.cleaned_data['set_new_date']:
            order.date = form.cleaned_data['new_date']

        order.save()
        return super().form_valid(form)

И вроде все ОК полиморфизм, наследование. Но не слишком ли костыльно? Может какой-то более очевидный способ есть типа form[field].save = False или типа этого?
Велик соблазн не использовать никакие классы, а просто в функции представления руками прописать. Но как я поняла, так делать не нужно.
С другой стороны такие большие вьюхи - это же смешение логики отображения и бизнес логики.
Как сделать лучше, не говнокодово. Помогите пожалуйста


text:
Q: node:internal/modules/cjs/loader:936 throw err; ^ Error: Cannot find module 'side-channel'. When I run "npm start" I encountered this error when I run npm start  to view my react app.
> react-scripts start

node:internal/modules/cjs/loader:936
  throw err;
  ^

Error: Cannot find module 'side-channel'
Require stack:
- C:\Users\USER-PC\Documents\Projects\frontend\Info_site\node_modules\qs\lib\stringify.js
- C:\Users\USER-PC\Documents\Projects\frontend\Info_site\node_modules\qs\lib\index.js
- C:\Users\USER-PC\Documents\Projects\frontend\Info_site\node_modules\webpack-dev-server\node_modules\express\lib\middleware\query.js
- C:\Users\USER-PC\Documents\Projects\frontend\Info_site\node_modules\webpack-dev-server\node_modules\express\lib\application.js
- C:\Users\USER-PC\Documents\Projects\frontend\Info_site\node_modules\webpack-dev-server\node_modules\express\lib\express.js
- C:\Users\USER-PC\Documents\Projects\frontend\Info_site\node_modules\webpack-dev-server\node_modules\express\index.js
- C:\Users\USER-PC\Documents\Projects\frontend\Info_site\node_modules\webpack-dev-server\lib\Server.js
- C:\Users\USER-PC\Documents\Projects\frontend\Info_site\node_modules\react-scripts\scripts\start.js
    at Function.Module._resolveFilename (node:internal/modules/cjs/loader:933:15)
    at Function.Module._load (node:internal/modules/cjs/loader:778:27)
    at Module.require (node:internal/modules/cjs/loader:1005:19)
    at require (node:internal/modules/cjs/helpers:102:18)
    at Object.<anonymous> (C:\Users\USER-PC\Documents\Projects\frontend\Info_site\node_modules\qs\lib\stringify.js:3:22)
    at Module._compile (node:internal/modules/cjs/loader:1103:14)
    at Object.Module._extensions..js (node:internal/modules/cjs/loader:1155:10)
    at Module.load (node:internal/modules/cjs/loader:981:32)
    at Function.Module._load (node:internal/modules/cjs/loader:822:12)
    at Module.require (node:internal/modules/cjs/loader:1005:19) {
  code: 'MODULE_NOT_FOUND',
  requireStack: [
    'C:\\Users\\USER-PC\\Documents\\Projects\\frontend\\Info_site\\node_modules\\qs\\lib\\stringify.js',
    'C:\\Users\\USER-PC\\Documents\\Projects\\frontend\\Info_site\\node_modules\\qs\\lib\\index.js',
    'C:\\Users\\USER-PC\\Documents\\Projects\\frontend\\Info_site\\node_modules\\webpack-dev-server\\node_modules\\express\\lib\\middleware\\query.js',
    'C:\\Users\\USER-PC\\Documents\\Projects\\frontend\\Info_site\\node_modules\\webpack-dev-server\\node_modules\\express\\lib\\application.js',
ules\\express\\lib\\application.js',
    'C:\\Users\\USER-PC\\Documents\\Projects\\frontend\\Info_site\\node_modules\\webpack-dev-server\\node_modules\\express\\lib\\express.js',
    'C:\\Users\\USER-PC\\Documents\\Projects\\frontend\\Info_site\\node_modules\\webpack-dev-server\\node_modules\\express\\lib\\express.js',
    'C:\\Users\\USER-PC\\Documents\\Projects\\frontend\\Info_site\\node_modules\\webpack-dev-server\\node_modules\\express\\index.js',
    'C:\\Users\\USER-PC\\Documents\\Projects\\frontend\\Info_site\\node_modules\\webpack-dev-server\\lib\\Server.js',
    'C:\\Users\\USER-PC\\Documents\\Projects\\frontend\\Info_site\\node_modules\\react-scripts\\scripts\\start.js'
  ]
}

And then I tried to install the module with this command:
npm i side-channel

I still got an error:

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\USER-PC\AppData\Local\npm-cache\_logs\2022-10-04T15_30_26_716Z-debug-0.log

What could possibly be the problem? I ran the start command just after installing the dependencies with 'npm install' command.

A: You can try removing node_modules and reinstalling all modules with npm install
To show your modules as of npm 7 for windows:
Global modules: npm ls --link --global

Local modules: npm ls --link

To unistall package run
npm uninstall <module_name>

To install just run
npm install <module_name>

A: It worked now. I had to delete the yarn.lock in my project, after deleting the node_modules file, then I ran the command again: npm install

A: The best solution i have found for this problem is to uninstall and reinstall react.
This will uninstall React
to make sure it's there and show dependencies run
npm ls -g --depth=0

output:
F:\Dev\NodeJS\node22
+-- create-react-app@5.0.1
+-- express@4.14.0

to uninstall run
npm uninstall -g create-react-app

to install run
npm install -g create-react-app


text:
Q: Why will $\lim_{z\to \infty} |e^{z^3}|=0$ only if $\mathrm{Re}(z^3) < 0$? I have come across a question in a textbook "Sketch the region in an Argand diagram where $\lim_{z\to \infty} |e^{z^3}|=0$
The solution in the book begins "This will only be satisfied if $\mathrm{Re}(z^3)$ is negative", without any justification as if it is obvious, but I cannot see why this is the correct condition.
Can anyone explain please? Thank you!

A: If $z=x+iy$ with $x,y\in\mathbb R$, then
$$|\exp(z)| = |\exp(x+iy)|=|\exp(x)\exp(iy)| = \exp(x)\,.$$

A: If we denote $z^3=a+ib$, where $a=Re(z^3), b=Im(z^3)$, then $|e^{a+ib}|=|e^ae^{ib}|=|e^a|$. In our case $|e^{a+ib}|=|e^a|\rightarrow 0$ and $e^a$ is a real exponential, so $|e^a|=e^a\rightarrow 0$ for $|a+ib|\rightarrow\infty$ iff $a\rightarrow -\infty$. So we have the necessary and sufficient condition $Re(z^3)\rightarrow-\infty$.


text:
Q: Get a list of all subsequences I'm looking for an equivalent to the subsequences function in Scala. I cannot find it in scala.collection.Seq, maybe it is defined somewhere else. But where?
I think the problem is well known. As an example, given the sequence "abc", the list of all subsequences is  ["","a","b","ab","c","ac","bc","abc"].
A quick and dirty implementation in Scala would be as follows:
(for {ys <- xs.inits.toList; zs <- ys.tails} yield zs).distinct

But it'd be nice to use something already defined, and more efficient.

A: You could use combinations:
(0 to xs.length).toIterator.flatMap(i => xs.combinations(i))


text:
Q: Shirt Designer tool jquery css I need a help  , i want to make a shirt design tool where users able to select each part of an shirt image and then they will chose different type of febric and the perticular portion of the shirt image will change to that febric.
is it possibile to make with jquery. please help me
reference http://www.shirtsmyway.com/design_myshirt.php

A: Your question is too broad, you need to mention your technology stack, weather you are storing pre-processed images or you want to generate images through image processing.
1)If you are using pre-processed images for all possible design combinations, you can easily do it with JQuery.
2) If you want to generate images on runtime, you would want to do some server side image processing. Here is a good example which uses mix of pre and post processing for this purpose.


text:
Q: Ways to place tiles on an $8\times8$ board.
How many ways are there to place, in an 8x8 board, 6 red tiles where they can't be in the same row or column, and 5 different coloured tiles (not red), which must all be in the same row.

Attempt:
1) Pick 6 rows out of the 8 for the red tiles $\binom 8 6$
2) Pick 6 columns for the red tiles: $\binom 8 6$
3) I have to place the 5 differently coloured tiles, I sepparate in two cases:
i) I place them in rows that have a red tile $\binom 6 1$, I pick the places for the 5 tiles $\binom 7 5$, I permute them $5!$.
ii) I place them in rows that don't have a red tile $\binom 2 1$, I pick the places for the 5 tiles $\binom 8 5$, I permute them $5!$.
Answer: $$\binom 8 6 ^2 \left( 6\cdot \binom 7 5\cdot 5!+2\cdot \binom 8 5\cdot 5! \right)$$
Is this correct?

A: The first part is not correct. Remember that just choosing the columns and rows for the red tiles is not enough.
Here, we choose the first 6 rows and the first 6 columns:
o-------
-o------
--o-----
---o----
----o---
-----o--
--------
--------

Here, we also choose the first 6 rows and the first 6 columns:
-----o--
----o---
---o----
--o-----
-o------
o-------
--------
--------

Clearly, they are different, even though you haven't accounted for them. The rest of your answer, however, should be right.
When tackling these problems, make sure to actually visualize the choices in your head so that you understand how exactly you're counting up the results. There are many different counting approaches to almost every problem, but at the end of the day, anything countable you can list out. Combinatorics at its heart is simply organizing these lists and then using methods to count efficiently.


text:
Q: DynamoDb Batch write update When we do table.batch_writer() , the boto3 API , does it insert or it updates as well?
By Update i mean the partition key, sort key are same , but other attributes are not same.I cannot find this in any documentation.

A: The batch_writer in Boto3 maps to the Batch Writing functionality offered by DynamoDB, as a service. This Batch Writing refers specifically to PutItem and DeleteItem operations and it does not include UpdateItem.
From the docs:

The BatchWriteItem operation puts or deletes multiple items in one or more tables. A single call to BatchWriteItem can write up to 16 MB of data, which can comprise as many as 25 put or delete requests. Individual items to be written can be as large as 400 KB.

Note
BatchWriteItem cannot update items. To update items, use the UpdateItem action.

To be clear, the PutItem operation either inserts a new item or replaces an item, uniquely identified by its key (either partition-only, or composite partition+sort key based on how the table was defined). So in a way, you may think of replacing an item as updating it's non-key attributes but it's more correct to think of that as a replace rather than an update. Contrast this with the UpdateItem API which allows selective manipulation of an item's attributes.
It's worth mentioning that even with Put & Delete item functions, the batch API is more limiting than doing individual PutItem or DeleteItem calls because it doesn't support conditional writes. The BatchWrite API is really only useful for batch loading, or batch deleting of data to save on network overhead with respect to HTTP headers, additional compute resources to generate & verify SigV4 signature, etc.


text:
Q: jq : Get values from children array and display on parent array I try to get theses value :
"VmDisplayName, CreationTimeUTC, EndTimeUTC, Reason, Result, State, TotalSize, BackupServerReference, BackupJobSessionReference" from this json :
{
  "JobSessionUid": "urn:veeam:BackupJobSession:fe8a7b44-5d5d-4767-e5f4-db0dba854c59",
  "CreationTimeUTC": "2017-11-14T21:02:54Z",
  "EndTimeUTC": "2017-11-14T21:03:30Z",
  "State": "Completed",
  "Result": "Success",
  "Reason": "",
  "TotalSize": 599785472,
  "VmUid": "urn:VMware:Vm:11e45620-a0dc-1278-6d13-11a58ce70564.vm-1128",
  "VmDisplayName": "VMName",
  "Name": "VMName@2017-11-14 21:02:54",
  "UID": "urn:veeam:BackupTaskSession:540c9985-52ab-ab01-a453-e0126edf8716",
  "Links": [
    {
      "Rel": "Up",
      "Href": "https://10.255.147.125:9398/api/backupServers/e435adc7-63f9-4115-be34-0a647e8faa1e",
      "Name": "veeam-dcc-02",
      "Type": "BackupServerReference"
    },
    {
      "Rel": "Up",
      "Href": "https://10.255.147.125:9398/api/backupSessions/fe8a7b44-5d5d-4767-e5f4-db0dba854c59",
      "Name": "Backup Name@2017-11-14 21:00:02",
      "Type": "BackupJobSessionReference"
    },
    {
      "Rel": "Alternate",
      "Href": "https://10.255.147.125:9398/api/backupTaskSessions/540c9985-52ab-ab01-a453-e0126edf8716",
      "Name": "VMName@2017-11-14 21:02:54",
      "Type": "BackupTaskSessionReference"
    },
    {
      "Rel": "Related",
      "Href": "https://10.255.147.125:9398/api/vmRestorePoints/6f27c79f-1d5c-4cf9-b5f8-43143447bc00?format=Entity",
      "Name": "VMName@2017-11-14 21:03:03",
      "Type": "VmRestorePoint"
    }
  ],
  "Href": "https://10.255.147.125:9398/api/backupTaskSessions/540c9985-52ab-ab01-a453-e0126edf8716?format=Entity",
  "Type": "BackupTaskSession"
}

The objective is to display all elements in root json with jq, like this :
{
  "JobSessionUid": "urn:veeam:BackupJobSession:fe8a7b44-5d5d-4767-e5f4-db0dba854c59",
  "CreationTimeUTC": "2017-11-14T21:02:54Z",
  "EndTimeUTC": "2017-11-14T21:03:30Z",
  "State": "Completed",
  "Result": "Success",
  "Reason": "",
  "TotalSize": 599785472,
  "VmUid": "urn:VMware:Vm:11e45620-a0dc-1278-6d13-11a58ce70564.vm-1128",
  "VmDisplayName": "VMName",
  "Name": "VMName@2017-11-14 21:02:54",
  "UID": "urn:veeam:BackupTaskSession:540c9985-52ab-ab01-a453-e0126edf8716",
  "BackupServerReference": "veeam-dcc-02",
  "BackupJobSessionReference": "Backup Name@2017-11-14 21:00:02",
}

I try several commands without success :
jq '{VmDisplayName,CreationTimeUTC,EndTimeUTC,Reason,Result,State,TotalSize} as $root | (.Links[] | select((.Type == "BackupServerReference")  or (.Type == "BackupJobSessionReference"))) | . as $ref | $root + $ref'

jq '{VmDisplayName,CreationTimeUTC,EndTimeUTC,Reason,Result,State,TotalSize} as $root | (.Links[] | + {"BackupServerReference": select(.Type == "BackupServerReference")})  | . as $ref | $root + $ref'

Can you help me ?
Best regards,

A: This full query should produce the output you want:
jq '[del(.Links), (.Links[] | { (.Type): .Name })] | add'

Broken down:
del(.Links) All elements except for Links.
(.Links[] | { (.Type): .Name }) Objects from every child in Links containing Type as the key and Name as the Value.
[...] | add Combine all objects in an array and add them together as one single object.
Outputs:
{
  "JobSessionUid": "urn:veeam:BackupJobSession:fe8a7b44-5d5d-4767-e5f4-db0dba854c59",
  "CreationTimeUTC": "2017-11-14T21:02:54Z",
  "EndTimeUTC": "2017-11-14T21:03:30Z",
  "State": "Completed",
  "Result": "Success",
  "Reason": "",
  "TotalSize": 599785472,
  "VmUid": "urn:VMware:Vm:11e45620-a0dc-1278-6d13-11a58ce70564.vm-1128",
  "VmDisplayName": "VMName",
  "Name": "VMName@2017-11-14 21:02:54",
  "UID": "urn:veeam:BackupTaskSession:540c9985-52ab-ab01-a453-e0126edf8716",
  "Href": "https://10.255.147.125:9398/api/backupTaskSessions/540c9985-52ab-ab01-a453-e0126edf8716?format=Entity",
  "Type": "BackupTaskSession",
  "BackupServerReference": "veeam-dcc-02",
  "BackupJobSessionReference": "Backup Name@2017-11-14 21:00:02",
  "BackupTaskSessionReference": "VMName@2017-11-14 21:02:54",
  "VmRestorePoint": "VMName@2017-11-14 21:03:03"
}


text:
Q: How to bind a property of a XAML view to a public variable in the code behind every time the property changes I am trying to take a property from a XAML control, specifically the TranslationX property, and store it in a public variable every time the value is changed.
I have tried using data binding by implementing the INotifyPropertyChanged interface and binding the TranslationX property to the public variable from my interface implementation, but had no luck
Essentially, I am needing the TranslationX property of a control to trigger function calls depending on the total displacement, ex. if the control is dragged to -200 in the X direction, it triggers function "Y". I cannot seem to access this translation value in a way that allows me to check if it is above or below a certain value.
I am very new to C# and Xamarin, so any advice is much appreciated.
EDIT:
Here is my current ViewModel class:
public class ReceiptPageViewModel : INotifyPropertyChanged
{
    double shift = 0;

    public double Shift
    {
        get => shift;
        set
        {
            if (shift == value)
                return;
            else
            {
                shift = value;
                OnPropertyChanged(nameof(Shift));
            }
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;

    void OnPropertyChanged(string name)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
    }
}

And here is my syntax for my Binding:
TranslationX="{Binding Shift}"

A: in your XAML
<SomeElement ... TranslationX="{Binding TransX}" ... />

in your ViewModel
double transX;

public double TransX {
  get { return transX; }
  set {
    transX = value;

    if (transX > somethresholdvalue) {
      ...
    }
  }
}

A: Follow the MVVM pattern.
Create a Base View Model with the INotifyPropertyChanged.
Then your custom view model is going to inherit from that base class.

BaseViewModel
public class BaseViewModel : INotifyPropertyChanged
{

    bool isBusy = false;
    public bool IsBusy
    {
        get { return isBusy; }
        set { SetProperty(ref isBusy, value); }
    }

    string title = string.Empty;
    public string Title
    {
        get { return title; }
        set { SetProperty(ref title, value); }
    }

    protected bool SetProperty<T>(ref T backingStore, T value,
        [CallerMemberName]string propertyName = "",
        Action onChanged = null)
    {
        if (EqualityComparer<T>.Default.Equals(backingStore, value))
            return false;

        backingStore = value;
        onChanged?.Invoke();
        OnPropertyChanged(propertyName);
        return true;
    }

    #region INotifyPropertyChanged
    public event PropertyChangedEventHandler PropertyChanged;
    protected void OnPropertyChanged([CallerMemberName] string propertyName = "")
    {
        var changed = PropertyChanged;
        if (changed == null)
            return;

        changed.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
    #endregion

Your custom class:
ReceiptPageViewModel
public class ReceiptPageViewModel : BaseViewModel
{
    double shift = 0;
    public double Shift
    {
        get { return shift; }
        set { SetProperty(ref shift, value); }
    }
}

And in your Xamarin Page set the BindingContext to the ViewModel
(This is an example)
public partial class Page1 : ContentPage
{
    private ReceiptPageViewModel viewModel;
    public Page1()
    {
        BindingContext = viewModel = new ReceiptPageViewModel();
        InitializeComponent();
    }
}

Now you can set the property in the XAML view:
<SomeElement ... TranslationX="{Binding Shift}" ... />

Here you can view a full episode about MVVM Pattern with @JamesMontemagno as host.


text:
Q: Python: simple divisibility test I am trying to write a simple code that prompts users to enter two numbers to determine whether they are evenly divisible:
print 'Enter the following'
num1 = input("Integer:")
num2 = input("Integer:")
evaluation = ((num1 / num 2) / 2)
print num1, "/2", num2, "/2" = ",evaluation

I am new to Python and am seeking advice on how to tweak this code. Any help would be greatly appreciated. Thank you for your time!

A: You need the modulo operator
print "Enter the following"
num1 = input("Integer:")
num2 = input("Integer:")
evaluation = num1 % num2
if evaluation == 0:
    print num1, "/", num2, " evenly divides"
else:
   print num1, "/", num2, " does not evenly divide"


text:
Q: composer install magento2.3.5-p1 I try to install magento2.3.5-p1 by use composer, when it is finished the folder structure looks like:  Anyone knows why it is like that?

A: I have used this command composer create-project --repository-url=https://repo.magento.com/ magento/project-community-edition and it is working properly . From the screenshot I can come to conclusion is that your download was not completed or might have interrupted.


text:
Q: Drag and Drop in rails 3 I am working on the drag and drop feature. I had a working code for that feature. Its written in rails 2.3.5. When I am shifted to rails 3, I used the same code. Actually drag and drop is working, but the position automatically changes in rails 3. In 2.3.5, position will not change.
<% for item in section_menu_items do %>
    <li id='<%= item[:id] %>' class='sec_drag'><%= image_tag(item[:icon], :align => 'absmiddle', :style => 'margin-right: 5px;') %><%= item[:text] %>

    <%= draggable_element "#{item[:id]}", :scroll => 'window', :revert => true, :ghosting => true, :onEnd => "function(){ $('add_here_marker').hide();}" %>
    <% end %>

This is the sample code. The class "sec_drag" contains the position:relative. When I am dragging the element, the position is automatically changed to absolute.
Is the syntax changed for rails 3. Whats the solution for this?


text:
Q: Changing window size from restore down to maximize causes some content appear over another I am using win32 api.When i restore down the window , i decrease width and height of list views but when i maximize it to its previous state , some of previously decreased-size window appears over the current list view.After i minimize the window , it unappears.

 InitCommonControls();
 hwndList1 = CreateWindow(WC_LISTVIEW , L"" ,  WS_VISIBLE | WS_CHILD | LVS_REPORT | WS_BORDER  | WS_VSCROLL, middle-(18+width) , middleH-(18+height) , width , height, hwnd, NULL, GetModuleHandle(NULL), 0);
 hwndList2 = CreateWindow(WC_LISTVIEW , L"" , WS_VISIBLE | WS_CHILD | LVS_REPORT | WS_BORDER  | WS_VSCROLL , middle+18 , middleH-(18+height) , width , height, hwnd, NULL, GetModuleHandle(NULL), 0);
 hwndList3 = CreateWindow(WC_LISTVIEW , L"" , WS_VISIBLE | WS_CHILD | LVS_REPORT | WS_BORDER  | WS_VSCROLL , middle-(18+width) ,middleH+18 , width , height, hwnd, NULL, GetModuleHandle(NULL), 0);
 hwndList4 = CreateWindow(WC_LISTVIEW , L"" ,  WS_VISIBLE | WS_CHILD | LVS_REPORT | WS_BORDER  | WS_VSCROLL , middle+18 , middleH+18 , width , height, hwnd, NULL, GetModuleHandle(NULL), 0);

This is WndProc:
LRESULT CALLBACK WndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
    switch (msg) {
        case WM_SIZE:
            if (wParam == SIZE_RESTORED) {
                SetWindowPos(hwndList1, 0, 30, 40, 200, 120, 0);
                SetWindowPos(hwndList2, 0, 255, 40, 200, 120, 0);
                SetWindowPos(hwndList3, 0, 30, 190, 200, 120, 0);
                SetWindowPos(hwndList4, 0, 255, 190, 200, 120, 0);
            }
            else if (wParam == SIZE_MAXIMIZED) {
                SetWindowPos(hwndList1, 0, middle - (18 + width), middleH - (18 + height), width, height, 0);
                SetWindowPos(hwndList2, 0, middle + 18 middleH - (18 + height), width, height, 0);
                SetWindowPos(hwndList3, 0, middle - (18 + width), middleH + 18, width, height, 0);
                SetWindowPos(hwndList4, 0, middle + 18, middleH + 18, width, height, 0);
            }
             break;
        case WM_NOTIFY:
            if (((LPNMHDR)lParam)->code == NM_CUSTOMDRAW) {
                LPNMLVCUSTOMDRAW  lplvcd = (LPNMLVCUSTOMDRAW)lParam;
                switch (lplvcd->nmcd.dwDrawStage) {
                    case CDDS_PREPAINT:
                        return CDRF_NOTIFYITEMDRAW;

                    case CDDS_ITEMPREPAINT:
                        if (((int)lplvcd->nmcd.dwItemSpec % 2) == 0) {
                            lplvcd->clrText = RGB(0, 0, 0);
                            lplvcd->clrTextBk = RGB(193, 228, 255);
                        }
                        else {
                            lplvcd->clrText = RGB(0, 0, 0);
                            lplvcd->clrTextBk = RGB(255, 255, 255);
                        }
                        return CDRF_NEWFONT;
                }
            }
            return TRUE;

        case WM_COMMAND:
            switch (LOWORD(wParam)) {
                case ID_FILE_EXIT:
                    PostMessage(hwnd, WM_CLOSE, 0, 0);
                    break;
                case ID_STUFF_GO:
                    break;
                case ID_ABOUT: {
                    int ret = DialogBox(GetModuleHandle(NULL), MAKEINTRESOURCE(ID_ABOUT), hwnd, AboutDlgProc);
                }
                    break;
            }
            break;
        case WM_CLOSE:
            DestroyWindow(hwnd);
            break;
        case WM_DESTROY:
            PostQuitMessage(0);
            break;
        default:
            return DefWindowProc(hwnd, msg, wParam, lParam);
    }
    return 0;
}

How can i fix it?
Where is the problem?
Thanks


text:
Q: Call to a member function query() on a non-object in profile.php on line 82 Working on echoing the users questions out so far I can insert the values and   this is working thru the php admin but its not working thru , the form on    the users profile page?
The error says ,"Call to a member function query() on a non-object in profile.php on line 82" The php code on this line is as follows
   $query1=$db->query("SELECT id,title,question,username FROM  QnA WHERE username='$dbusername'");

The rest of profile.php is below
   <?php
     session_start();
     $dusername=$_GET['username'];
    if (isset($dusername)){
        require('connect.php');

        $userquery =$db->query("SELECT id,firstname,username,lastname,email FROM users WHERE username = '".$dusername."'");
                while ($row =$userquery->fetch()){
                        $id=$row["id"];
                        $dbusername =$row["username"];
                        $dfirstname = $row["firstname"];
                        $demail =$row["email"];
                        $dlastname =$row["lastname"];

                        }

    }

 ?>

   <title><?php  echo $dfirstname;?></title>
    <link rel="stylesheet" href="stylesheets/profile.css" type="text/css">

<?php
echo'

  <form action="ask.php" method="post">
   Title

   <input type ="text" name="title"/>

   Question

   <textarea name="question"></textarea>

   This is to make sure your not a robot  2+2=
   <input type="text" name="plus"/>

   <input type="submit" value="Submit"name="submit"/>
   </form>

    ';
?>

 <?php

   $query1=$db->query("SELECT id,title,question,username FROM  QnA WHERE username='$dbusername'");
  //$query2=$db->query("SELECT * FROM answers");

   while($asked=$query1->fetch()){
    if($asked['username']==$dbusername){
     echo '
Title
 ',$asked['title'],'

Question
',$asked['question'],'

';

   }
     else if(!$asked['username']==$dbusername){
          error_reporting(E_ALL);
    echo 'No questions have been asked';
        }

 }
     ?>

The form is in the profile.php the action for the form is in a separate file named ask.php which is below.
   <?php

   //form action below
   require('profile.php');
   session_start();
   require('connect.php');
   $plus=$_POST['plus'];
   $title=$_POST['title'];
   $question=$_POST['question'];
   $dusername=$_SESSION['username'];
         if(isset($_POST['submit'])){
          if(!empty($_POST['title']) && !empty($_POST['question'])&& $plus==4){
              $query="INSERT INTO `QnA` (id,title,question,username) VALUES (?,?,?,?)";
              $query=$db->prepare($query);
              $query->execute(array(' ',$title,$question,$dusername));
                echo'succes';
                header("Location: profile.php");
            }
         else{
             error_reporting(E_ALL);
             echo " Fill in all Slots or you gave the wrong answer to the security question";
            }
         }

?>

A: The below code is not returning True at all :
if(isset($_POST['username'])){

that's why it is going in else statement.
You are using isset function for username field, but you should check for Submit button. Try replacing following lines :
<input type="submit" value="Log In" />

to
<input type="submit" value="Log In" name="submitbtn" />

AND
if(isset($_POST['username'])){

to
if(isset($_POST['submitbtn'])){

It should work then :)

A: You have error in you query add space between ANDpassword=', maybe this should work
$query="SELECT  * FROM  users WHERE username='".$username."' AND password='".$password."' LIMIT 1" ;

to debug you error try
$res =  mysql_query($query) or die(mysql_error());

Take note this query is vulnerable in SQL Injection, maybe you should try using mysqli or PDO for security purposes.
How can I prevent SQL injection in PHP?

A: Try this :
<form action="login.php" method="post" >

   Username: 	<input type="text" name="username" />

    Password: 	<input type="password" name="password" id ="password"/>

   <input type="submit" value="Log In" />
   <input type="button" value="Register" onClick="location.href='register.php'" />
</form>

<?php

require('connect.php');
session_start();
 if ($_SESSION['username'])
{
header("Location: home.php");
 }
else{
if(isset($_POST['username'])){
 require('connect.php');

 //According to user's input

  $username=$_POST['username'];
  $password=$_POST['password'];
  $query="SELECT  * FROM  users WHERE username='".$username."'AND password='".$password."'";

 $res =  mysql_query($query);

 //check username and password for match
 if (mysql_num_rows($res) > 0){

 //Sets username to the comment session so no username has to be input

$_SESSION['username']=$username;

// jumps to secure page

 header ("Location: home.php");

}

A: As above mentioned you are getting 0 rows values, there may be space or some thing else in you query so do below.
echo this query
SELECT  * FROM  users WHERE username='".$username."' AND password='".$password."'

and execute this query manually in database and see what is happening with this query. And correct your query accordingly.


text:
Q: How to execute a python file (.py) on hadoop distributed file system (hdfs) Hadoop offers the possibility to run java applications directly on the cluster using
hadoop jar <jar>

Now I have a python script instead of a java application.
Below is the construct of the .py file without the all the functionality, just left the "remove-files-from-folder" part
import os.path

def transform():
    inputfolder = "input"
    for filename in os.listdir(inputfolder):
        path = inputfolder + "\\" + filename
        os.remove(path)
def main():
    transform()
if __name__ == "__main__":  main()

Is there a way to execute the .py file similarly to the way I'd execute a .jar file?
I'm new to Python and Hadoop. If my approach seems totally off and doesn't make sense, I'm happy for any kind of clarification!

A: If you are simply looking to distribute your python script across the cluster then you want to use Hadoop Streaming.
The basic syntax of the command looks like (from https://hadoop.apache.org/docs/r1.2.1/streaming.html):
$HADOOP_HOME/bin/hadoop  jar $HADOOP_HOME/hadoop-streaming.jar \
-input myInputDirs \
-output myOutputDir \
-mapper myPythonScript.py \
-file myPythonScript.py

This basically creates a map-reduce job for your python script


text:
Q: Redirect site specific domain to a new extension My htaccess controls multiple domains (it's a custom CMS). I need to redirect all requests to my domain "mydomian.com.br" to "mydomain.org.br" This includes calls to sites such as "mydomain.com.br/contact".
I tried this but it just redirects everything to the homepage:
RewriteCond %{HTTP_HOST} ^(www\.)?mydomain\.com\.br$ [NC]
RewriteRule ^(.*)$ http://www.mydomain.org.br/$1 [R=301,L]

A: Try this:
RewriteEngine on
RedirectMatch permanent ^(.*)$ http://mydomain.org.br$1


text:
Q: Read each line of a .txt file into an array in bash/shell/unix in Mac OS X without readarray or mapfile commands I am working on a simple catalog program for my personal library in bash/shell. I am developing in OS X and am stuck on how I am supposed to configure my program without access to UNIX commands such as readarray or mapfile.
Here is the logic of what I am trying to do:

*

*init my program by reading a series of config files that contain the various attributes books that have been cataloged during a previous session. I want the information of each .txt file (one entry per line, per book) read and indexed into an array  (ex. titles.txt -> TITLES=(), authors.txt -> AUTHORS=(), ect...)

*Once the arrays have been filled with the cataloged info, I want to input the attributes of a new book into the catalog by appending the new information to each respective array. This new content would be pushed into the arrays after a confirmation prompt such as "are you sure this information is correct, if yes it will be saved to catlog, if no it will be discarded"

*after the new book attributes have been successfully added to the respective arrays, I want to update/save the updated arrays into to the same .txt config files i used to init the program, appending the newest information to the bottom of each file

Here is what I wanted to do with mapfile
init_catalog(){
    #read catalog entries into arrays
    printf "%s\n" "Loading catalog..."
    mapfile -t TITLES < titles.txt
    mapfile -t AUTHORS < authors.txt
    mapfile -t EDITORS < editors.txt
    mapfile -t PUB_NAMES < pub-names.txt
    mapfile -t PUB_LOCATIONS < pub-locations.txt
    mapfile -t PUB_DATES < pub-dates.txt
    mapfile -t PAGE_COUNTS < page-counts.txt
    mapfile -t GENRES < genres.txt
    mapfile -t ISBN_NUMS < isbn-nums.txt
    printf "%s\n" "Catalog loaded..."
    INITIALIZED="true"
}

save_catalog_entry(){
    clear
    printf "%s\n\n" "You have entered the following information for this work:"
    printf "%s\n" "PENDING ENTRIES FOR THIS WORK..."
    underline_above_text
    printf "Title: $WORK_TITLE\n"
    printf "Author(s): $WORK_AUTHOR\n"
    printf "Editor(s): $WORK_EDITOR\n"
    printf "Publisher: $WORK_PUB_NAME\n"
    printf "Publication Location: $WORK_PUB_LOCATION\n"
    printf "Publication Date: $WORK_PUB_DATE\n"
    printf "Page Count: $WORK_PAGE_COUNT\n"
    printf "Genre: $WORK_GENRE\n\n"
    underline_above_text
    printf "%s\n" "Is this information correct? If yes, all pending entries for this work will be saved to catalog. If no, all pending entries for this work will be discarded."
    yes_or_no
    if [ $USER_INPUT_YES_NO == "true" ]
    then
        #save input to catalog files
        printf "%s\n" "${TITLES[@]}" > titles.txt
        printf "%s\n" "${AUTHORS[@]}" > authors.txt
        printf "%s\n" "${EDITORS[@]}" > editors.txt
        printf "%s\n" "${PUB_NAMES[@]}" > pub-names.txt
        printf "%s\n" "${PUB_LOCATIONS[@]}" > pub-locations.txt
        printf "%s\n" "${PUB_DATES[@]}" > pub-dates.txt
        printf "%s\n" "${PAGE_COUNTS[@]}" > page-counts.txt
        printf "%s\n" "${GENRES[@]}" > genres.txt
        printf "%s\n" "${ISBN_NUMS[@]}" > isbn-nums.txt
    else
        DISCARDING_ENTRIES="true"
        printf "%s\n" "All input information for this work has been discarded. Please, try again."
    fi
}

Does anyone know which UNIX commands I should/can use to access these config files from the shell, read their contents into arrays, and then save the new content of the arrays back into the .txt config files? Thanks for the help!

A: You can use the normal array construction methods (arr[n]="asdas" and arr=( "123" 45 "ss gg" )). Consider this titles.txt file:
once upon a time
pink "cherry" troubles
obfuscator 2

Just read it into a variable by either using bash's f=$(<filename) construct (older than mapfile, so you should have it) or other tools like cat. Then you can iterate over it in a while read loop and save the lines to an array. If you don't need the variable, you can also just read the file in the loop (...; done < filename). Saving back would be done in a similar manner, just looping over the array instead and either using >> to append individually or redirecting the whole loop, where you can use a normal empty-and-fill >.
Approach 2
To skip the explicit loop, read the file to an array by splitting it into whitespace separated pieces first:
oifs=$IFS # save a copy of the input field separator character list
IFS=$'\n' arr=( $(< titles.txt) )
IFS=$oifs # restore
$ echo "${arr[@]}"
once upon a time pink "cherry" troubles obfuscator 2
$ echo "${arr[1]}"
pink "cherry" troubles

Or if you want to also mark the titles' boundaries more obviously, you can quote them:
oifs=$IFS
IFS=$'\n' arr=( $(sed -n 's,",\\",g; s,^.*$,"&",p' titles.txt) )
IFS=$oifs
$ echo "${arr[@]}"
"once upon a time" "pink \"cherry\" troubles" "obfuscator 2"
$ echo "${arr[1]}"
"pink \"cherry\" troubles"


text:
Q: Almacenar array en base de datos MySQL y PHP Tengo una tabla de base de datos donde entre otras cosas necesito almacenar un dato para cada día del mes (que refleja los ingresos obtenidos ese día).
Todas las cantidades de todos los días del mes (31 días que son reiniciados al final del mes) necesito almacenarlas en una sola columna, y he pensado que la mejor forma de hacerlo es almacenando un Array que luego pueda devolver y usar sin ningún problema.
Mi pregunta es, ¿cómo puedo almacenar un Array de PHP en una base de datos? y ¿Qué hago para recuperarlo desde la base de datos de nuevo como otro Array de PHP?
La pregunta excluye cómo hacer el INSERT y el SELECT, tan solo necesito saber cómo transformar y recuperar el array.

A: Puedes insertar los datos dentro de una columna normal, del tipo VARCHAR será suficiente si es una lista de números, o del tipo TEXT si fueran datos más grandes (quizá en ese caso habría que pensar en normalizar la tabla).
Luego, por programación puedes traer los datos y crear un array con explode.
Supongamos que esta es tu lista de valores:
# $row["valores"]=$mValues; #valores es tu columna de valores separados por coma
$mValues="12,8,-1,80,99,157,77,22";
$arrValues=explode(",",$mValues);

#Prueba
print_r($arrValues);

Salida de la prueba:
Array
(
    [0] => 12
    [1] => 8
    [2] => -1
    [3] => 80
    [4] => 99
    [5] => 157
    [6] => 77
    [7] => 22
)

Si por algún motivo necesitaras saber a qué día corresponde cada dato, por lo único que debes preocuparte es por crear la lista de valores debidamente ordenada, luego, para buscar tienes que restar 1 al valor del día que necesites,  ya que, como se ve en la salida PHP crea los arrays indexando a partir de 0.
Digamos que necesitas el dato del día 5 del mes, ese dato está realmente en el índice 4 de array.
$dia=5;
echo $arrValues[$dia-1];

Salida:
99

That's all folks!

A: Yo lo que hago en esos casos es insertar los datos con json_encode() y después al leerlos de base de datos los recupero con json_decode().
Te pongo un ejemplo, muy básico, de la clase donde utilizo este método.
En este pequeño ejemplo, los campos cosa1, cosa2y cosa3 serán campos con estas características.
class clausulas extends db {

    protected $tableName = 'clausulas';
    protected $orden_defecto = 'descripcion';
    protected $id_empresa = null;

    public function __construct($id_empresa) {
        parent::__construct();

        $this->id_empresa = $id_empresa;
    }

    public function get($id) {
        if ($instance = parent::get($id)) {
            $instance->cosa1 = json_decode($instance->cosa1);
            $instance->cosa2 = json_decode($instance->cosa2);
            $instance->cosa3 = json_decode($instance->cosa3);
            return $instance;
        }
    }

    public function save($registro) {

        if (isset($registro->cosa1)) {
            $registro->cosa1 = $this->json_encode($registro->cosa1);
        }

        if (isset($registro->cosa2)) {
            $registro->cosa2 = $this->json_encode($registro->cosa2);
        }

        if (isset($registro->cosa3)) {
            $registro->cosa3 = $this->json_encode($registro->cosa3);
        }

        parent::save($registro);
      }

    }

De esta forma, con $clausulas->get($id) obtengo un registro del cual ya tengo los campos decodificados y con $clausulas->save($instancia) ya se almacenan debidamente formateados.
He utilizado esto en uno de mis últimos proyectos y los resultados son muy satisfactorios, eso sí, son campos sobre los cuales no se harán referencias cruzadas de otras tablas ni ningún tipo de acción (agrupación, ordenación...) sobre esos campos más que su lectura y posterior procesado en PHP.
Lo bueno, además, es que esto me permite que unos registros tengan datos que otros no van a tener, en tu caso tendrás meses de diferentes número de días.
Explorando este método, he visto que mysql tiene ahora un tipo de dato que se llama json pero como yo uso MariaDB y no lo implementa me quedo con mi pequeña aproximación.
Creo que esta es la forma más sencilla y versátil de realizar lo que comentas, mejor que parsearlo con otro formato arbitrario.
NOTA
Verás que utilizo $this->json_encode(), eso lo hice por si en un futuro necesito hacer algo más que un mero json_encode(), así ya tengo la clase prepara usando un método propio.
NOTA 2
Por aclarar, yo lo que almaceno realmente en esos campos son arrays multidimensionales y arrays de objetos, quizá para datos más simples (arrays unidimensionales) seria conveniente otro tipo de parseado más sencillo.
Eso ya queda al gusto del consumidor ;)


text:
Q: Steps needed to move postgres DB from Heroku to an Azure hosted Linux-based VM (Django app) I have a postgres database with 40 tables residing on Heroku right now. It's a Django app, and overall rows are roughly 5 million.
I want to migrate all that to an exact replica in an Azure VM (which already has postgres correctly installed and set up).
What's the safest, cleanest way to make this migration?
Here are the steps in my head:
1) Prepare the Azure VM, by:

*

*switching to user postgres and going to psql client via typing psql

*creating a database called mydatabase via the command CREATE DATABASE mydatabase;

*no need to run syncdb to create tables at this stage.
2) Log onto the Heroku commandline, and run the command heroku maintenance:on
3) Next, run the command heroku run pg_dump -C dbname | bzip2 | ssh  myusername@hostname "bunzip2 | psql mydatabase" (source: here)
That's it. No syncdb to create table structures or anything at any point.
Can anyone comment on those steps, and rectify wherever needed? Thanks!
Note: ask for more information in case you need it

A: heroku pg:backups capture (to capture the pg backup)
curl -o latest.dump heroku pg:backups public-url (to download the pg backup to your local machine)
ls -lh latest.dump (to check the size of the downloaded file, so you're certain you downloaded the complete file)
scp -P <your port e.g. 2222> latest.dump user@example.cloudapp.net:/home/user (this will transfer the file to your remote machine)
Then on your remote machine:
pg_restore --verbose --clean --no-acl --no-owner -U myuser -d mydb latest.dump
Hopefully this gets the job done.


text:
Q: Javascript - undefined array element when adding eventlistener I am fairly new to javascript and I am trying to grab all the "td" elements in the DOM and add a click event to them. When the code finishes executing, i can see I have 37 elements in cells array, but when I click the element, I get "clicked td37 undefined" in my console statement no matter which element is clicked. I do not have a clue what is wrong and any help would be appreciated.
<script>
window.addEventListener("DOMContentLoaded", createEventListeners, false);

function createEventListeners() {
   var cells = document.getElementsByTagName("td");
   console.log(cells);

   for (var i = 0; i < cells.length; i++) {
      cells[i].addEventListener("click", function () {
      console.log("clicked td" +  i + " " + cells[i]);

      }, false);
   }

 }
</script>

A: At the end of the loop, the value of i will be the cells.length, so cells[i] is undefined. You need to wrap them in a function so that i is the value you want. Read more about closure here
function createEventListeners() {
  var cells = document.getElementsByTagName("td");

  for (var i = 0; i < cells.length; i++) {
    (function(i) {
      cells[i].addEventListener("click", function () {
        console.log("clicked td" +  i + " " + cells[i]);
      }, false);
    }(i));
}

A: This is a scope issue. You need a closure. By the time any Event in your loop is called, i looks for it's last know value, which happens to be it's value at the end of the loop. Solution:
var pre = onload; // previous onload
onload = function(){
  if(pre)pre();
  function createEventListeners(){
    var cells = document.getElementsByTagName('td');
    for(var i=0,l=cells.length; i<l; i++){
      (function(i){
        cells[i].addEventListener('click', function(){
          console.log('i is at position:'+i));
        }, false);
      })(i);
    }
  }
  window.addEventListener('DOMContentLoaded', createEventListeners, false);
}

A: At the end of your loop, i is always the length of the array for anything you click on and since they're zero indexed, no element with that index exists. For example, if there are 10 elements, they're indexed as 0-9, but when you click any of them, i is always 10.

A: This question+answers are a great example of when and how to use closures. Since this question is tagged with jQuery, the each function would be a way to do it in jQuery. When you use each, it conveniently closes over what you are eaching through, so this would also work:
$(document).ready(function () {
    var $tds = $('td');
    $tds.each(function (i, td) {
        $(td).click(function () {
            console.log(i, td);
        });
    });
});

And also,  there is a way to do it without closures. If you store the value of the iterator onto the element itself via a data attribute, it stores a copy of the value, rather than a reference, so it retains the value of i at the time it was assigned:
window.addEventListener("DOMContentLoaded", createEventListeners, false);
function createEventListeners() {
    var cells = document.getElementsByTagName("td");
    console.log(cells);

    for (var i = 0; i < cells.length; i++) {
        cells[i].setAttribute('data-i', i);
        cells[i].addEventListener("click", function () {
            var i = this.getAttribute('data-i');
            console.log("clicked td" + i + " " + cells[i]);

        }, false);
    }
}


text:
Q: How can I simplify this conversion from underscore to camelcase in Python? I have written the function below that converts underscore to camelcase with first word in lowercase, i.e. "get_this_value" -> "getThisValue". Also I have requirement to preserve leading and trailing underscores and also double (triple etc.) underscores, if any, i.e.
"_get__this_value_" -> "_get_ThisValue_".

The code:
def underscore_to_camelcase(value):
    output = ""
    first_word_passed = False
    for word in value.split("_"):
        if not word:
            output += "_"
            continue
        if first_word_passed:
            output += word.capitalize()
        else:
            output += word.lower()
        first_word_passed = True
    return output

I am feeling the code above as written in non-Pythonic style, though it works as expected, so looking how to simplify the code and write it using list comprehensions etc.

A: This one works except for leaving the first word as lowercase.
def convert(word):
    return ''.join(x.capitalize() or '_' for x in word.split('_'))

(I know this isn't exactly what you asked for, and this thread is quite old, but since it's quite prominent when searching for such conversions on Google I thought I'd add my solution in case it helps anyone else).

A: Your code is fine.  The problem I think you're trying to solve is that if first_word_passed looks a little bit ugly.
One option for fixing this is a generator.  We can easily make this return one thing for first entry and another for all subsequent entries.  As Python has first-class functions we can get the generator to return the function we want to use to process each word.
We then just need to use the conditional operator so we can handle the blank entries returned by double underscores within a list comprehension.
So if we have a word we call the generator to get the function to use to set the case, and if we don't we just use _ leaving the generator untouched.
def underscore_to_camelcase(value):
    def camelcase():
        yield str.lower
        while True:
            yield str.capitalize

    c = camelcase()
    return "".join(c.next()(x) if x else '_' for x in value.split("_"))

A: I think the code is fine. You've got a fairly complex specification, so if you insist on squashing it into the Procrustean bed of a list comprehension, then you're likely to harm the clarity of the code.
The only changes I'd make would be:

*

*To use the join method to build the result in O(n) space and time, rather than repeated applications of += which is O(n²).

*To add a docstring.

Like this:
def underscore_to_camelcase(s):
    """Take the underscore-separated string s and return a camelCase
    equivalent.  Initial and final underscores are preserved, and medial
    pairs of underscores are turned into a single underscore."""
    def camelcase_words(words):
        first_word_passed = False
        for word in words:
            if not word:
                yield "_"
                continue
            if first_word_passed:
                yield word.capitalize()
            else:
                yield word.lower()
            first_word_passed = True
    return ''.join(camelcase_words(s.split('_')))

Depending on the application, another change I would consider making would be to memoize the function. I presume you're automatically translating source code in some way, and you expect the same names to occur many times. So you might as well store the conversion instead of re-computing it each time.  An easy way to do that would be to use the @memoized decorator from the Python decorator library.

A: This algorithm performs well with digit:
import re

PATTERN = re.compile(r'''
    (?<!\A) # not at the start of the string
    _
    (?=[a-zA-Z]) # followed by a letter
    ''', re.X)

def camelize(value):
    tokens = PATTERN.split(value)
    response = tokens.pop(0).lower()
    for remain in tokens:
        response += remain.capitalize()
    return response

Examples:
>>> camelize('Foo')
'foo'
>>> camelize('_Foo')
'_foo'
>>> camelize('Foo_')
'foo_'
>>> camelize('Foo_Bar')
'fooBar'
>>> camelize('Foo__Bar')
'foo_Bar'
>>> camelize('9')
'9'
>>> camelize('9_foo')
'9Foo'
>>> camelize('foo_9')
'foo_9'
>>> camelize('foo_9_bar')
'foo_9Bar'
>>> camelize('foo__9__bar')
'foo__9_Bar'

A: Here's mine, relying mainly on list comprehension, split, and join. Plus optional parameter to use different delimiter:
def underscore_to_camel(in_str, delim="_"):
    chunks = in_str.split(delim)
    chunks[1:] = [_.title() for _ in chunks[1:]]
    return "".join(chunks)

Also, for sake of completeness, including what was referenced earlier as solution from another question as the reverse (NOT my own code, just repeating for easy reference):
first_cap_re = re.compile('(.)([A-Z][a-z]+)')
all_cap_re = re.compile('([a-z0-9])([A-Z])')
def camel_to_underscore(in_str):
    s1 = first_cap_re.sub(r'\1_\2', name)
    return all_cap_re.sub(r'\1_\2', s1).lower()

A: I prefer a regular expression, personally.  Here's one that is doing the trick for me:
import re
def to_camelcase(s):
    return re.sub(r'(?!^)_([a-zA-Z])', lambda m: m.group(1).upper(), s)

Using unutbu's tests:
tests = [('get__this_value', 'get_ThisValue'),
         ('_get__this_value', '_get_ThisValue'),
         ('_get__this_value_', '_get_ThisValue_'),
         ('get_this_value', 'getThisValue'),
         ('get__this__value', 'get_This_Value')]

for test, expected in tests:
    assert to_camelcase(test) == expected

A: I agree with Gareth that the code is ok. However, if you really want a shorter, yet readable approach you could try something like this:
def underscore_to_camelcase(value):
    # Make a list of capitalized words and underscores to be preserved
    capitalized_words = [w.capitalize() if w else '_' for w in value.split('_')]

    # Convert the first word to lowercase
    for i, word in enumerate(capitalized_words):
        if word != '_':
            capitalized_words[i] = word.lower()
            break

    # Join all words to a single string and return it
    return "".join(capitalized_words)

A: The problem calls for a function that returns a lowercase word the first time, but capitalized words afterwards. You can do that with an if clause, but then the if clause has to be evaluated for every word. An appealing alternative is to use a generator. It can return one thing on the first call, and something else on successive calls, and it does not require as many ifs.
def lower_camelcase(seq):
    it=iter(seq)
    for word in it:
        yield word.lower()
        if word.isalnum(): break
    for word in it:
        yield word.capitalize()

def underscore_to_camelcase(text):
    return ''.join(lower_camelcase(word if word else '_' for word in text.split('_')))

Here is some test code to show that it works:
tests=[('get__this_value','get_ThisValue'),
       ('_get__this_value','_get_ThisValue'),
       ('_get__this_value_','_get_ThisValue_'),
       ('get_this_value','getThisValue'),
       ('get__this__value','get_This_Value'),
       ]
for test,answer in tests:
    result=underscore_to_camelcase(test)
    try:
        assert result==answer
    except AssertionError:
        print('{r!r} != {a!r}'.format(r=result,a=answer))

A: Here's a simpler one.  Might not be perfect for all situations, but it meets my requirements, since I'm just converting python variables, which have a specific format, to camel-case.  This does capitalize all but the first word.
def underscore_to_camelcase(text):
"""
Converts underscore_delimited_text to camelCase.
Useful for JSON output
"""
    return ''.join(word.title() if i else word for i, word in enumerate(text.split('_')))

A: Here is a list comprehension style generator expression.
from itertools import count
def underscore_to_camelcase(value):
    words = value.split('_')
    counter = count()
    return ''.join('_' if w == '' else w.capitalize() if counter.next() else w for w in words )

A:     def convert(word):
        if not isinstance(word, str):
            return word
        if word.startswith("_"):
            word = word[1:]
        words = word.split("_")
        _words = []
        for idx, _word in enumerate(words):
            if idx == 0:
                _words.append(_word)
                continue
            _words.append(_word.capitalize())
        return ''.join(_words)

A: This is the most compact way to do it:
def underscore_to_camelcase(value):
    words = [word.capitalize() for word in value.split('_')]
    words[0]=words[0].lower()
    return "".join(words)

A: For regexp sake !
import re

def underscore_to_camelcase(value):
    def rep(m):
        if m.group(1) != None:
            return m.group(2) + m.group(3).lower() + '_'
        else:
            return m.group(3).capitalize()

    ret, nb_repl = re.subn(r'(^)?(_*)([a-zA-Z]+)', rep, value)
    return ret if (nb_repl > 1) else ret[:-1]

A: Another regexp solution:
import re

def conv(s):
    """Convert underscore-separated strings to camelCase equivalents.

    >>> conv('get')
    'get'
    >>> conv('_get')
    '_get'
    >>> conv('get_this_value')
    'getThisValue'
    >>> conv('__get__this_value_')
    '_get_ThisValue_'
    >>> conv('_get__this_value__')
    '_get_ThisValue_'
    >>> conv('___get_this_value')
    '_getThisValue'

    """
    # convert case:
    s = re.sub(r'(_*[A-Z])', lambda m: m.group(1).lower(), s.title(), count=1)
    # remove/normalize underscores:
    s = re.sub(r'__+|^_+|_+$', '|', s).replace('_', '').replace('|', '_')
    return s

if __name__ == "__main__":
    import doctest
    doctest.testmod()

It works for your examples, but it might fail for names containting digits - it depends how you would capitalize them.

A: A slightly modified version:
import re

def underscore_to_camelcase(value):
    first = True
    res = []

    for u,w in re.findall('([_]*)([^_]*)',value):
        if first:
            res.append(u+w)
            first = False
        elif len(w)==0:    # trailing underscores
            res.append(u)
        else:   # trim an underscore and capitalize
            res.append(u[:-1] + w.title())

    return ''.join(res)

A: I know this has already been answered, but I came up with some syntactic sugar that handles a special case that the selected answer does not (words with dunders in them i.e. "my_word__is_____ugly" to "myWordIsUgly"). Obviously this can be broken up into multiple lines but I liked the challenge of getting it on one. I added line breaks for clarity.
def underscore_to_camel(in_string):
return "".join(
    list(
        map(
            lambda index_word:
                index_word[1].lower() if index_word[0] == 0
                else index_word[1][0].upper() + (index_word[1][1:] if len(index_word[1]) > 0 else ""),
            list(enumerate(re.split(re.compile(r"_+"), in_string)
                           )
                 )
        )
    )
)

A: Maybe, pydash works for this purpose (https://pydash.readthedocs.io/en/latest/)
>>> from pydash.strings import snake_case
>>>> snake_case('needToBeSnakeCased')
'get__this_value'
>>> from pydash.strings import camel_case
>>>camel_case('_get__this_value_')
'getThisValue'


text:
Q: Specify object type for lodash reduce Lodash _.reduce() will accept an object, but I get a TypeScript error (commented below) that suggests it's expecting an array. How do I correctly set the types in this example?
interface Fees {
    CardHandlingFee: number;
    AirlineSurcharge: number;
}

const fees: Fees = {
    CardHandlingFee: 2,
    AirlineSurcharge: 3
};

let total = 100;

// Argument of type 'Fees' is not assignable to parameter of type 'NumericDictionary'.
// Index signature is missing in type 'Fees'.
total += _.reduce(fees, (sum: number, v: number) => sum + v, 0);

A: Unfortunately because you define the type of fees as Fees, it is no longer treated an Object, which would pass the check of NumericDictionary<T> because of TypeScript's structural typing.
So you have two options basically.
1) Remove the type declaration from the fees variable. There is no need for declaring the type anyway. TypeScript will infer the type for you and later when you pass the object somewhere where an instance of Fees is needed, it will pass, because of the structural typing (basically duck typing).
interface Fees {
    CardHandlingFee: number;
    AirlineSurcharge: number;
}

const fees = {
    CardHandlingFee: 2,
    AirlineSurcharge: 3
};

let total = 100;
total += _.reduce(fees, (sum, v) => sum + v, 0);

2) Declare Fees as an extension to NumericDictionary<number>
interface Fees extends _.NumericDictionary<number> {
    CardHandlingFee: number;
    AirlineSurcharge: number;
}

const fees: Fees = {
    CardHandlingFee: 2,
    AirlineSurcharge: 3
};

let total = 100;
total += _.reduce(fees, (sum, v) => sum + v, 0);

And by the way, you don't need to declare the types of sum and v in the reduce function, that is infered from the type of fees.


text:
Q: Extract rows of clusters in hierarchical clustering using seaborn clustermap I am using hierarchical clustering from seaborn.clustermap to cluster my data. This works fine to nicely visualize the clusters in a heatmap. However, now I would like to extract all row values that are assigned to the different clusters.
This is what my data looks like:
import pandas as pd

# load DataFrame
df = pd.read_csv('expression_data.txt', sep='\t', index_col=0)

df

    log_HU1         log_HU2
EEF1A1  13.439499   13.746856
HSPA8   13.169191   12.983910
FTH1    13.861164   13.511200
PABPC1  12.142340   11.885885
TFRC    11.261368   10.433607
RPL26   13.837205   13.934710
NPM1    12.381585   11.956855
RPS4X   13.359880   12.588574
EEF2    11.076926   11.379336
RPS11   13.212654   13.915813
RPS2    12.910164   13.009184
RPL11   13.498649   13.453234
CA1 9.060244    13.152061
RPS3    11.243343   11.431791
YBX1    12.135316   12.100374
ACTB    11.592359   12.108637
RPL4    12.168588   12.184330
HSP90AA1    10.776370   10.550427
HSP90AB1    11.200892   11.457365
NCL 11.366145   11.060236

Then I perform the clustering using seaborn as follows:
fig = sns.clustermap(df)

Which produces the following clustermap:

For this example I may be able to manually interpret the values belonging to each cluster (e.g. that TFRC and HSP90AA1 cluster). However I am planning to do these clustering analysis on much bigger data sets.
So my question is: does anyone know how to get the row values belonging to each cluster?
Thanks,

A: Using scipy.cluster.hierarchy module with fcluster allows cluster retrieval:
import pandas as pd
import seaborn as sns
import scipy.cluster.hierarchy as sch

df = pd.read_csv('expression_data.txt', sep='\t', index_col=0)

# retrieve clusters using fcluster
d = sch.distance.pdist(df)
L = sch.linkage(d, method='complete')
# 0.2 can be modified to retrieve more stringent or relaxed clusters
clusters = sch.fcluster(L, 0.2*d.max(), 'distance')

# clusters indicices correspond to incides of original df
for i,cluster in enumerate(clusters):
    print(df.index[i], cluster)

Out:
EEF1A1 2
HSPA8 1
FTH1 2
PABPC1 3
TFRC 5
RPL26 2
NPM1 3
RPS4X 1
EEF2 4
RPS11 2
RPS2 1
RPL11 2
CA1 6
RPS3 4
YBX1 3
ACTB 3
RPL4 3
HSP90AA1 5
HSP90AB1 4
NCL 4


text:
Q: perl utf8 corruption I am using the perl module sapnwrfc to connect to SAP and retrieve reports.  This module uses utf8 and when the data is returned some of the data has a pattern of utf8 character corruption.  This appears to happen when a line in the SAP report is more than 4096 in length and my current thinking is that the read buffer of perl is splitting utf8 characters and causing the corruption.
$abap_lookup = $sap_rfc->function_lookup("REPORT");
$abap_program = $abap_lookup->create_function_call;

# set abap program input variables
$abap_program->REPORT($abap_program_name);
$abap_program->VARIANT($abap_variant_name);

# call the abap program
$abap_program->invoke;

$abap_program->DATA has the corruption in one place in each line that is more than 4Kb
This is the fragment with the corruption, the actual line is a byte or two more than 4Kb.
\x{f8fc}\x{2500}     \x{500}/\x{f8fc}\x{2500}

This is what is expected, so I am assuming something is splitting the line and causing the problem.
\x{f8fc}\x{2500}\x{f8fc}\x{2500}\x{f8fc}\x{2500}

I have tried all manner of open ':utf8' pragma and other settings (use utf8, binmode(STDIN, ":utf8"), binmode(STDOUT, ":utf8");).  Also have tried to turn off buffering ($| = 1;).  I cannot tell if this is a utf8 problem or a buffering problem.  Does anyone know why this would be doing this and how to fix it?

A: was not able to figure out where the corruption is happening, but it is repeatable so I built a filter.


text:
Q: How do i properly rotate a thumbnail image based on the orientation value? I'm currently developing an API where it takes a in a video as parameter and then generates a thumbnail from that. When it's later presented with a thumbnail the thumbnail is rotated in the wrong way, i know this has to do with the orientation but i can't seem to find either 0x0112 (274) or 0x5029 (20521) in the PropertyIdList. The only ones i got are 771, 769, 37510, 20753, 20753, 20754. None of these as far as i know are focused on the orientation of the image. I generated the thumbnail with Nreco if that has any connection with it. This is my code thus far:
  if(Array.IndexOf(image.Img.PropertyIdList,20521)>-1)
            {
                var orientation = (int)image.Img.GetPropertyItem(20521).Value[0];
                switch(orientation)
                {
                    case 1:
                        break;
                    case 2:
                        image.Img.RotateFlip(RotateFlipType.RotateNoneFlipX);
                        break;
                    case 3:
                        image.Img.RotateFlip(RotateFlipType.Rotate180FlipNone);
                        break;
                    case 4:
                        image.Img.RotateFlip(RotateFlipType.Rotate180FlipX);
                        break;
                    case 5:
                        image.Img.RotateFlip(RotateFlipType.Rotate90FlipX);
                        break;
                    case 6:
                        image.Img.RotateFlip(RotateFlipType.Rotate90FlipNone);
                        break;
                    case 7:
                        image.Img.RotateFlip(RotateFlipType.Rotate270FlipX);
                        break;
                    case 8:
                        image.Img.RotateFlip(RotateFlipType.Rotate270FlipNone);
                        break;
                }
            }

But it never enters this block of code since it can't find the the indexOf propertyIdList 20521.
Any help would be higly appritiated!
Thank you.
EDIT: Video was taken with an Iphone 6


text:
Q: How to run each on each html element I have an html table inside a div, and i want to run jquery on each li element or the li class
and alert his id.
this is the html code.
this is the html code.
HTML:

               2014-03-27 10:36:25
Title - 6 test
               <input type="button" class="minimze" style="background-color:green;background:url(/srv/admin/img/announcement/minimise_button.png);float:right;" id="minimze7">

               <input type="button" value="Confirm" class="ajax_btn_right_toolbar" id="button7"><input type="checkbox" class="ajax_checkbox_toolbar" id="checkbox7">

               0000-00-00 00:00:00
Title - 4 test
               <input type="button" class="minimze" style="background-color:red;background:url(/srv/admin/img/announcement/minimise_button.png);float:right;" id="minimze5">

               <input type="button" value="Confirm" class="ajax_btn_right_toolbar" id="button5"><input type="checkbox" class="ajax_checkbox_toolbar" id="checkbox5">

Please confirm you have read and acted upon this message

i try:
jQuery.each(".announcement_tlbr", function(k,v){  alert(k); })

what is a good way to do this?

A: You should use this inside each to get the reference of current element.Try this:
jQuery.each(".announcement_tlbr", function(e){
  alert($(this).attr('id'));//or this.id
});

A: $(document).ready(function() {
    $(".announcement_tlbr").each(function(){
       alert($(this).attr("id"))
    });
});


text:
Q: Web build for Unity ARCORE project can we create webgl build for unity arcore based project? We are planning to create Unity + ARCORE based Augumented reality app, is it possible to make WEBGL build?

A: Unity does not support it yet. But there are samples with webgl projects
Google docs
Samples
Code sample


text:
Q: Ec2 Metadata updgrade from imdSV1 to imdSV2 causes 403 and 401 error- kube2iam I recently updated my ec2 instances to use imdSV2 but had to rollback because of the following issue:
It looks like after i did the upgrade my init containers started failing and i saw the following in the logs:
time="2022-01-11T14:25:01Z" level=info msg="PUT /latest/api/token (403) took 0.753220 ms" req.method=PUT req.path=/latest/api/token req.remote=XXXXX res.duration=0.75322 res.status=403 time="2022-01-11T14:25:37Z" level=error msg="Error getting instance id, got status: 401 Unauthorized"
We are using Kube2iam for the same. Any advice what changes need to be done on the Kube2iam side to support imdSV2? Below is some info from my kube2iam daemonset:
EKS =1.21
image = "jtblin/kube2iam:0.10.9"

A: You can modify instances to support imdSV1, but better solution is to use IRSA.
https://github.com/terraform-aws-modules/terraform-aws-eks/issues/1749


text:
Q: How to convert magento1 extensions to magento2? Is it possible to convert magento1 extensions to magento2?.I am searching but no perfect solution.Can you please help me?

A: I did't tried , but You can check below links :
https://github.com/magento/code-migration
https://github.com/unirgy/convertm1m2
https://www.slideshare.net/VladimirKerkhoff/convert-magento-1-extensions-to-magento-2


text:
Q: TomCat stores logs with delay Since monday I've been working on setting up the CI server Jenkins. Today I've noticed, that files like catalina.YYYY-MM-DD.log and tomcat6-stderr.YYYY-MM-DD.log of today does not contain some of errors and stacktraces that I see in my browser. It's strange, but the messages and stacktraces of yesterday are there. Does anybody know something about this kind of delay?

A: Try in "localhost.YYYY-MM-DD.log", Most of the errors you can find in this file.

A: Have you looked in catalina.log and tomcat6-stderr.log ?  Our configurations don't add a datestamp to the log until the logging system rolls them over (DailyFileAppender or something like that) at midnight.


text:
Q: Symfony2 translatable doesn't use joins I use translatable and now my page has 133 db queries because symfony retrieves every translation separate. How can I make it do a join when fetching entities?

A: You should use query hint to do the join before..
https://github.com/l3pp4rd/DoctrineExtensions/blob/master/doc/translatable.md#using-orm-query-hint
However maybe its better not to use translatable sometimes ...


text:
Q: Php show error or ok message before redirect after sending an email message through a form, i'd like to send a message like 'mail sent' or 'error, retry!' before than redirect the user to another page. here is the php code i'm using after sending the email:
<?php
[... send mail php code]
$mail->MsgHTML($_POST["message"]);
// this messages are not show, of course
if (!$mail->send()) {
echo '<script language="javascript">';
echo 'alert("Mailer Error: " . $mail->ErrorInfo;)';
echo '</script>';

} else {
echo '<script language="javascript">';
 echo 'alert("Message successfully sent. Thank\'s")';
echo '</script>';

}

header( 'Location: http://localhost:8888/contacts.html' ) ;

?>

How can i do it?

A: You can do this:
header( "refresh:5; url=http://localhost:8888/contacts.html" );

if(!$mail->send($to, $subject, $body)) {
   echo "Didn't send yo";
} else {
  echo "Sent";
}

Or this:
if(!$mail->send($to, $subject, $body)) {
   echo "Didn't send yo";
} else {
  echo "Sent";
}

sleep(NUMBER_OF_SECONDS);
@header( 'Location: http://localhost:8888/contacts.html' ); //Please note that this method is a big no!!

Or if PHP isn't doing it for you:
echo "<script>window.setTimeout(function() {window.location.href = 'http://localhost:8888/contacts.html';},NUMBER_OF_SECONDS);</script>";

A: Try this:
<?php
// Mail code goes here

echo 'Successfull';
header( "refresh:5; url=Location: http://localhost:8888/contacts.html" );
?>


text:
Q: Minimum Tournament Required During a contest, I came up with a question:

What are the minimum number of tournaments needed to get the winner? A
  player is out when he loses two matches. Total players are 51. (
  Assume  Badminton )

I'm not sure how to solve it. Unfortunately, It is confusing me with combinations and permutations.
Any suggestions? Thanks!

A: 51 players, 1 winner:  50 needed to go out.
50 players out, 2 losses each, need: 100 losses.
100 losses means 100 games.
So, minimum is: 100 games.

A: 95 matches required... if make a binary tree with 32 players competing, only 1 will remain in end with no loss yet while the rest have 1 loss each... if these 32 players wid 1 loss each are made to compete again, then only 1 with 1 loss will remain and rest will be eliminated from the contest... this process can be done wid any number of players by making proper trees and optimizing number of matches required... i'm not sure if am able to optimize it enough to give least number of matches or not !


text:
Q: Android sqlite backup/restore without overwriting Question in short form: It seems from the followups that I should perhaps emphasize and simplify the core of my question. The core is this: other backup options for Android DBs seems to leave the risk that a restore could overwrite data currently in the database. Is this so, and is there a way to backup/restore without this risk?
.
Question in long form: Having looked through many of the (rather numerous) questions about backing up up an SQLite db on Android I have one question that I couldn't find an answer to.
All the other backup/restore discussions dealt with saving the db file to the SD (or, in How to backup/restore SQLite database on Android to Dropbox, to the cloud), and then restoring it when required. My concern is, wouldn't that restore overwrite the current DB?
I'm concerned about when the a user has a new install of an app they've been using for a short time (generating new data) and then want to import data from a previous backup of the app. With all the other backup/restore approaches it seems like restoring the old DB file would overwrite any new data in the current DB file. What I want instead is a backup option that, on restore, would add the data from the backup into the current DB to make it complete without overwriting anything else in it.
Do the other approaches do this? Or do they, as I suspect, overwrite in such a case?
If they do overwrite then my best backup option is probably to write out to a csv or xml file or something and I expected these backup discussions to be about easy ways to do that. Are there any processes build to speed that process and make it easy or do I have to do all that manually? If so, recommendations on the format to write to and why?
Similarly, does anyone know if the built in Google backup using BackupAgentHelper would have this same overwrite issue?
And finally, if I end up going through a data migration (similar to How to Restore SQLite Database from Backup after Core Data model has changed (lightweight migration)) at any point what should I do now (I'm still in DB design stage) to make such a potential future change easier vis-à-vis this backup process?

A: I think the problem of restoring old data without changing (or conflicting with) the 'newer' data is not very hard to solve in the scenario you describe.  It seems that essentially you just want to 'add' the old data (records) to the new database with the assumption that the old data has no logical conflict with the newer data (that is, it is semantically OK to create new records for the old data). I believe that taking care of the primary key conflicts during restoration would be the most important issue to consider.
Let's take two cases:
1: You are using the auto generation of primary key values feature of the database (e.g., using an AUTOINCREMENT column of a SQLite table).
Let's assume that the 'newer' database records might have used primary key (ROWID) values of 1 to 10 before the restoration process is started. If you have 'older' database records with any of those primary key values (1 to 10), you have a problem only if you want to preserve those old primary key values. To avoid that problem, don't retain the 'old' primary key value of an'old' record – after reading the record from the 'old' database, just save the values of other attributes (columns) of the 'old' record and let the database generate a new primary key value for this 'restored' record. Essentially, the 'old' record is saved with a new primary key value. If you are concerned about maintaining a chronological order of the records after this 'restoration' process, I suggest you also keep a timestamp column whose value does not get changed in the process.
2: You are using an alternate mechanism (UUID, Sequence Generators, etc.) for generating primary key values:
In this case, read the 'old' record and before saving it in the 'newer' database, replace the 'old' primary key value with a primary key value generated with the alternate mechanism – that would, by design, guarantee the uniqueness of the primary key value of the 'restored' record with respect to the pre-existing 'newer' records.
To simplify the programming effort for this 'restoration' process, especially if you are dealing with multiple tables, you may use an ORM like JDXA. One of the sample apps shipped with the SDK illustrates a similar technique for transferring 'old' data while upgrading a database to a newer version. JDXA also offers a convenient sequence generator mechanism to easily and efficiently create unique ids that you can assign to your objects before persisting them.

A: After continued research I'm increasingly concluding there isn't a better approach to this problem. For a simple backup you can simply copy the database file as many of the other threads discuss and leave the overwrite on restore issue unaddressed (and also risk compatibility problems evidently: https://stackoverflow.com/a/10842043/3108762). For a truly robust backup you just have to write your entire DB out to XML and read it back in with all the work that entails.
The only better alternative I've found is mentioned in https://stackoverflow.com/a/34477622/3108762 which refers to the new Android feature Configuring Auto Backup for Apps, but only works in Android 6.0 and up. I will be testing that, but if it doesn't work, and for anything below Marshmallow, it seems writing my entire DB out to XML and then reading it back in again is the only truly robust approach.
Not entirely a surprise but good to know.