text:
Q: Input to capture minutes and seconds in the format (mm:ss) in angularjs I am creating a simple form for an application in angularjs. I need an input field to recieve time data with only minutes and seconds in the format "mm:ss". Anyone who has worked on this, your assistance would be highly appreciated. I already have created time input for my form. Actually, I am working on project created by other programmer. The model for the time input was initialized as follows:
function initDate(date, indexX, indexY){
      if(date != null && date != ''){
        var dateArray = date.split(":");
        var dt = new Date(1970,1,1,dateArray[0],dateArray[1],dateArray[2]);
        vm.modelDate[indexX][indexY] = dt;
      }
}

<input name="inputExTime{{q.listSubQuestions[contTime].questionId}}{{contTime}}0"
    type="time" class="form-control btn-act btn-act-inputs intime_ex" step="1"
    ng-disabled="disabledfields"
    ng-model="vm.modelDate[0][contTime]"
    min="00:00:00" max="12:59:00"
    ng-change="vm.changeDate(parentIndex,0,contTime);vm.calculateHours(form['inputExTime'+q.listSubQuestions[contTime].questionId+contTime+0].$modelValue, form['inputExTime'+q.listSubQuestions[contTime].questionId+contTime+2].$modelValue, form['inputExTime'+q.listSubQuestions[contTime].questionId+contTime+3], contTime);vm.average();"
    ng-required="$index<vm.numberOfRequiredRows?(q.attributes.required==false?false:isregister):false"
    ng-class="{true: 'inp-f'}[form['inputExTime'+q.listSubQuestions[contTime].questionId+contTime+0].$invalid]"
    ng-init="vm.modelDate[0][contTime]=null;vm.initArray(''+q.listSubQuestions[contTime].questionId+contTime+0);vm.initDate(q.listSubQuestions[0].listAnswers[contTime].detail, 0, contTime);"

/>

A: You need to define an input element in your form of the time time:
<input type="time" ng-model="timeModel">

The ng-model would be a Date object. Otherwise, AngularJS will throw an error.

var app = angular.module('time', []);

app.controller('MainCtrl', function($scope) {
  // The order of the params is the following:
  // Year, Month, Day, Time, Minutes, Seconds
  $scope.timeModel = new Date(2017, 10, 13, 10, 30, 0);
});
<!DOCTYPE html>
<html ng-app="time">

<head>
  <meta charset="utf-8" />
  <title>Time Model Example using AngularJS</title>
  <script>
    document.write('<base href="' + document.location + '" />');
  </script>
  <script data-require="angular.js@1.5.x" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.11/angular.min.js" data-semver="1.5.11"></script>
  <script src="app.js"></script>
</head>

<body ng-controller="MainCtrl">
  <input type="time" ng-model="timeModel">
</body>

</html>

On the official documentation, you can find more information about this.
Keep Rocking!


text:
Q: Why are we not affected by the radiation of the radioactive decay going inside the Earth? I was reading the question Why has Earth's core not become solid?, and one of the answers says that

The core is heated by radioactive decays of Uranium-238, Uranium-235, Thorium-232, and Potassium-40

Why are we not affected by the radioactive emission of the condition below? Is this due to the fact that there is a very thick layer of mantle and crust between us and the core? Or I am wrong and we suffer from it's radiation in everyday life up to some extent?

A: Alphas and betas are stopped by a small amount of material. Gammas are more penetrating, but a gamma ray with a typical energy would be stopped by something like 10 cm of rock.

A: You are always subjected to a low background of ionizing radiation from a number of natural and artificial sources, which include cosmic rays, trace amounts of radioactive nuclei in the air and in food, and indeed from the ground. A good place to read up on this is the corresponding Wikipedia article.
The radiation from the core, however, has no chance of making it to the surface. Gamma radiation is typically stopped by a few to maybe 20 or 30 cm of rock or soil. (There is also the danger that material used to shield against gamma radiation becomes radioactive itself, but of course this is hardly an issue with the Earth's core.) Alpha and beta rays are even easier to stop. Trace amounts of radioactive nuclei, though, can be present in the soil and buildings around you and will then expose you to a small amount of radiation.
It's important to note that this is natural and nothing to worry about. The most significant contribution to background radiation, away from zones like Hiroshima, Chernobyl or Fukushima, is the trace amount of radon in the air you breathe.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Windows environmental variable keeps loading despite removing I don't remember how exactly, but I had set up an environmental variable on Windows. This is not inside the Windows advanced settings -> Environmental Variables.
I have tried to unset it in many ways including, from git-bash:
$ unset DUMMY
$ env | grep DUMMY

This works only for the current session. When I restart or open a new terminal I can still see the variable set. I also tried to unset it from PowerShell as follows:
$ Remove-Item Env:\DUMMY

But like the previous technique, this is only for the current session. How can I find where this environmental variable is being loaded?
PS: To clarify, this is an environment variable that I created myself some weeks ago, but I forgot where/how I had set it to stay persistent.


text:
Q: How can a proof by formula induction in a formal language be formalized? From a set of not-so-rigorous lecture notes on Metalogic:

Formulas of $L$:

*

*(i) Each sentence letter is a formula.

*(ii) If $A$ is a formula, then so is $\neg A$.

*(iii) If $A$ and $B$ are formulas, then so is ($A$ $\wedge$ $B$).

*(iv) Nothing is a formula unless its being one follows from
  (i)-(iii).

A proof by formula induction of some property $P$ of this formal language shows that the property $P$ holds for (i), (ii), (iii) respectively, and therefore holds for all possible formulas by (iv).
For example, a proof of the property $P$ that all formulas $A$ contain the same number of left parentheses as right parenthesis involves 3 steps:

*

*A sentence letter $s$ has no parentheses, and so it vacuously holds, or $0_{left} = 0_{right}$

*Assume $P$ holds for $A$, then as $\neg A$ contains the same number of parentheses as $A$, $P$ holds for $\neg A$.

*Assume that $P$ holds for $A$ and $B$, then for $(A \wedge B)$ the number of parentheses on the left is $A_{left}+B_{left}+1$ and on the right $A_{right}+B_{right}+1$, and as $A_{left}=A_{right}$, $B_{left}=B_{right}$, and $1=1$, $P$ holds.

The property $P$ of formulas of $L$ is proven by formula induction.
My question is, how can such a property and its proof be formalized in a logical system / calculus, using formal inference rules and axioms?

A: You can see some textbooks, like :

*

*Herbert Enderton, A Mathematical Introduction to Logic (2nd ed - 2001), SECTION 1.4 : Induction and Recursion, page 34-on

*Dirk van Dalen, Logic and Structure (5th ed - 2013), page 7-on :

Definition 2.1.1 The language of propositional logic has an alphabet consisting of

(i) proposition symbols: $p_0,p_1,p_2,\ldots$,
(ii) connectives: $∧,∨,→,¬,↔,⊥$,
(iii) auxiliary symbols: ( , ).

Definition 2.1.2 The set $PROP$ of propositions is the smallest set $X$ with the properties

(i) $p_i \in X (i \in \mathbb N), ⊥ \in X$,
(ii) if $\varphi, \psi \in X$, then $(\varphi \square \psi) \in X$, where $\square$ is one of the connectives $∧,∨,→,↔$.
(iii) if $\varphi \in X$, then $(¬ \varphi) \in X$.

Properties of propositions are established by an inductive procedure analogous to Definition 2.1.2: first deal with the atoms, and then go from the parts to the composite
  propositions. This is made precise in the following theorem.
Theorem 2.1.3 (Induction Principle) Let $A$ be a property, then $A(\varphi)$ holds for all $\varphi \in PROP$ if

(i) $A(p_i)$, for all $i$, and $A(⊥)$,
(ii) if $A(\varphi),A(\psi)$, then $A((\varphi \square \psi))$,
(iii) if $A(\varphi)$, then $A((¬ \varphi))$.

We call an application of Theorem 2.1.3 a proof by induction on $\varphi$.
[...]

Example Each proposition has an even number of brackets. Proof :

(i) Each atom has $0$ brackets and $0$ is even.
(ii) Suppose $\varphi$ and $\psi$ have $2n$, resp. $2m$ brackets, then $(\varphi \square \psi)$ has $2(n + m + 1)$ brackets.
(iii) Suppose $\varphi$ has $2n$ brackets, then $(¬ \varphi)$ has $2(n +1)$ brackets.

[...]

In arithmetic one often defines functions by recursion [...]. The justification is rather immediate: each value is obtained by using the preceding values (for positive arguments). There is an analogous principle in our syntax.
Example 1. The number $b(\varphi)$ of brackets of $\varphi$, can be defined as follows:

$b(\varphi) =0$ for $\varphi$ atomic,
$b((\varphi \square \psi)) = b(\varphi)+b(\psi)+2$,
$b((¬ \varphi)) = b(\varphi)+2$.

The value of $b(\varphi)$ can be computed by successively computing $b(\psi)$ for its subformulas $\psi$.
We can give this kind of definition for all sets that are defined by induction. The
  principle of "definition by recursion" takes the form of "there is a unique function
  such that ...". The reader should keep in mind that the basic idea is that one can
  "compute" the function value for a composition in a prescribed way from the function
  values of the composing parts.
The general principle behind this practice is laid down in the following theorem.
Theorem 2.1.6 (Definition by Recursion) Let mappings $H_{\square} : A^2 \to A$ and
  $H_¬ :  A \to A$ be given and let $H_{at}$ be a mapping from the set of atoms into $A$, then there exists exactly one mapping $F : PROP \to A$ such that

$F(\varphi) =  H_{at}(\varphi)$ for $\varphi$ atomic,
$F((\varphi \square \psi)) = H_{\square}(F(\varphi),F(\psi))$,
$F((¬ \varphi)) = H_¬(F(\varphi))$.

[...]

Example 2. The rank $r(\varphi)$ of a proposition $\varphi$ is defined by

$r(\varphi) = 0$ for atomic $\varphi$,
$r((\varphi \square \psi)) = max(r(\varphi), r(\psi)) + 1$,
$r((¬ \varphi)) = r(\varphi)+1$.

We now use the technique of definition by recursion to define the notion of subformula.
Definition 2.1.7 The set of subformulas $Sub(\varphi)$ is given by

$Sub(\varphi) = \{ \varphi \}$ for atomic $\varphi$
$Sub(\varphi_1 \quad \varphi_2) = Sub(\varphi_1) \cup Sub(\varphi_2) \cup \{ \varphi_1 \square \varphi_2 \}$
$Sub(¬ \varphi) = Sub(\varphi) \cup \{ ¬ \varphi \}$.

We say that $\psi$ is a subformula of $\varphi$ if $\psi \in Sub(\varphi)$.

For a formalization into set theory, see :

*

*Kenneth Kunen, The Foundations of Mathematics (2009), page 82 and page 90-on,

and the final remark [page 93] :

Working in set theory, the set $\mathcal W$ of symbols can have arbitrary cardinality, but if $\mathcal W$ is finite or countable, it is conventional to assume that $\mathcal W \subseteq HF$. Then [...] all expressions will lie in $HF$ also, [... i.e.] all finite mathematics lives within $HF$ [where $HF$ is the set of hereditarily finite sets (see page 74)].


text:
Q: Using Postgresql Schemas with Sequelize I am trying to drop all tables in a schema (Postgres 9.3). When the models were being created, I have specified which schema they belong to.
model.schema( "schema_name")

And I was able to generate all tables in this specific schema. No problem here. However, when I want to drop the tables in the same schema, I am having to explicitly set the search path for it to be successful.
        db.sequelize.query("set search_path=consumer")
        .then( function( arg ){
            db.sequelize.drop({cascade:true})
                .then( function( arg ){
                    fulfill( arg );
                },function( err ){
                    reject( err );
                });
        });

When Sequelize claims support for PostgreSQL schema, I would expect that this detail must have been taken care of (because most of the other features work charmingly well!). So my question is : Do I have to set search path or am I missing some option that I am not making use of?

A: sequelize creates a clone of the object, sets the schema on it and returns the clone.  Therefore the original object is unchanged.
Try
model.schema( "schema_name") instead.


text:
Q: CURL and PHP session based authentication I have an application on https://app.example.com. The application requires users to login; if they are not logged in they are redirected to https://app.example.com/login.php when attempting to access any URL on this domain.
When the user has logged in successfully the application uses native PHP sessions to maintain the login state.
We have a separate application on https://db.example.com. This has been built with CakePHP 3. It is configured so that a user will be unable to access any URL on this domain unless they have logged in through https://app.example.com first. This was done by configuring the session.cookie_domain to .example.com and then setting the cookie used for sessions to PHPSESSID:
// config/app.php on db.example.com
'Session' => [
    'defaults' => 'php',
    'cookie' => 'PHPSESSID',
    'timeout' => '0',
    'ini' => [
        'session.cookie_domain' => '.example.com',
        'session.cookie_httponly' => 'off'
    ]
];

There is a script included from app.example.com on db.example.com which runs on every request. This - combined with the ability to read the session cookie - means we are checking the user is logged in before they can access anything on db.example.com; they get redirected to app.example.com/login.php if not.
Up to this point everything works fine.
The problem is that I'm trying to make a CURL request (using Cake's in-built functionality for this: https://book.cakephp.org/3.0/en/core-libraries/httpclient.html) in part of my application on db.example.com to another URL also on db.example.com but for response is a 302 redirect to https://app.example.com/login.php.
The request is made from https://db.example.com/foo to https://db.example.com/bar - which also requires an id parameter in the POST data - like this:
// Request made by /foo:
public function foo()
{
    $this->autoRender = false;

    $http = new Client();

    $response = $http->post('https://db.example.com/bar', [
        'id' => '12345'
    ]);

    debug($response);
}

The output from the above is a HTTP 302 with the location set to the login page on app.example.com:
object(Cake\Http\Client\Response) {
    [protected] code => (int) 302
    [protected] cookies => null
    [protected] reasonPhrase => 'Found'

// ...

'Set-Cookie' => [
    (int) 0 => 'PHPSESSID=g9aeqt2acol6av03rqul2puo20; path=/; domain=.example.com; secure'
    ],
'Location' => [
    (int) 0 => 'https://app.example.com/login.php'
    ],

}

I have read Keeping session alive with Curl and PHP but can't see what else to configure to solve this?
I also don't understand the cookies => null part of the debug information, when Set-Cookie has the correct session/cookie/domain details.
Environment details:

*

*Both app.example.com and db.example.com are on the same server.

*Both use PHP 7.0.33

*db.example.com uses CakePHP 3.5.13 as a framework; but app.example.com uses vanilla PHP (no framework).

*Web server is Apache 2 / CentOS.

A: The HTTP client will not auto-populate itself with cookies from the application it's running in, or any other application state for that matter, and as mentioned by @misorude in the comments, your code doesn't set any cookies to the client, hence it won't send any.
You'll have to set the required session cookie yourself, for example like this for a single request:
$data = [
    'id' => '12345'
];
$config = [
    'cookies' => [
        //'PHPSESSID' => $this->request->getSession()->id() // before CakePHP 3.6
        'PHPSESSID' => $this->getRequest()->getSession()->id()
    ]
];
$response = $http->post('https://db.example.com/bar', $data, $config);

The supposed cookies property on the response object being empty is a debug display "problem", there is no custom debug output for that class, hence PHP defaults are being used, which will include protected properties like $cookies, which however is not being populated until you're invoking the proper methods for reading cookies, that is getCookies(), getCookie(), getCookieData(), or getCookieCollection().
See also

*

*Cookbook > Http Client > Setting and Managing Cookies

*Cookbook > Http Client > Accessing Cookie Data


text:
Q: Intermediate tutorial for OpenGL as implemented in Qt I am making an interface for a free-and-open project I'm working on. I know that eventually I'll need it to do some heavy lifting with 3D graphics, so I'll need access to the GPU. I stumbled upon the Qt framework and its use of OpenGL. Their cross-platform properties are very appealing to me, and I've learned a lot about building run of the mill / plumbing kinda stuff on Qt, but using OpenGL is more challenging than I'd have hoped.
I've rooted around in several books and on Google for good tutorials, but they jump around, or don't seem to quite work when I try to implement them.  The examples presented in the IDE have a lot of bells and whistles, and almost none of it is explained.  When I tried implementing the example from "C++ GUI Programming with Qt 4", it didn't compile properly.  There are a set of somewhat famous "NeHe" tutorials on OpenGL, but they are not implemented with Qt and the companion series on made by "The Independent Qt Tutorial" is very brief.
I would be very grateful for an example that goes very slowly and introduces Qt and OpenGL together.  There is a blog entry that made things a lot clearer when I read it from a man named Daniel Eder.  But he hasn't actually written code in that part of the discussion.
Specifically, if I could just get something really simple working in Qt like a cube I could rotate or maybe something more sophisticated like a sphere, I'd have enough traction to understand other tutorials.  I definitely want to do the coding myself, but I'm having trouble even getting to the place where I can fool around, haha.

A: Here are some places with tutorials and examples:

*

*There is also a Wiki in the Qt Dev network that you may find useful. I particularly suggest Wesley Stessens's blog that helped me personally a lot.

*Nehe website provide a good tutorial where you can find some of the examples given ported to Qt.

*There are also many QtOpenGL examples in Qt Creator/SDK that can be handy. I strongly suggest you take a look at them as they are very simple to understand and to play around with.
With that my next step was to read these two books:

*

*C++ GUI Programming with Qt 4, 3rd edition

*OpenGL Programming Guide: The Official Guide to Learning OpenGL, 7th edition
I have also been very happy when looking for help in the related Doc's/Reference manuals, etc.:

*

*Qt Documentation

*QtOpenGL module

*OpenGL Documentation
At this level, you may solve your implementation problem straight away : )
Good luck.


text:
Q: Which file is generated after preprocessing of a C program? For a C program just before compilation, i.e. after the pre-processing has been completed which file(what extension) is generated?

A: It is compiler dependent. Most compilers by default don't generate intermediate pre-processor files.
With gcc, if you add -save-temps option to get the intermediate files, the output of the pre-processor is dumped in a .i file. With -E option (to perform only the pre-processing), without -o to specify the output file, the result is dumped to stdout.

A: In most current compilers (e.g. GCC or Clang/LLVM) - and for performance reasons - the C/C++ preprocessor is an internal part of the compiler (in GCC it is libcpp/ and is a library ...), so no preprocessed form is output into a file.
In the very first C or proto-C compilers (1970s PDP-8) the memory was so small (64kilobytes!) that such an organization was not possible, and the preprocessor was a separate program /lib/cpp
Today, our laptops have several gigabytes of memory, which is usually much larger than the preprocessed form (of the largest source file you'll feed to your compiler). So current compilers keep some internal representation of the whole translation unit and are able to optimize it entirely (inter-procedural optimizations, including inlining).
All compilers keep several forms of the abstract syntax tree (AST); the bulk of the work of a compiler is not parsing or code generation, but transforming some internal representation of the AST into another internal representation (itself further transformed). In GCC most of the optimizations are working on the GIMPLE form. You can extend the compiler by adding your own optimization passes, e.g. with your GCC plugin.
In turn, this technological evolution has fertilized the (evolution of) the definition of our programming languages, recent C++11 is designed for a very optimizing compiler. The recent style guiding or coding hints around C++11 are presupposing (and makes sense only because of) very powerful optimizations.
You still can usually invoke the compiler to spit the preprocessed form, e.g. with gcc -C -E source.c > source.i, in a seperate file (conventionally suffixed .i or .ii, and such suffixes can be known to builder like make)

A: Journey of a C Program to Linux Executable in 4 Stages :

*

*Pre-processing

*Compilation

*Assembly

*Linking

Check this link for more details C program compilation process

A: >gcc -E fname.c >fname.x /fname.x is the pre-processed output to which u r saving/
The following four things happen in the pre-processing stage.
1> header file inclusion

2>comment removal

3>macro substitution (eg if u have #fenine NUM 10, where-ever in code you have used NUM ll be replaced by 10)
4> conditional compilation (eg
#if 0
...
some code
...
#endif

since "#if 0" evaluates to 0, the code under it never executes. Therefore code under it is not included in your pre-processed output


text:
Q: Restricting Textbox input to only operator symbols I have a TextBox in my WinForms application and I have a method that I want to use to check that the user passes  +, -, *, /.
I'm using the TextBox, so the user can input an operator similar to a calculator.  I know that by default TextBoxes only accept strings and how to convert them but I'm not sure how to check to make sure the input matches the restriction that you want.
I just want to make sure they enter one of these symbols: +, -, *, /.
I don't have any code besides my TextBox in my Form and my method with nothing inside because I'm not sure how to start.
Does anyone have suggestions what I can search on Microsoft's website to read more about this or where I can watch videos about restrictions applied to a TextBox? Thanks.

A: Every time the text changes, process it to find the first permitted symbol only:
//attach this handler code to the TextChanged event
private void OperatorTextBox_TextChanged(object sender, EventArgs e){

  //if there is nothing in the box return so we don't crash
  if(OperatorTextBox.Text.Length < 1)
    return;

  //could define this elsewhere
  string permittedCharacters = "+-*/";

  //if the box already contains only one permitted char, return. this stops an endless loop
  if(OperatorTextBox.Text.Length == 1 && permittedCharacters.Contains(OperatorTextBox.Text))
    return;

  //find the first permitted char
  int index = OperatorTextBox.Text.IndexOfAny(permittedCharacters.ToCharArray());

  //and set the box contents to the permitted char. This will cause the textchanged event to raise again. Looping is prevented by the above two checks
  if(index > -1)
    OperatorTextBox.Text = OperatorTextBox.Text[index].ToString();
  else
    OperatorTextBox.Clear();

}

Satish's answer will work if the user is pressing keys, but not if they paste. Using the textchanged we can react to any mtheod of altering the text in the box, even pasting a large document in. In that case of paste this method will find the first occurrence of a permitted character and reduce the text in the box to just that character, or clear it if it's all bad input
To put this code in the text changed event handler, double click your textbox on the form designer

A: You can use Key Press event, as shown below.
First subscribe to textbox's key press event.
 textBox1.KeyPress += TextBox1_KeyPress;

In Key press Event code
 if(e.KeyChar == '+' || e.KeyChar == '-'|| e.KeyChar == '*' || e.KeyChar == '/' || e.KeyChar == '\b' ) // \b is to handle back space.
        {

        }
        else
        {
            e.Handled = true;
        }


text:
Q: Annihilators and dimensions This question is related to this question.
I have learnt from the question in the link that the equality below does not always hold. So here is my new question:
What is a necessary and sufficient condition for $\dim S+\dim {ann}(S)=\dim Y$, where $ann(S)$ is the annihilator of $S$, that is $ann(S)=\{y\in Y|B(S,y)=0\}$? Also, $X$ and $Y$ are vector spaces, and $S\leq X$ is a subspace. Where $B: X\times Y\to F$ is a bilinear map.
Thank you.

A: Pick bases for $X$ and $Y$ say $\beta=(x_1,x_2,\dots,x_m)$ and $\gamma=(y_1,y_2,\dots,y_n)$. Suppose in addition that $X$'s basis is a completion of a basis for $S$, so that $(x_1,\dots,x_\ell)$ is a basis for $S$. Write $[x]$ for a vector $x$ written as a (column) coordinate vector. We can write down a coordinate matrix for $B$, call it $[B]$ -- it's $(i,j)$-entry is $B(x_i,y_j)$. Thus $B(x,y)=[x]^T [B] [y]$.
Requiring $B(S,y)=0$ means $[x_i]^T[B][y]=0$ for $i=1,\dots,\ell$. Put another way,
$$ \left[ \begin{array}{c} [x_1]^T \\ [x_2]^T \\ \vdots \\ [x_\ell]^T \end{array}\right] [B] [y] = P[B][y] = \begin{bmatrix} 0 \\ 0 \\ \vdots \\ 0 \end{bmatrix} $$
where $P$ is the matrix obtained by stacking the transposes of coordinate vectors of $S$'s basis. The dimension of the annihilator of $S$ is the same as the nullity  of $P[B]$. Since $P$'s rows are linearly independent, $\mathrm{rank}(P)=\ell$ and so the rank of $P[B]$ is at most $\ell$. Thus its nullity is at least $n-\ell$. Therefore, $\dim(S)+\dim(ann(S)) \geq \ell+(n-\ell) = \dim(Y)$. To get equality we need $\mathrm{rank}(P[B])=\ell$.


text:
Q: Bash printf value does not show up or is cut off I trying to get a value from a command into a var
and then print it our using printf.
Problem: i got the value in the var but with printf it does not appear
or is cut off.
INFO: In my script im calling redis-cli info memory
and to check whats wrong i tried a call on vmstat -s.
Working vmstat test:
format="%-16s | %-16s"
container_name="some_name"
used_memory=$(vmstat -s | sed -n "s/^\(.*\) K used memory.*$/\1/p")
row=$(printf "${format}" "${container_name}" "${used_memory}")
echo "${row}"

Output: some_name        |      11841548
The actual script that is not working:
format="%-50s | %-16s"
container_name="totally_secret_container_name_1"
used_memory=$(docker exec -it "${container_name}" redis-cli info memory | sed -n "s/^used_memory_human:\(.*\)$/\1/p")
row=$(printf "${format}" "${container_name}" "${used_memory}")
echo "${row}"

Output:          ecret_container_name_1                    | 1.08M
Weird is than when i set the format to format="%-50s | %-1s"
then it works - the container name (left value) gets printed correctly.
What happen here?
How can i fix this?
Thanks for your time!

A: You need to remove the \r characters in the output that are causing it to go back to the beginning of the line and overwrite.
used_memory=$(docker exec -it "${container_name}" redis-cli info memory | sed -n "s/^used_memory_human:\(.*\)$/\1/p")
used_memory=${used_memory//$'\r'/}
row=$(printf "${format}" "${container_name}" "${used_memory}")

This uses the bash ${variable//old/new} replacement operator.


text:
Q: Sql Equivalent to UInt16 I know that the Sql equivalent of Int16 is SqlInt16.
But what is the Sql equivalent of UInt16, UInt32 and Uint64?

A: Except for tinyint, there are no native unsigned types in SQL server so there is no good equivalent.  The best you can do is use a bigger precision number and add a constraint on the permissible values.


text:
Q: Reading files per character with Lua (Löve API) I am trying to read files per character in Lua with the Löve API but I just can't figure out how. There must be some way to do this right? In other posts I found something about reading files per line but I really need to read them per char. Could someone please tell me how to do this?
Thanks in advance,
Leveljaap

A: If f is a file handle, then f:read(1) returns the next byte in the file or nil at the end of the file.
Note that the next byte may not be the next character if the file contains UTF-8 Unicode for instance.


text:
Q: How to create .ipa file for testing using Runner.app? I am android developer learning Flutter, and I really have some trouble trying to create debug .ipa file, for testing purposes.
So, I managed to create Runner.app file using command from Terminal:
flutter build ios --debug

The location of Runner.app file is

my_project_folder/build/ios/iphoneos/Runner.app

What to do next?
Also, is there a way to create debug .ipa file from Xcode?
Thanks.

A: You can create .ipa file by your self and send iOS build url to your client or other.
Just follow me :)
1) Generate your iOS build by below command
-> flutter build ios --release/debug
2) You will found exact path of your Runner.app Ex.
-> Built /Users/UserName/Documents/AppName/build/ios/iphoneos/Runner.app.
Just find this Runner.app file and do copy/paste it to Desktop.
3) Create folder name is "Payload" (case-sensitive) on Desktop
4) Move your Runner.app File in the "Payload" folder.
5) Compress Payload folder to default .zip
6) Convert/rename Payload.zip to Payload.ipa
That's it. Now you have to open "Diawi" and Upload the Payload.ipa on it. Wait for 100% done. Click on send button. You will find one url, Send this url to your client or any other person. They can install on his/her device.

~ PS : Make sure diawi Url valid for those UDIDs that attached with your provisioning profile. And I haven't tried these steps to upload app on TestFlight/AppStore.

A: I have a simple implementation combining a Makefile and Fastlane. This way, I can run make beta from my project directory to deploy.
./Makefile:
.PHONY: beta
beta:
    flutter build ipa --export-options-plist=ExportOptions.plist
    cd ios && fastlane beta ipa:../build/ios/ipa/YourBundleName.ipa

./ios/fastlane/Fastfile:
platform :ios do
    lane :beta do |options|
        # ... pre-delivery actions, eg: `match(type: "appstore")`
        pilot(
            ipa: options[:ipa]
            # ... the rest of your pilot configuration
        )
        # ... post-delivery actions, eg: `slack(message: "Uploaded to TestFlight")`
    end
end

Note that I use match(type: "appstore"), so that's why you see signingStyle as manual.
./ExportOptions.plist:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>compileBitcode</key>
    <true/>
    <key>method</key>
    <string>app-store</string>
    <key>provisioningProfiles</key>
    <dict>
        <key>your.bundle.identifier</key>
        <string>Your Provisioning Profile Name</string>
    </dict>
    <key>signingCertificate</key>
    <string>iOS Distribution</string>
    <key>signingStyle</key>
    <string>manual</string>
    <key>stripSwiftSymbols</key>
    <true/>
    <key>teamID</key>
    <string>YourTeamId</string>
    <key>thinning</key>
    <string><none></string>
</dict>
</plist>

A: flutter build ipa is now available and takes an optional --export-options-plist flag to make an IPA from the archive bundle. See flutter build ipa -h on the master channel for details.

A: I use the next bash-script
flutter build ios --debug
cd ios
xcodebuild -workspace Runner.xcworkspace -scheme Runner archive -archivePath Runner.xcarchive
xcodebuild -exportArchive -archivePath Runner.xcarchive -exportOptionsPlist ../scripts/exportOptions.plist -exportPath ../scripts -allowProvisioningUpdates
rm -fr Runner.xcarchive

ipa will be created at '../scripts'. You may have own path.

-allowProvisioningUpdates is using if you want xcodebuild updates certificates automaticaly.

exportOptions.plist - it's a file with distribution settings.
I use next
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>compileBitcode</key>
    <false/>
    <key>method</key>
    <string>enterprise</string>
    <key>signingStyle</key>
    <string>automatic</string>
    <key>stripSwiftSymbols</key>
    <true/>
    <key>teamID</key>
    <string>YOUR TEAM ID</string>
</dict>
</plist>

A: These are the next steps outlined in the instructions (which are found here: https://flutter.io/ios-release/):
In Xcode, configure the app version and build:
In Xcode, open Runner.xcworkspace in your app's ios folder.
Select Product > Scheme > Runner.
Select Product > Destination > Generic iOS Device.
Select Runner in the Xcode project navigator, then select the Runner target in the settings view sidebar.
In the Identity section, update the Version to the user-facing version number you wish to publish.
In the Identity section, update the Build identifier to a unique build number used to track this build on iTunes Connect. Each upload requires a unique build number.

Finally, create a build archive and upload it to iTunes Connect:
Select Product > Archive to produce a build archive.
In the sidebar of the Xcode Organizer window, select your iOS app, then select the build archive you just produced.
Click the Validate… button. If any issues are reported, address them and produce another build. You can reuse the same build ID until you upload an archive.
After the archive has been successfully validated, click Upload to App Store…. You can follow the status of your build in the Activities tab of your app's details page on iTunes Connect.


text:
Q: How to get date representing the first day of a month? I need functionality in a script that will enable me to insert dates into a table.
What SQL do I need to insert a date of the format
01/08/2010 00:00:00

where the date is the first day of the current month. What do I need to change order that I can specify the month value? Thanks

A: The best and easiest way to do this is to use:
SELECT DATEADD(m, DATEDIFF(m, 0, GETDATE()), 0)

Just replace GETDATE() with whatever date you need.

A: select cast(cast(datepart(year,getdate()) as char(4))
+ '/'
+ cast(datepart(month,getdate()) as char(2))
+ '/01' as datetime)

A: Here is a very simple way to do this (using SQL 2012 or later)
datefromparts(year(getdate()),month(getdate()),1)

you can also easily get the last day of the month using
eomonth(getdate())

A: The accepted answer works, and may be faster, but SQL 2012 and above have a more easily understood method:
SELECT cast(format(GETDATE(), 'yyyy-MM-01') as Date)

A: SELECT DATEADD(day,1-DATEpart(day, GETDATE()),GETDATE())

A: i think normally converts string to MM/DD/YY HH:mm:ss, you would need to use 08/01/2010 00:00:00
Sorry, misunderstood the question, looking to see if you can change the order for strings.
This may be what you want:
declare @test as date

select @test = CONVERT(date, '01/08/2010 00:00:00', 103)
select convert(varchar(15), @test, 106)

A: Modified from this link.  This will return as string, but you can modify as needed to return your datetime data type.
SELECT CONVERT(VARCHAR(25),DATEADD(dd,-(DAY(GetDate())-1),GetDate()),101)

A: SELECT  CAST(FLOOR(CAST(DATEADD(d, 1 - DAY(GETDATE()), GETDATE()) AS FLOAT)) AS DATETIME)

A: SELECT DATEADD(m, DATEDIFF(m, 0, GETDATE()), 0)

This worked perfectly.  I actually added a Case statement.  Thanks for the post:
SELECT Case(DATEADD(m, DATEDIFF(m, 0, GETDATE()), 0) as Date)

A: As of SQL Server 2012 you can use the eomonth built-in function, which is intended for getting the end of the month but can also be used to get the start as so:
select dateadd(day, 1, eomonth(<date>, -1))

If you need the result as a datetime etc., just cast it:
select cast(dateadd(day, 1, eomonth(<date>, -1)) as datetime)

A: Get First Day of Last Month
Select ADDDATE(LAST_DAY(ADDDATE(now(), INTERVAL -2 MONTH)), INTERVAL 1 DAY);
Get Last Day of Last Month
Select LAST_DAY(ADDDATE(now(), INTERVAL -1 MONTH));

A: ... in Powershell you can do something like this:
Get-Date (get-Date ((Get-Date) ) -format MM.yyyy)
... for the last month do this:
Get-Date (get-Date ((Get-Date).AddMonths(-1) ) -format MM.yyyy)
... or for custom Date do this:
Get-Date (get-Date ((Get-Date  12.01.2013) ) -format MM.yyyy)
Im sure theres something like this possible ...
Gruß

A: Very simple piece of code to do this
$date - extract(day from $date) + 1
two ways to do this:

*

*my_date - extract(day from my_date) + 1

*'2014/01/21' - extract(day from '2014/01/21') + 1

A: select last_day(add_months(sysdate,-1))+1 from dual;


text:
Q: Float blocks of text over images in left and right columns I am trying to recreate the attached screen shot in wordpress and I'm having some css issues.

As you can see there are two columns with very simular content.
At present I have got this far:

 .race-tri {
   width: 570px;
   position: relative;
 }
 .banner_txt {
   width: 250px;
   background: #F08E03;
   padding: 5px 15px;
   color: #ffffff;
   position: absolute;
   top: 150px;
   left: 0;
 }
 .race-tri h3 {
   text-transform: uppercase;
   margin-bottom: 15px;
   font-weight: 800;
 }

RACES

Throughout the year Tri Team Glos runs various events, notably the TTG Gloucester Triathlon and the TTG Newent Duathlon.

Our Triathlon is a pool based Sprint race with a 400m Swim and a two lap 28km bike course finished off with a 6km run and will take place on Sunday 29th May 2016.

Our duathlon comprises a 5k run, 18k bike and 5k run. Next year's event will take place on 3rd April 2016,

For those wishing to enter the Tri Team Glos' Children's Race, please click here.

Glocester triathlon

    May 25th, 2016
    Triathlon

Swim: 1km

Bikd: 20km

Run: 5km

  ENTER EVENT
  MORE INFORMATION

Newent Duathlon

    April 16th, 2017 (TBC)
    Duathlon

Swim: 1km

Bikd: 20km

Run: 5km

  ENTER EVENT
  MORE INFORMATION

Ignoring the main background image and some the smaller styling issues, I am having issues floating the two blocks side by side, whilst floating the inner orange text block.
I thought I could achieve this by making the background relative and then the inner text block absolute. Hoping it would be absolute within the block, not the page.
Many thanks in adavance for suggestions.

A: @Dhaval Chheda recommended looking at flexboxes, which I'd recommend too - they'd be a better way to get what you're looking for.
.container {
  display: flex;
}

See this link for a way to divvy up the structure of the blocks, and this fiddle for it in action. This way you'll be able to have some more precise control over the layout of the page.


text:
Q: can't access MySQL database for Drupal I just installed an instance of Drupal on a shared web hosting account earlier today (via softaculous). I set some things different from how I wanted it the first time, so I deleted the directory it installed in, and the database and user that were created for it, and then tried again. Shortly after starting to work with the second install, I got the error described below, and I hadn't done much yet so I re-installed again. Now I'm on my third install, with all three using the same database and user name (I deleted the old MySQL database and user through cPanel before each install), and the same error is happening again.
When I try to access any of the drupal pages, I get this:
PDOException: SQLSTATE[HY000] [1045] Access denied for user
'mareofni_twocit'@'localhost' (using password: YES) in
lock_may_be_available() (line 167 of
home/mareofni/public_html/twocities/includes/lock.inc).

The "MySQL Databases" section of cPanel says that the database and user still exist. When I use the "check database" feature, it gives this error message:
Error from MySQL query: DBD::mysql::db do failed:
Unknown database 'mareofni_twocit'Failed to use
mareofni_twocit: Unknown database 'mareofni_twocit'

"Repair database" in cPanel doesn't fix the problem, and gives the same error message.
Error from MySQL query: DBD::mysql::db do failed:
Unknown database 'mareofni_twocit'Failed to use
mareofni_twocit: Unknown database 'mareofni_twocit'

I tried looking at the databse in phpMyAdmin, but phpMyAdmin doesn't list the database - like it can't tell that it exists.
Is there anything I can do to fix this problem myself, or prevent it happening again the next time I install Drupal? Some insight on what the problem is would also be helpful.
(Line breaks in the error messages are mine, added for readability.)

A: I've figured out that I cannot create database users who are able to drop databases, and the user I access phpMyAdmin through also cannot drop databases. Since phpMyAdmin couldn't find the database at all, I think the database must have been dropped or corrupted (rather than all the tables dropped or something).
This can't be something that Drupal did, since the Drupal user didn't have permission to drop the database. (Unless Drupal managed to corrupt the database somehow; I don't know enough about how that works to be sure of whether it's possible.) I suspect there's a bug in cPanel, Softaculous, or some other software put there by the hosting company that caused it. Maybe it didn't like that I re-created the DB immediately after deleting it.
I'm trying again with a different database name and crossing my fingers.


text:
Q: Trying to pass props down to child component/route but ".children" is returning null I made comments in the code. I tried to make it as straightforward as possible. For some reason ".children" is returning "null" inside "Index.js" or CompetitionsIndex component, it should not do this because ViewCompetition component is the child as seen in "routes.js"

// routes.js

<Router history={hashHistory}>
    <Route   path='/'                        component={Main} >
      <IndexRoute                            component={Home} />
      <Route path="login"                    component={Login} />
      <Route path="logout"                   component={Logout} />
      <Route path="register"                 component={Register} />
      <Route path="CompetitionIndex"         component={CompetitionIndex} >
        <Route path="/ViewCompetition/:id"   component={ViewCompetition} />
   </Route>
      <Route path="CreateCompetition"        component={CreateCompetition} />
      <Route path="EditCompetition/:id"      component={EditCompetition} />
      <Route path="dashboard"                component={Dashboard} onEnter={requireAuth} />
    </Route>
  </Router>

// Main.js

export default class Main extends React.Component {
  constructor(props) {
    super(props)

    this.state = {
      loggedIn: false,
      userRole: null
    }
  }

  // ... methods and stuff

  render() {
    let childrenWithProps = React.cloneElement(this.props.children, {userRole: this.state.userRole});

    return (

            {childrenWithProps}

    )
  }
}

// Dashboard.js

export default class Dashboard extends React.Component {
  render() {
    let userRole = this.props.userRole // Works Like a charm!!!

    return(

 DASHBOARD (A Secure Route)

    )
  }
}

// Everything above works great!
// Now check out the same exact pattern below
// I'm trying to pass props(editableDoc) from CompetitionIndex to it's child component/route ViewCompetition
// The same EXACT way I passed props(userRole) from Main to it's child component/route dashboard

// Index.js

export default class CompetitionIndex extends React.Component {
  constructor(props) {
    super(props)

    this.state = {
      error: false,
      docList: [],
      editableDoc: []
    }
  }

  handleView(docId) {
    db.get(docId).then((doc) => {

      this.setState({
        editableDoc: doc
      })
      this.context.router.push(`/ViewCompetition/${doc._id}`)
    }).catch((err) => {
      console.log(err)
      this.setState({
        error: err
      })
    })
  }

  componentDidMount() {
 // some code
  }

  render() {
    let FML = React.cloneElement(this.props.children, {editableDoc: this.state.editableDoc});

    return(

{FML}

    )
  }
}

// Before even getting to render() the View.js below I get this shitty Error
// bundle.js:967 Uncaught TypeError: Cannot read property 'props' of null
// After console logging a bunch I realize everything is ok until I call `.children`, so there's no children?
// How da puck is that possible When I'm doing the EXACT same thing with Main and dashboard...???

// View.js

export default class ViewCompetition extends React.Component {
  render() {
    console.log("editableDocument", this.props.editableDoc)
    return(

    )
  }
}

A: I solved the problem by adding an <IndexRoute component={whatever} /> inside of <Route component={CompetitionIndex} >
This enabled me to pass props down from "CompetitionIndex" to "ViewCompetition"
Why this fixes the problem I'm not exactly sure. All I can think of is if you're nesting routes each level has to have an <IndexRoute/> if you want to pass props down from the parent.


text:
Q: Swift 3.0 - How to build Sourcekit and Sourcekitten in Ubuntu 14.04? What are the steps in building Sourcekit and Sourcekitten for the stable release version of Swift 3.0? Thanks in advance.
Note: Dependencies and other tools for building are already installed as per https://github.com/apple/swift

A: This is duplicate to Building Swift SourceKit on Linux
Updated Nov.24, 2016.
Build Sourcekit
The official branch of swift may still have the issue https://bugs.swift.org/browse/SR-1676. But Norio Nomura maintained a docker building environment here https://github.com/norio-nomura/docker-sourcekit-builder/
If you don't want to build it yourself, just download the package with sourcekit https://github.com/norio-nomura/docker-sourcekit-builder/releases
You may have to put libsourcekitdInProc.so under lib directory of this package into your lib path, or the lib directory into your LD_LIBRARY_PATH
Build SourceKitten
SourceKitten has Linux support now. Download the git source code and use swift build.


text:
Q: Create a print function that takes an ostream as an argument and writes to that stream Im currently anwsering exercise questions concerning operator overloading in C++. I have a question:
Create a simple class containing an int and overload the operator+ as a member function. Also provide a print( ) member function that takes an ostream& as an argument and prints to that ostream&. Test your class to show that it works correctly.
I can create the class and write the operator+ function alright but I really dont understand the second part of the question. So far in my study of c++ I havent really come across ostream's and as such am not sure if its possible to explicitly create such a stream. I have tried using:
std::ostream o;
However this produces an error. Could someone please enlighten me on how I should create this function please?

A: You don't create an ostream, you create an ostream reference, like your exercise question said.  And you do it in the parameter list of your print function, i.e.
void print(std::ostream & os);

Then you can call that function, passing cout or any other object of a class derived from ostream(ofstream, ostringstream, etc...)

A:
So far in my study of c++ I havent really come across ostream's and as
  such am not sure if its possible to explicitly create such a stream. I
  have tried using: std::ostream o;

You must have missed something, because ostreams are important.  std::cout is a variable of type std::ostream by the way.  Usage is more or less like this
#include <iostream> //defines "std::ostream", and creates "std::ofstream std::cout"
#include <fstream> //defines "std::ofstream" (a type of std::ostream)
std::ostream& doStuffWithStream(std::ostream &out) { //defines a function
    out << "apples!";
    return out;
}
int main() {
    std::cout << "starting!\n";
    doStuffWithStream(std::cout); //uses the function

    std::ofstream fileout("C:/myfile.txt"); //creates a "std::ofstream"
    doStuffWithStream(fileout); //uses the function

    return 0;
}


text:
Q: access denied with mysql database I want to install a CMS, first time I tried to install "Silver Stripe CMS" but the installation hangs at the database it shows me this error:
I couldn't find a database server on 'localhost': Access denied for user 'root'@'localhost' (using password: NO)
Then I tried to install the CMS "Modx" still hangs at the database the message this time is:
Connexion au serveur MySQL:
No processor specified!
I tried to reinstall PhpMyAdmin, I affice this error:

Une erreur s'est produite lors de la création de la base de données.
ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using
  password: YES)
Vous pouvez soit recommencer soit abandonner l'opération. Si vous
  choisissez « Recommencer », la mise à jour sera tentée à nouveau en
  vous       posant à nouveau les questions de configuration. Avec
  l'option                 « Recommencer avec les mêmes réglages », la
  mise à jour sera tentée            immédiatement. Avec le choix
  « Abandonner », la mise à jour échouera et        vous devrez revenir
  à la version précédente, désinstaller et
  reconfigurer ce paquet, à moins d'effectuer vous-même les opérations
  nécessaires pour continuer à l'utiliser. Enfin, le choix « Ignorer »
  poursuivra les opérations en ignorant les erreurs ultérieures issues
  de        dbconfig-common.
<Ok>

Although I connect well with my phpmyadmin login as root and my password no problem

A: I think the giveaway is in this bit:

Access denied for user 'root'@'localhost' (using password: NO)

It looks as if the password isn't set for your CMS that you have installed. I am not familiar with silverstripe, but it seems that you will need to edit a file somewhere to tell it the password.
Also, using the root user is probably not advisable, I would suggest creating a secondary user on your database with the permissions you want and use that account in the CMS.

A: Try to connect from command-line, if you're logged in as root simply type mysql and enter. if it works, the problem is on the application level.
Look for silver-stripe configuration file:
<your app root folder>/conf/ConfigureFromEnv.php
and make sure to set the credentials right, in lines:
/* Database connection */
define('SS_DATABASE_SERVER', 'localhost');
define('SS_DATABASE_USERNAME', 'root');
define('SS_DATABASE_PASSWORD', '');

I agree with my friend Fluffeh, you should not use root - better create a dedicated user for Silver Stripe.


text:
Q: How important is optimization? I got into a bit of a debate yesterday with my boss about the proper role of optimization when building software. Essentially, his position was that optimization needs to be a primary concern during the entire process of development.
My opinion is that you need to make the right algorithmic decisions during development, but you should never be counting cycles during development. In fact, I feel so strongly about this I had to walk away from the conversation. I've seen too many bad programming decisions in the name of "optimization", and too much bad code defended with the excuse "this way is faster".
What does the StackOverflow.com community think?

A: Optimization is almost tautologically a tradeoff: you gain runtime efficiency at the cost of other things (readability, maintainability, flexibility, compile times, etc.).  As such, it's really never a good idea to do unless you know what the tradeoff is and why it's worthwhile.
Even worse, thinking about "how do I do X fast" can be very distracting.  To much energy in that direction can easily lead to you misisng out on method Y which is much better (and often faster --- this is how "optimization" can make your code slower).  Particularly if you do too much of this on a big project from the beginning, it represents a lot of momentum.  If you can't afford to overcome that momentum, you can easily become locked into a bad design because you can't afford the time to restructure it.  This way lie dragons
What your boss may be thinking of is more of an issue of writing bad code via inappropriate representations and algorithms.  It's not really the same thing as optimizing, but an approach where you pay no attention whatsoever to appropriate data structures etc. can result in a codebase that is slow everywhere, and (much like the above "lock in") requires heroic effort to fix.
In general though, premature optimization really honestly is a terrible idea.  Particularly when you end up with a complex, finely tuned, well documented (because that's the only way you can understand it) piece of code you end up not using anyway.  And that's not even getting into the issue of subtle bugs that are often introduced when "optimizing"
[edit:  pshaw, of course a Knuth quote encapsulates this well.  That's what I get for typing too much]

A: Engineer throughout, optimize at the end.

A: Since with going with pithy, I'll say that optimization is as important as the impact of not doing it.

A: I think the "premature optimization is root of all evil" has to be understood literally - it does not say when is premature, and does not say you should optimize only at the end. Just not too early. Also, the "use the right algorithm, O(n^2) vs O(N)" is a bit dangerous if taken literally - because for many problems, the N is actually small, etc...
I think it depends a lot of the type of software you are doing: some software are such as every part is very independent, and can be optimized separately. But that's not always the case. For many (most ?) applications, speed just does not matter at all, the brute force but obviously correct way is the best one. But for projects where speed matters, it often has to be taken into account early - maybe that's another possible interpretation of Knuth's saying: many applications don't need to be optimized at all, just know which ones need and plan ahead.

A: Optimization is a primary concern through development when you have a good reason to expect that performance will be unfixably bad if optimization is a secondary concern.
This depends a lot what kind of code you're writing, but there are often better reasons to believe that your code will be unfixably difficult to use; or maintain; or full of bugs; or late; if all those things become secondary to tweaking performance.
Bad managers say, "all of those things are our primary concerns". Good managers work to find out which are dangers for this project.
Of course, good design does have to consider all these things, and the earlier you have a back-of-the-envelope estimate of any of them, the better. If all your manager is saying, is that if you never think about how fast your code will run then too much of your code will be dog-slow, then he's right. I just wouldn't say that makes optimization your "primary" concern.
If the USP of your software is that it's faster than your competitors', then optimization is a primary concern. With experience, you can often predict what sorts of operations will be the bottlenecks, design those with optimization in mind right from the start, and more-or-less ignore optimization elsewhere. A lot of projects won't even need this: they'll be fast enough without much effort, provided you use sensible algorithms and don't do anything stupid. "Don't do anything stupid" is always a primary concern, with no need to mention performance in particular.

A:
"We should forget about small efficiencies, say about 97% of the time: premature optimization is the root of all evil. Yet we should not pass up our opportunities in that critical 3%."

- Donald Knuth

A: I think the premature optimization quote is used by too many to avoid thinking about the hard stuff concerning how well the application will run. I guarantee the users want you to think about how to design it so it will run as fast as possible.
This is not to say you should be timing everything, but the design phase is the easiest place to optimize and not cost lots of time later.
There are often several ways to do anything, you should pick in the design phase the one which is most likely to perform the best (if it turns out to be one of the times when it isn't the best, then optimize later). This should trump the need to have easy to read code.
If you aren't considering performance in the design phase, you aren't going to have a well designed system. That doesn't mean it should be the only concern (although in a database I'd rate it as 3rd in importance, right after data integrity and security), but trying to fix a system where poorly performing techniques were used throughout because the developers thought they were easier to understand is a nightmare. Being a user of such a system where you have to wait for minutes everytime you want to move from one screen to another is a nightmare (developers reallly should spend all day everyday for at least a week, using their systems!) for everyone who is stuck with the badly designed system. It costs less to design properly  than to fix later and considering performance is critical to designing properly.
I work somewhere where the orginal developers drank the koolaid about premature optimization and did everything the way they thought was simplest (but which in almost every case was the wrong choice from a performance perspective). Now we are at 10 times the size we were three years ago and every screen on every website takes 30 seconds or so to load (or worse times out) and we are losing customers because of it. But changing it will be too hard because at the base they designed the database without considering how it would perform and redesigning a database with many many gigabytes of data into a new structure is way too time consuming and costly. If it had been designed to perform from the start it would be both easier to maintain and faster for the clients. We aren't talking about the need to performance tune the top 10 slowest queries here, we are talking about the fact that the overall structure requires a drastic change (one that would affect virtually every query against the system) to perform well.
Yes don't do micro optimization until you nmeed to, but please do the macro stuff. Consider if is this the best way before you commit to the path. Don't write cursors to hit tables with millions of records when a set-based statement will do. Don't try to have as few tables as possible becasue that seems to be a more elegant solution when the tables are storing disparate items (such as people, places, and vehicles) causing every single query to hit the same table and causing every delete to check all sorts of foreign key tables that will not ever have a record for that type of entity (it takes minutes to delete one record from the main table in our database, it's a real joy when something goes wrong in an import (bad data from a client usually) and we have to delete 200,000 let me tell you).

A: I think that code needs to be, first and foremost, readable and understandable. So, optimisations that are done, should not be at the expense of readability. However, optimisation is often a trade-off.
Whether or not you should optimise your code depends on your application domain. If you are working on an embedded processor with only 8Mb of memory, then optimisation is probably something that every team member needs to keep in mind, when writing code - optimising for space vs speed.
However, pre-mature optimisation is not useful unless your system has been clearly spec'ed and understood. This is because most programmers do not make good optimisation decisions unless they can factor in the influence of the overall system, including processor architectural factors such as cache memory, hardware threads, pipelines, etc.

A: From 2 years of building highly optimized Java code (and that needed to be optimized that way) I would say that there is a time-spent rule that governs optimization:

*

*optimizing on the spot: 5%-10% of your development time, because you have to do it countless times (every single time you have to amend your design)

*optimizing just when you have had it working: 2% of your development time (you do it only once)

*going back to it and optimizing when it's too slow: 30% of your development time, because you have to plunge yourself back into the system

SO I would come to the conclusion that there is a right time and a right way to optimize: do it entity by entity (class by class, if you have classes that have a single, well defined job to do, and can be tested and optimized), test well, make sure the logic is working, optimize just afterward, and forget about that entity's implementation details forever.

A: *

*When developing, just keep it simple. IMHO, most performance problems are caused by over-engineering - making mountains out of molehills, often because of wanting "the right algorithm".

*Periodically, stress test with a big data set, profiling or (my favorite technique) manual random sampling. You find a problem, you fix it. You find another, you fix it.
That way you avoid creating slugs (slowness bugs), and when they do arise, you kill them.
Added: If I can just elaborate on point 1. OO is seemingly the law of the land, and it certainly has good reasons behind it. Unfortunately it causes many young programmers to feel that programming is all about having lots of data structure, with layers upon layers of abstraction. Not that those are inherently bad, but combine that with the natural tendency to assume that the time something takes is roughly proportional to the number of characters you have to type to invoke it, and that this tendency multiplies over the layers (and besides, the machines are really fast), it's easy to create a perfect storm of cycle-waste.

A: Quote from a friend:  "It's easier to make a working system efficient than to make an efficient system work".
I think it is important to use smart practices and patterns from the start, but get the system actually running for small test cases then do performance analysis.  Frequently the areas of code that have poor performance aren't anticipated at the beginning, so get some real data and then optimize the bottlenecking 3% (or 20%, or whatever it is).

A: I think your boss is a lot more right than you are.
Allt too often the user experience is lost only to be "rediscovered" at the last possible moments when performance activites are prohibitively costly and inefficient. Or when it is discovered that the batch program that will process today's transactions requires forty hours to run.
Things such as database organization, when and when not to do which SELECTs are examples of design decisions that can make or break an application. Still you run the risk of a single programmer deciding to to otherwise, misinterpret or simply not understand what to do. Following-up on performance during an entire project decreases the risk that such things will happen. It also allows design decisions to be changed when there is a need for that without puting the entire poroject at risk.
"You need to make the right algorithmic decisions during development" is certainly true yet how many mainstream programmers are able to do that? Browsing the net for information does not guarantee finding a high quality solution. "Right" could be interpreted as meaning that it is ok to choose a poor algorithm because it is easy to understand and implement (= less development time, lower cost) than a more complicated one (= more development time, higher cost).
The pendulum of quantity vs quality is almost always on the quantity side because more code per hour or faster development time means money in the short term. The quality side means money in the long term.
EDIT
This article discusses performance and optimization quite thoroughly.
Performance preacher Rico Mariana sums it up in the short statement "never give up your performance accidentally."

A: Premature optimization is the root of all evil...There is a fine balance between, but I would say 95% of the time you need to optimize at the end; however, there are decisions you can make early on to help prevent issues. For example assume we are talking about an e-commerce web site. You have a requirement to display the catalog. Now you can grab all 100,000 items and display 50 of them, or you can grab just 50 from the database. These type of decisions should be made up front.
Cycle counting should only be done when a problem has been identified.

A: Your boss is partly right, optimisation does need to be considered throughout the development lifecycle but it is rarely the primary concern. Also, the term 'optimisation' is vague - it's an adjective, 'optimise for ...' which could be 'memory', 'speed', 'usability', 'maintainability' and so on.
However, the OP is right that counting cycles is pointless for many projects. For most PC applications the CPU is never the bottleneck. Also, the IA32 is not consistent - what worked well on one architecture, performs poorly on another. Cycle counting should only ever be done when it will actually make a difference - usually in CPU limited code or code with very specific timing needs.
Optimisation, of any kind, must always be driven by hard evidence. Never assume anything about the system or how the code is behaving. In an ideal world, application performance / constraints will be specified in the initial product design and tools to monitor the application's performance during development will be added early on in the development phase to guide the programmers as the product is made.


text:
Q: Why light rays gets scattered when it enters a translucent window pane? Consider the light source is the light post, outside the window of my house (Pic 1). When the rays from the light post enters through the window pane which is translucent gets scattered and forms a prominent design (Pic 2). Why does this happen?

A: Your window is made of patterned glass, with regular changes in thickness. This is designed to diffuse light in order to prevent people outside from seeing what's inside (or you inside from seeing out; I don't know what your neighborhood is like).
In your case, the patterns are extremely regular, so that each incoming beam of light will get spread into a wide, regular pattern, which you'd see if you shone a laser pointer through the window onto a sheet of paper (perhaps moving the laser about a bit to catch every part of the pattern).
Here, though, you have light hitting the entire window in parallel beams (from that distant streetlight), and a single recipient (your eye). This means you'll see a bright point at every location where the patterned glass bends the beam to point exactly at your eye, which produces the pattern of light that you see.


text:
Q: How to model and create a custom deck of cards in rails? I'm trying to model a card game in order to learn Rails. This is different than a standard deck of playing cards in that there can be multiple copies of a card in the deck. I'm running into problems while trying to initialize the deck. So far I've got a basic Card model with various attributes (such as copies_in_deck) but no associations. A DeckCard model which represents the cards in the deck (this is due to having multiples of the same card in the deck):
class DeckCard < ActiveRecord::Base
  belongs_to :card
  belongs_to :deck
end

These DeckCards will eventually have attributes reflecting position; such as in discard pile, in draw pile, etc.
A Deck model with
belongs_to :game
has_many :deck_cards

I'm trying to inialize the deck and am having various problems. I'm trying the following in Deck
def initialize
  @cards = Card.find(:all)
  @cards.each do |card|
    # eventually another loop here on copies_in_deck
      @deck_cards.build(card)
  end
end

When I do Deck.new I get an error on nil.build.  Why is @deck_cards nil?
I'm using InstantRails2, which has rails 2.0.2. I found this article  about creating multiple models in one action, so I tried using Deck.create! instead, and got an error about the wrong number of arguments.
Any suggestions?

A: class Deck < ActiveRecord::Base
  belongs_to :game
  has_many :deck_cards

  # To create new: Deck.new.build_deck
  def build_deck
    Card.find(:all).each do |card|
      self.deck_cards << DeckCard.new(:card => card)
    end
  end
end

A: subclasses of ActiveRecord should not define an initialize method since ActiveRecord takes care of that for you.
Sounds like you want one record per card. And the Model DeckCard can hold more than one pack of cards at a time.
Re:  Why is @deck_cards nil?
Because you haven't set it anywhere.
@deck_cards is an instance variable. You're trying to call the build method on it, but you haven't set it to anything. You should be calling the build (or create or new method) on the class DeckCard.
If you want to create and save a card in the DeckCard model:
    DeckCard.create(card) # not @deck_cards.build(card)
Larry

A: Don't use #initialize on objects that inherit from ActiveRecord::Base.  It'll break all sorts of internal Rails magic.  Instead, use the #after_initialize callback documented here: http://api.rubyonrails.org/classes/ActiveRecord/Callbacks.html
Note that after_initialize is called after finds as well as on newly created objects, so you'll want to wrap your initialization code to make sure that the object hasn't been saved previously (use #new_record?):
def after_initialize
  if new_record?
    # initialize deck_cards here.
  end
end

In the past, I've taken this alternate approach with a nicer syntax, but be warned that it doesn't kick in until you try to save or validate the record.
before_validation :build_default_associations, :if => :new_record?

def build_default_associations
  # initialize default associations here.
end


text:
Q: Epson Image scanning in Debian I couldn't get my Epson XP-430 to work on an Ubuntu 16.04 based system.
Saw errors like:
Could not send command to scanner
no devices found
And this is after installing all the official drivers here:
http://support.epson.net/linux/en/imagescanv3.php?version=1.3.28

A: Turns out that you need to add the scanner into the config manually, especially if it is connected via network.
CTI on the Linux Mint forums was especially helpful:
edit the file /etc/sane.d/epkowa.con and set/add the line
net <your epson LAN address>
e.g. in my case
net 192.168.1.137

src: https://forums.linuxmint.com/viewtopic.php?t=232860


text:
Q: python get max and min values across mutiple columns while grouping a dataframe This query is related to How to get the max value of a multiple column group-by pandas? and well as Pandas DataFrame find the max after Groupby two columns and get counts
I am trying to create min and max values from two columns within grouped data
I have a data set in this shape
measure     measure_group     route     year      actual     budget
AC          electrification   A         20182019  103        99
AC          electrification   A         20192020  110        122
AC          electrification   B         20182019  9          10
AC          electrification   B         20192020  55         50
HV          electrification   A         20182019  2          10
HV          electrification   A         20192020  7          15
HV          electrification   B         20182019  67         10
HV          electrification   B         20192020  100        115
cat 1       track             A         20182019  10         15
cat 1       track             A         20192020  111        25
cat 1       track             B         20182019  55         16
cat 1       track             B         20192020  75         175
cat 2       track             A         20182019  84         5
cat 2       track             A         20192020  125        1005
cat 2       track             B         20182019  7          4
cat 2       track             B         20192020  15         25

What I would like to have is as new columns the min and max of [actual, budget] for each combination of measure, measure_group, route, something like this
measure     measure_group     route     year      actual     budget  min  max
AC          electrification   A         20182019  103        99      99   122
AC          electrification   A         20192020  110        122     99   122
AC          electrification   B         20182019  9          10      9    55
AC          electrification   B         20192020  55         50      9    55
HV          electrification   A         20182019  2          10      2    15
HV          electrification   A         20192020  7          15      2    15
HV          electrification   B         20182019  67         10      10   115
HV          electrification   B         20192020  100        115     10   115
cat 1       track             A         20182019  10         15      10   111
cat 1       track             A         20192020  111        25      10   111
cat 1       track             B         20182019  55         16      16   175
cat 1       track             B         20192020  75         175     16   175
cat 2       track             A         20182019  84         5       5    1005
cat 2       track             A         20192020  125        1005    5    1005
cat 2       track             B         20182019  7          4       4    25
cat 2       track             B         20192020  15         25      4    25

I've tried various combination of df.groupby df_remapped['min'] = df_remapped.groupby(['Measure','measure_group','route'])[['Actual','Budget']].transform('min')  , but this return a value error: Wrong number of items passed 2, placement implies 1  I have a sense I'm trying to return the two columns into the one new column.
I did consider generating a free-standing dataframe, and then rejoining to the original dataframe using join on the common index, but this feels like a long-winded workaround....
Any pointers to possible approaches would be appreciated.  It's odd that most of the examples of aggregation are for single columns only.

A: You can melt the DataFrame so that you consider either 'actual' or 'budget' when calculating the min or max. Then group the melted DataFrame and merge back.
id_vars = ['measure', 'measure_group', 'route']

df1 = (df.melt(id_vars=id_vars, value_vars=['actual', 'budget'])
         .groupby(id_vars)['value']
         .agg(['min', 'max']))

df = df.merge(df1, how='left', on=id_vars)

   measure    measure_group route      year  actual  budget  min   max
0       AC  electrification     A  20182019     103      99   99   122
1       AC  electrification     A  20192020     110     122   99   122
2       AC  electrification     B  20182019       9      10    9    55
3       AC  electrification     B  20192020      55      50    9    55
4       HV  electrification     A  20182019       2      10    2    15
5       HV  electrification     A  20192020       7      15    2    15
6       HV  electrification     B  20182019      67      10   10   115
7       HV  electrification     B  20192020     100     115   10   115
8     cat1            track     A  20182019      10      15   10   111
9     cat1            track     A  20192020     111      25   10   111
10    cat1            track     B  20182019      55      16   16   175
11    cat1            track     B  20192020      75     175   16   175
12    cat2            track     A  20182019      84       5    5  1005
13    cat2            track     A  20192020     125    1005    5  1005
14    cat2            track     B  20182019       7       4    4    25
15    cat2            track     B  20192020      15      25    4    25


text:
Q: Recursive/Hierarchical Query in LINQ Scenario is,
im using EntityFrame Work 6. I have a DB have table having structure below.
cat_id     geo_id     parent_id geo_name
   Root       1       NULL      Pakistan
   Province   2        1        Punjab
   District   3        2        Attock
   City       4        3        Attock
   City       5        3        Fateh Jang
   City       6        3        Hasan Abdal

Table have hierarchical data in relational form,as you can see.
I want to traverse this hierarchy, want to specific parent level, If im at geo_id 6 then I want to go parent_id 3 and get value Attock or want to go to parent_id 2 and want to get value Punjab.
Moral of the story is,standing at any child,want traverse till specified parent or grand parent,not entire hierarchy. Below is code I have tried but it gives me only its immediate parent.
More Shortly, Want a LINQ query,which will return name of specified parent or grand parent,For Example. I can ask my query, "hey! im Hasan Abdal(City),tell me my Province"
Province = (from cp in db.geo_hierarchy
                                                     join mp in db.geo_hierarchy on cp.parent_id equals mp.geo_id
                                                     where cp.geo_name == risk.geo_hierarchy.geo_name
                                                     select mp.geo_name).FirstOrDefault()

see full code below,it used in inside LINQ query's select clause
 Risklists = (from risk in db.risk_cat_detail
            where risk.occurance_date.Value.Year==2014 && risk.occurance_date.Value.Month>=6 && risk.occurance_date.Value.Month<=9
                                 select new risk_cat_detail_contract()
                                 {
                                     cat_id = risk.cat_id,
                                     catdesc = risk.category_main.cat_name,
                                     risk_cat_detail_id = risk.risk_cat_detail_id,
                                     trans_date = risk.trans_date.Value,
                                     occurance_date = risk.occurance_date.Value,
                                     occurance_time = risk.occurance_time,

                                     geo_id = risk.geo_id,
                                     geo_desc = risk.geo_hierarchy.geo_name,
                                     Province = (from cp in db.geo_hierarchy
                                                 join mp in db.geo_hierarchy on cp.parent_id equals mp.geo_id
                                                 where cp.geo_name == risk.geo_hierarchy.geo_name
                                                 select mp.geo_name).FirstOrDefault()

                                 }).ToList<risk_cat_detail_contract>();

Help me out,Thanks in Advance

A: Try this:
var geo_hierarchy = new []
{
    new { cat_id = "Root", geo_id = 1, parent_id = (int?)null, geo_name = "Pakistan", },
    new { cat_id = "Province", geo_id = 2, parent_id = (int?)1, geo_name = "Punjab", },
    new { cat_id = "District", geo_id = 3, parent_id = (int?)2, geo_name = "Attock", },
    new { cat_id = "City", geo_id = 4, parent_id = (int?)3, geo_name = "Attock", },
    new { cat_id = "City", geo_id = 5, parent_id = (int?)3, geo_name = "Fateh Jang", },
    new { cat_id = "City", geo_id = 6, parent_id = (int?)3, geo_name = "Hasan Abdal", },
};

var map = geo_hierarchy.ToDictionary(x => x.geo_id);

Func<int, string, string> up = null;
up = (geo_id, cat_id) =>
{
    var record = map[geo_id];
    return
        record.cat_id == cat_id
            ? record.geo_name
            : (record.parent_id.HasValue
                ? up(record.parent_id.Value, cat_id)
                : null);
};

var result = up(5, "Province"); // -> "Punjab"


text:
Q: Unreadable: bootstrap-sprockets only after git merge I'm new to RoR and going through Hartl's Rails Tutorial.  After completing Chapter 5.4, all tests pass:
6 tests, 14 assertions, 0 failures, 0 errors, 0 skips

Immediately afterwards, I continue to Chapter 5.5 instructions:
$ git add -A
$ git commit -m "Finish layout and routes"
$ git checkout master
$ git merge filling-in-layout
$ rails test

But now the tests return:
6 tests, 0 assertions, 0 failures, 6 errors, 0 skips

With all errors containing:
ActionView::Template::Error: File to import not found or unreadable: bootstrap-sprockets.

Also I'm running this on Cloud9 IDE
What gives?

A: try running bundle install in your master branch folder as I can see that you only installed it in this filling-in-layout branch.


text:
Q: Eclipse History Load When Opening Source File Is there a way to automatically load the History tab to show the change history whenever I open a source file in Eclipse?
Right now, I have to right-click Team -> Show in History

A: Fourth tip from https://help.eclipse.org/oxygen/topic/org.eclipse.platform.doc.user/tasks/tasks-119.htm?cp=0_3_16_2_6

Tip: You can have the History view update automatically to the history of the file in the active editor by enabling the Link with Editor item in the view's toolbar.


text:
Q: How to fix Among Us authentication issues on Switch? When I try to join a private room in Among Us on Switch, I get this error:

I opened the profile section in the menue, and clicked "sign in", yet the error persists. Any way to fix this? I've tried uninstalling the game, removing my savegame data, reinstalling the game, signing in again, and yet the error persists.

A: Based on this document created by innersloth, it looks like it's a server side/traffic issue...


text:
Q: Can we use two pivot in a single query? Declare @tbl table(SessionId varchar(max),ItemID_FK int,Roles varchar(max))
    insert into @tbl
    select distinct SessionID,ItemID_FK,Roles from tbl_Answers where ID_FK=@ID
    SELECT ItemID_PK,ItemName,case when [Role1] IS NULL then 0 else [Role1] end as [Role1],
    case when [Role2] IS NULL then 0 else [Role2] end as [Role2],
    case when [Role3] IS NULL then 0 else [Role3] end as [Role3],
    case when [Role4] IS NULL then 0 else [Role4] end as [Role4],
    case when [Role5] IS NULL then 0 else [Role5] end as [Role5],
    case when [Role6] IS NULL then 0 else [Role6] end as [Role6],
    case when [Role7] IS NULL then 0 else [Role7] end as [Role7]
    FROM
    (
    select  items.ItemID_PK ,items.ItemName,count(ans.Roles) as cntRoles,ans.Roles from tbl_Items items Full  join  @tbl ans
    on items.ItemID_PK=ans.ItemID_FK where items.ID_FK= @ID group by Roles,ItemName , items.ItemID_PK
    ) d  PIVOT
     (
          max(cntRoles)
          FOR Roles IN ([Role1],[Role2],[Role3],[Role4],[Role5],[Role6],[Role7])
     ) AS pvt order by ItemID_PK

I used the above stored procedure and got the output as
+----------+----------+-----+-----+-----+-----+-----+-----+-----+
|ItemID_PK |ItemName  |Role1|Role2|Role3|Role4|Role5|Role6|Role7|
+----------+----------+-----+-----+-----+-----+-----+-----+-----+
|  111     | aaaaa    | 6   |  5  | 0   | 5   |   1 |  4  |  2  |
|  222     | bbbbb    | 1   |  1  | 7   | 2   |   0 |  3  |  1  |
+----------+----------+-----+-----+-----+-----+-----+-----+-----+

I have another query and got the following output.
Select Category,Answer,Roles
from tbl_Answers where ID_FK=1 and Category='OtherText'

+---------+--------+-----+
|Category |Answer  |Roles|
+---------+--------+-----+
|OtherText| xxx    |Role1|
|OtherText| yyy    |Role1|
|OtherText| zzz    |Role2|
|OtherText| xzx    |Role3|
+---------+--------+-----+

I need to merge the above two outputs to generate the result as
+----------+----------+-----+-----+-----+-----+-----+-----+-----+
|ItemID_PK |ItemName  |Role1|Role2|Role3|Role4|Role5|Role6|Role7|
+----------+----------+-----+-----+-----+-----+-----+-----+-----+
|  111     | aaaaa    | 6   |  5  | 0   | 5   |   1 |  4  |  2  |
|  222     | bbbbb    | 1   |  1  | 7   | 2   |   0 |  3  |  1  |
|  Null    | Othertext| xxx | zzz | xzx | saa |     | xxx |     |
|  Null    | Othertext| yyy |     |     | zxz |     |     |     |
+----------+----------+-----+-----+-----+-----+-----+-----+-----+

How to combine the second query to the first pivot query to get the result mentioned above?
Thanks in advance.

A: You could just use UNION ALL to combine the two results, you would need to convert the roles from the top query from int to VARCHAR though:
DECLARE @ID INT = 1;

WITH Ans AS
(   SELECT  DISTINCT SessionID,ItemID_FK,Roles
    FROM    tbl_Answers
    WHERE   ID_FK = @ID
), PivotData AS
(   SELECT  items.ItemID_PK,
            items.ItemName,
            cntRoles = COUNT(ans.Roles),
            ans.Roles
    FROM    tbl_Items items
            FULL JOIN Ans
                ON items.ItemID_PK = ans.ItemID_FK
    WHERE   items.ID_FK = @ID
    GROUP BY Roles,ItemName, items.ItemID_PK

)
SELECT  ItemID_PK,
        ItemName,
        [Role1] = CAST(ISNULL([Role1], 0) AS VARCHAR(255)),
        [Role2] = CAST(ISNULL([Role2], 0) AS VARCHAR(255)),
        [Role3] = CAST(ISNULL([Role3], 0) AS VARCHAR(255)),
        [Role4] = CAST(ISNULL([Role4], 0) AS VARCHAR(255)),
        [Role5] = CAST(ISNULL([Role5], 0) AS VARCHAR(255)),
        [Role6] = CAST(ISNULL([Role6], 0) AS VARCHAR(255)),
        [Role7] = CAST(ISNULL([Role7], 0) AS VARCHAR(255))
FROM    PivotData
        PIVOT
        (   MAX(cntRoles)
            FOR Roles IN ([Role1],[Role2],[Role3],[Role4],[Role5],[Role6],[Role7])
        ) AS pvt
UNION ALL
SELECT  ItemID_PK = NULL,
        ItemName = Category,
        [Role1] = ISNULL([Role1], ''),
        [Role2] = ISNULL([Role2], ''),
        [Role3] = ISNULL([Role3], ''),
        [Role4] = ISNULL([Role4], ''),
        [Role5] = ISNULL([Role5], ''),
        [Role6] = ISNULL([Role6], ''),
        [Role7] = ISNULL([Role7], '')
FROM    (   SELECT  Category,Answer,Roles
            FROM    tbl_Answers
            WHERE   ID_FK = 1
            AND     Category = 'OtherText'
        ) pd
        PIVOT
        (   MAX(Answer)
            FOR Roles IN ([Role1],[Role2],[Role3],[Role4],[Role5],[Role6],[Role7])
        ) AS pvt
ORDER BY ItemID_PK;

Note, I have changed this expression:
case when [Role2] IS NULL then 0 else [Role2] end

to
ISNULL([Role2], 0)

as the effect is the same, but it is much shorter. I have also removed the table variable, and just placed the same query within a Common Table Expression, as it seems redundant to fill a table variable then only refer to it once. You are removing the use of indexes and statistics on the actual table and gaining no benefit for it.

A: Use a UNION to combine the two pivots.


text:
Q: Can't bind to a command in my custom control I created a control based of TextBox that looks like this:
public class DelayedTextBox : TextBox
{
    public ICommand DelayedTextChangedCommand
    {
        get;
        set;
    }
}

I then create Foo.xaml with the following code:
<h:DelayedTextBox DelayedTextChangedCommand="{Binding FooCommand}"/>

And I have FooViewModel (which is hooked up correctly in the XAML because other parts can bind to properties in FooViewModel) that has this:
private ICommand _fooCommand;
    public ICommand FooCommand
    {
        get
        {
            if (_fooCommand == null)
            {
                _fooCommand = new RelayCommand(CheckFoo, () => CanExecuteFooCheck());
            }

            return _fooCommand;
        }
    }

I am using RelayCommand from GalaSoft.MvvmLight, which works for other commands in my project
When I run my project, I get the following error when Foo.xaml gets loaded:

WinRT information: Failed to assign to property
  'TestApp.Helpers.DelayedTextBox.DelayedTextChangedCommand'. [Line: 29
  Position: 103] An exception of type
  'Windows.UI.Xaml.Markup.XamlParseException' occurred in TestApp.exe
  but was not handled in user code WinRT information: Failed to assign
  to property
  'TestApp.Helpers.DelayedTextBox.DelayedTextChangedCommand'. [Line: 29
  Position: 103] The text associated with this error code could not be
  found.
Failed to assign to property
  'TestApp.Helpers.DelayedTextBox.DelayedTextChangedCommand'. [Line: 29
  Position: 103]

I'm super confused as to why it can't bind properly, what am I doing wrong?

A: The issue was I didn't add a dependencyProperty as @Lynn Crumbling mentioned in the comments to my question.
Adding the following to DelayedTextBox did the trick:
public static readonly DependencyProperty DelayedTextChangedCommandProperty =
    DependencyProperty.Register(
        "DelayedTextChangedCommand",
        typeof(ICommand),
        typeof(DelayedTextBox),
        new PropertyMetadata(0));


text:
Q: Using viewpager with specific fragments I am creating an app that is using a viewpager to slide between 4 specific fragments.
All the examples of viewpager I have read so far, create new fragments each time the getPosition method of FragmentPagerAdapter is called. So it's something like:
return FragmentA.newInstance();

What I have done is the following:
In the main activity
public static final int FRAGMENTS = 4;
public static final String FRAGMENT_LIST ="LIST";
public static final String FRAGMENT_SETTINGS = "SETTINGS";
public static final String FRAGMENT_MAP = "MAP";
public static final String FRAGMENT_TICKET = "TICKET";

MainAdapter _adapter;
ViewPager _pager;

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

    if (savedInstanceState == null) {
        getSupportFragmentManager()
                .beginTransaction()
                .add(new FragmentMap(), FRAGMENT_MAP)
                .add(new FragmentList(), FRAGMENT_LIST)
                .add(new FragmentTicket(), FRAGMENT_TICKET)
                .add(new FragmentSettings(), FRAGMENT_SETTINGS)
                .commit();
    }

    _adapter = new MainAdapter(getSupportFragmentManager());
    _pager = (ViewPager) findViewById(R.id.pager);
    _pager.setAdapter(_adapter);
}

and in the adapter:
public class MainAdapter extends FragmentPagerAdapter {

FragmentManager _manager;

public MainAdapter(FragmentManager fm) {
    super(fm);
    _manager = fm;
}

@Override
public Fragment getItem(int position) {
    return _manager.getFragments().get(position);
}

@Override
public int getCount() {
    return ActivityMain.FRAGMENTS;
}
}

This raises an exception because the adapter is trying to change the tag of each fragment in getItem
My questions are:
a) Is it incorrect to always use the same fragment every time? I have seen no example that uses the above method or a similar one, they always create a new instance in the getItem method
b) If I wish for fragments to have some persistence, then does that mean that I should store the data that should be held by each fragment in static variables and always create new instances that use those variables?

A: a) You must create a new instance in the getItem() method, this method is not called every time you switch fragment from your viewpager.
I recommend you to use your adapter like
public class MainAdapter extends FragmentPagerAdapter {

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

@Override
public Fragment getItem(int position) {
            case 0 :
                return new FragmentMap();
            case 1 :
                return new FragmentList();
            case 2 :
                return new FragmentTicket();
            case 3 :
                return new FragmentSettings();
            default :
                return null;
}

@Override
public int getCount() {
    return ActivityMain.FRAGMENTS;
}
}

b) Fragments in FragmentPagerAdapter are persistents, and they will be recreate only if you switch several fragment in your ViewPager. You can set the refresh limit by _pager.setOffscreenPageLimit(3); for exemple if you never want to recreate your fragments in your case.
For more information : http://developer.android.com/reference/android/support/v4/view/ViewPager.html#setOffscreenPageLimit(int)

A: a) I think it's perfectly ok. They always create ne instance because it is easier and in many cases (like image gallery) it is better.
b) Static variables get lost if you send the app to backround and then return to it. Shared prefferences or bundle should do the work.

A: You should use FragmentStatePagerAdapter. If you fragmentstatepager adapter, you can remove or add fragment dynamically.


text:
Q: How can I reconnect the restarted peer to the peers' network correctly with Hyperledger v1.0 alpha? I followed the procedure of Quickstart in the link below to setup the peers' network with Hyperledger v1.0 alpha.
https://hyperledger.github.io/composer/installing/quickstart.html
In the procedure, using "docker-compose up" to boot the four peer node as follows.
hlfv1 git:(master) ✗ docker ps
CONTAINER ID        IMAGE                                           COMMAND                  CREATED             STATUS              PORTS                                            NAMES
76ac234a65ed        hyperledger/fabric-peer:x86_64-1.0.0-alpha      "peer node start -..."   30 seconds ago      Up 28 seconds       0.0.0.0:7056->7051/tcp, 0.0.0.0:7058->7053/tcp   peer1
5075165661f3        hyperledger/fabric-peer:x86_64-1.0.0-alpha      "peer node start -..."   32 seconds ago      Up 29 seconds       0.0.0.0:7051->7051/tcp, 0.0.0.0:7053->7053/tcp   peer0
1955163b6e3d        hyperledger/fabric-orderer:x86_64-1.0.0-alpha   "orderer"                34 seconds ago      Up 31 seconds       0.0.0.0:7050->7050/tcp                           orderer0
65f4ad3217db        hyperledger/fabric-ca:x86_64-1.0.0-alpha        "sh -c 'fabric-ca-..."   34 seconds ago      Up 31 seconds       0.0.0.0:7054->7054/tcp                           ca_peerOrg1

After the four peer node booted, I used docker command to stop and start the peer.

docker stop peer1
  docker start peer1

Then I executed the composer command to deploy business archive as follows .

composer network deploy --archiveFile marbles-network@0.0.8.bna -p
  hlfv1 --enrollId admin --enrollSecret adminpw

It says ...

Error: Error: Invalid results returned ::NOT_FOUND

And also I can see the errors in the log of each peer.

2017-05-21 12:36:25.239 UTC [eventhub_producer] Chat -> ERRO 03a Error
  during Chat, stopping handler: stream error: code = 1 desc = "context
  canceled"

Without restarting the peer , the network is still OK and I can deploy business archive correctly.
How can I reconnect the restarted peer to the peers' network correctly with Hyperledger v1.0 alpha?


text:
Q: How to sort by a composed field with CrudRepository? I have a simple CrudRepository that accepts a sortable:
class PersonReposiroty extends CrudRepository<Person, Long> {
  findAll(Pageable page);
}

I want to sort it by the sum of two fields:
dao.findAll(PageRequest.of(page, size, Sort.by("price1, price2"));

Problem: this sorts first by price1, then by price2. How can I sum it before?

A: I found out that it is actually possible to order by sum, as follows with querydsl:
private PageRequest pricePageSort() {
    OrderSpecifier<BigDecimal> sort = QPerson.person.price1.add(QPerson.person.price2).asc(); //or .desc()
    return new QPageRequest(pageNumber, pageSize, sort);
}

Then use it by:
dao.findAll(predicate, pricePageSort());

Maybe the CrudRepository has to extends QuerydslPredicateExecutor<Person> therefore, but I'm using it anyways.


text:
Q: Get value from 2nd list based on ID from 1st list in Python I'm a beginner in Python and have a file i've read in that has an Market_ID field.  While looping over this file (list), I need to access the Market_name in a 2nd file (Market_ID,Market_Name).
What's the best place for me to start? I can give more detail on what the program is doing if necessary.
The files(lists) are laid out as follows:
File1:  Cust_ID, Market_ID, Cust_Name, IsNew
File2:  Market_ID, Market_Name

My main loop is over File1.  I need to be able to access the Market_Name from File2 to be able to place it in a new file i'm creating from data in File1.  Hope that helps.

A: If the files are not too big (a few megabytes) you could store each item in a dict() using the Market_ID as key.
This looks like data drom a database - if you are familiar with relational databases and their use you could insert each file into a separate table and then perform queries. Python has an interface to sqlite in its standard library.
For solving this quickly I suggest to use dicts though.

A:
If the files are not too big (a few megabytes) you could store each item in a dict() using the Market_ID as key.
This looks like data drom a database - if you are familiar with
  relational databases and their use you could insert each file into a
  separate table and then perform queries. Python has an interface to
  sqlite in its standard library.
For solving this quickly I suggest to use dicts though.
  BY -- sleeplessnerd

More about dictionaries,
More about sqlite
file2 = open("/path/to/file2", "r")
market_names = {}
for line in file2:
  fields = line.split(",")
  market_names[int(fields[0])] = fields[1]
file2.close()

file1 = open("/path/to/file1", "r")
for line in file1:
  fields = line.split(",")
  market_name = market_names[int(fields[1])]
  # do what ever you want with the Market_Name associated with
  # the Market_ID contained in this line
file1.close()

A: Hmm, could you please supply more details?
When you say file(list) do you mean that you've created a list that contains all the data you need from the first file? what about the second file?
If they are both lists than something like this would work:
for market_id in flie1_list:
    for pair in file2_list:
        if pair[0] == market_id:
            market_name = pair[1]
            break
    <keep doing whatever it is you need to do in first loop>

Note - I'm fairly a beginner as well, and it's my first answer on this site. Go easy ;)

A: I'm not up on my python, but conceptually, what you'll probably want to do is read the second file into a dictionary first and then look up the id in the dictionary to get the associated name.  Alternatively, if the ids are numeric and more-or-less dense, you could just read them into a regular array.