text:
Q: Home Icon is not showing next to Hamburger icon in ActionBar I am using AppCompat library for DrawerLayout. However the action bar is not showing the launcher icon next to hamburger menu icon. I have tried several ways to resolve this issue but none of them worked. Anybody has a clue how to resolve it?
I want to show an image just like here Google+ icon is visible next to hamburger icon.

Best Regards

A: The reason appIcon/launcher icon is not appearing in the actionBar is because of the new design  guidelines of Material Design (Thanks to CommonsWare for telling). However I have used a much simpler & easier solution - Custom ActionBar.
Steps:

*

*Create an XML file which follows your design pattern for Action Bar

*In Activity:
LayoutInflater inflater = LayoutInflater.from(this);
inflater.inflate(R.layout.custom_action_bar, null);

getSupportActionBar().setHomeEnabled(true); // for burger icon
getSupportActionBar().setDisplayHomeAsUpEnabled(true); // burger icon related
getSupportActionBar().setDisplayShowCustomEnabled(true); // CRUCIAL - for displaying your custom actionbar

getSupportActionBar().setDisplayShowTitleEnabled(true); // false for hiding the title from actoinBar

Hopefully this will save some ones time.


text:
Q: IE 11 ignores nth-child and last-child Can someone tell me why IE 11 ignores at all the following rule of my css file ?
.navigation.menu ul li:nth-child(7):hover ul,
.navigation.menu ul li:nth-child(8):hover ul,
.navigation.menu ul li:last-child:hover ul {

     right:0;left:initial;

}

This rule is being read and working as expected by all other browsers, but IE doesn't even see it.

A: Assuming you have the right doctype, I don't think your selector is the problem, it's the rule set.
IE doesn't understand the initial keyword. (And neither does Firefox, for that matter — it supports it with a prefix, -moz-initial.)
Since the initial value of left is auto, you can use that instead for the best compatibility with browsers:
right:0;left:auto;

redpajama_set_name: RedPajamaStackExchange


text:
Q: How do margins work with div positioning? The #content div holds most of the web content. As you can see below, there is a top margin of 280px, because that is the height of the header image of the site, which is placed in the 'body' as a background (image/sky1.jpg).
How do I position a div as a holder above the 'margin' of the #content div so that I could place my #navigation, #Title divs above the header image?
The #top-float div just above the #content div was the start of it but each time I add more to the height the
'margin' get affected pushing it below.
I tried putting the

 above the

 in the html. Is this how should I position this?
html {
    background: #73ADD7 url(images/gradient.gif) repeat-x;
}
body {
    padding: 0;
    margin: 0;
    background:url(images/sky1.jpg) no-repeat center top;
    color: #666;
    width: 100%;
    display: table;
}
#top-float{
    padding-left:2.3em;
    padding-right:2.3em;
    height:10em;
}
#content {
    width: 890px;
    margin: 280px auto 0;
    background: #fff;
    border: solid 0px #ccc;
    padding: 0px;
}
#footer {
    width: 890px;
    margin: px auto 0;
    background:url(images/footer-bg.jpg)
    no-repeat center bottom #fff;
    border: solid 0px #ccc;
    height:250px;
}

A: The easiest way would be to give your #top-float a height of 280px and drop the top-margin for #content as such:

If you need em sizing, then give the children of #top-float em sizing, and make sure to give #top-float overflow: hidden;
If you want your content to appear above your header in your markup for SEO purposes, you can do the following:

A: Just remove the top margin from your content div, and add the placeholder above it with the height specified.
HTML snip:

Stuff

Body stuff.../div>

And CSS:
#content {
  margin-top:0;
}

#header {
  height:280px;
}

If it makes more sense for the extra header information to be within the content div (semantically), you can use a negative margin.
HTML snip:

Stuff

    Body stuff...

And CSS:
#content {
  margin-top:280px;
}

#header {
  margin-top:-280px;
}

A: It is a little tricky answering this without also seeing your HTML, but a few suggestions:

*

*Place your #top-float div outside of your content div

*Use negative margins

*Put your content div flush with the top of the browser with a header div inside. Then put your header image inside your header div as the background image

*it doesn't look like you are centering anything so you can also use absolute positioning for the header div

As always, there is no one way of accomplishing this.

A: You may want to use absolute or fixed positioning for your #top-float div.
Why do you want to put the header image as a background image?  I think you'll find that it all works out easier if you don't put the site's header image as a background.  It is also common practice that clicking on the site's logo (which I assume is in your header image) takes the user back to the home page.  Making the site's logo a background image effectively disables this feature.


text:
Q: Ошибка в коде PHP для сайта Помогите найти ошибку в коде пожалуйста. Сам ищу и никак найти не могу, в интернете тоже ничего не нашел по данной ошибке.
Выдает ошибку: Warning: mysqli_query() expects parameter 1 to be mysqli, null given in C:\OSPanel\domains\geekbrain.ru\index.php on line 12
Warning: mysqli_error() expects parameter 1 to be mysqli, null given in C:\OSPanel\domains\geekbrain.ru\index.php on line 12
Код:
    <?
   $link = mysqli_connect('localhost','mysql', 'mysql', 'gb') or die (mysqli_error($link));

   $page = $_GET['p'];

   if ($page = 2) {
    $name = $_POST ['name'];
    $link = $_POST ['link'];
    $info = $_POST ['info'];

    $sql = "INSERT INTO news ( name, link, info) VALUES ( '$name', '$link', '$info')";
    $res = mysqli_query($link, $sql) or die (mysqli_error($link));
   }

?>

    <title>Блог</title>
    <meta charset="utf-t">

Главная

Добавить

<?
   switch($page) {
case 2:
var_dump($_POST);
echo<<<text
<form method="post">
<input name= "name" placeholder="Название">

<input name= "link" placeholder="Ссылка">

<textarea name= "info" placeholder=""></textarea>

<input type='submit'>

</form>

text;
break;
default:
 $res = mysqli_query($link, 'SELECT * FROM news')  or die (mysqli_error($link));

while($row = mysqli_fetch_assoc($res)) {
echo<<<text

{$row['name']}

text;
}
break;
}

?>

A: По моему ошибка в переменной $link, потому возвращает null и поэтому в 12 строке ошибка. Проверь подключение в $link

A: Попробуй добавь проверку для форму добавления, на заполнение каждого поля
        if($_POST['name'] && $_POST['link'] && $_POST['info'])
        {
          $name = $_POST ['name'];
          $link = $_POST ['link'];
          $info = $_POST ['info'];

          $sql = "INSERT INTO news ( name, link, info) VALUES ( '$name', '$link', '$info')";
          $res = mysqli_query($link, $sql) or die (mysqli_error($link));
        }


text:
Q: How to use a non-const member function inside a const member function? Following are a simple C++ struct and a class for 3D vector and 3x3 matrix. As you can see the subscript operator is overloaded for both of them. I return a reference to the data members from them in order to be able to assign to those members like vec[0] = 5.0;, mat[0] = vec3(2.0); and mat[0][0] = 3.0; etc. Now I declare another operator for mat3, the plus(+) operator which should not modify the matrix itself but should return a new matrix as the sum. How can I make this non-modifying + operator as const?
Vector
struct vec3 {
    typedef double value_type;
    vec3::value_type x, y, z;

    vec3(const vec3::value_type x,
         const vec3::value_type y,
         const vec3::value_type z)
    : x{x}, y{y}, z{z} {}

    vec3(const vec3::value_type w)
    : vec3(w, w, w) {}

    vec3()
    : vec3(0.0) {}

    // this works because [] operator is not used
    vec3 operator+(const vec3& v) const {
        return vec3(this->x + v.x, this->y + v.y, this->z + v.z);
    }

    vec3::value_type& operator[](const std::size_t index) {
        switch(index) {
        case 0:
            return x;
        case 1:
            return y;
        case 2:
            return z;
        default:
            throw std::invalid_argument("vec3 supports upto 3(0-2) elements");
        }
    }
};

Matrix
class mat3 {
    std::array<vec3,3> val;
public:
    using vtype = vec3::value_type;
    mat3(const vtype v00, const vtype v01, const vtype v02,
         const vtype v10, const vtype v11, const vtype v12,
         const vtype v20, const vtype v21, const vtype v22) {
        val[0][0] = v00; val[0][1] = v10; val[0][2] = v20;
        val[1][0] = v01; val[1][1] = v11; val[1][2] = v21;
        val[2][0] = v02; val[2][1] = v21; val[2][2] = v22;
    }

    mat3(const vtype m[3][3]) {
        for(std::size_t i = 0; i < 3; ++i) {
            for(std::size_t j = 0; j < 3; ++j) {
                val[i][j] = m[j][i];
            }
        }
    }

    mat3(const vtype v)
    : mat3(v, v, v,
           v, v, v,
           v, v, v) {}

    mat3()
    : mat3(0.0) {}

    // how to make it `const`
    mat3 operator+(const mat3& m) {
        mat3 t;
        for(std::size_t i = 0; i < 3; ++i) {
            t[i] = val[i] + m[i];
        }
        return std::move(t);
    }

    vec3& operator[](const std::size_t index) {
        switch(index) {
        case 0:
            return val[0];
        case 1:
            return val[1];
        case 2:
            return val[2];
        default:
            throw std::invalid_argument("mat3 supports upto 3(0-2) vec3");
        }
    }
};

A: You could (and should) add a const version for operator[], then you can make operator+ const, the const version of operator[] will be invoked in it.
vec3& operator[](const std::size_t index) {
    ...
}
const vec3& operator[](const std::size_t index) const {
~~~~~                                           ~~~~~
    ...
}

Note you can overload const and non-const member functions.
See const-, volatile-, and ref-qualified member functions (emphasis mine)

A non-static member function can be declared with a const, volatile,
  or const volatile qualifier (this qualifier appears after the name of
  the function in function declaration). Differently cv-qualified
  functions have different types and so may overload each other.
In the body of a cv-qualified function, the this pointer is
  cv-qualified, e.g. in a const member function, only other const member
  functions may be called normally. (A non-const member function may
  still be called if const_cast is applied or through an access path
  that does not involve this.)


text:
Q: Batch files incapable of launching other batch files I'm working on a project using batch, and I've been experiencing issues. Basically, the batch file is stored in a folder called WPI located in Documents. That folder hosts the launcher batch file and a few other batch files as well. On all testing in my main PC, things worked fine. When I tested it on a PC with a user that had a space in the username, I had issues. This was the code:
start %USERPROFILE%\Documents\WPI\%add%.bat

"Windows cannot find 'C:\Users\example\. Make sure you typed the name correctly, and then try again"

The user name had spaces, so it errored out and attempted to open something completely wrong. How I thought I would fix this was by putting the directory in quotes - like this:
start "%USERPROFILE%\Documents\WPI\%add%.bat"

NOTE: Unfortunately I'm seeing a stackexchage bug right now, trust me the backslash is there, it just refuses to display on stackexchange, That isn't the issue.
Unfortunately, this started me down a rabbit hole. No errors occur at all, and things look like they are functioning  properly, but when the other batch file is launched, it does nothing. Actually, it launches a cmd window with the directory it's located in, but it never actually runs the batch file itself. It opens a cmd window, for some reason:

As you can see, instead of executing the batch file like it should, it just opens a blank cmd window pointing to the directory it's located in. I noticed that using CD to go to the directory then using
start %add%.bat

works, but going through the code and adding that everywhere would be time-consuming and I really don't want to do that. Any ideas?


text:
Q: Conditional logical condition in R Suppose I have a data frame looking like this:
> testdf <- data.frame(x=rep(1:3, each = 3), y=rep(1:3))
> testdf
  x y
1 1 1
2 1 2
3 1 3
4 2 1
5 2 2
6 2 3
7 3 1
8 3 2
9 3 3

Suppose now that I want to select the rows in which the combination of (x, y) corresponds to any of the rows in
> conddf <- data.frame(x=c(1, 1, 3), y=c(2, 3, 1))
> conddf
  x y
1 1 2
2 1 3
3 3 1

So for this particular example, I would like to select rows (2, 3, 7). I stressed the word 'combination' above, because I think that is what making a correct formulation of the logical statement problematic for me. I have tried using some variants including the %in% command, but I haven't been able to formulate it such that it takes the combination of (x, y) into account. In some sense, the admissible values of y are conditional on the values of x. My original data set is quite large, so looping I would like to avoid.
Any ideas?

Edit: This seems to do what I want, but using a loop. I can't seem to get it into subset()or sapply(), though, so help with that would be sufficient!
testdf <- data.frame(x=rep(1:3, each = 3), y=rep(1:3))
conddf <- data.frame(x=c(1, 1, 3), y=c(2, 3, 1))
tempfun <- function(x) {ifelse(x[,2] %in% conddf$y[conddf$x == x[,1]], 1, 0)}
ind <- c()
for (i in 1:9) {
  ind <- c(ind, tempfun(testdf[i,]))
}


text:
Q: Prevent activity from restarting? I have an app.It starts with activity A. Then we can go to activity B. When I minimize app and start the app from resent application, there is no problem (Activity B comes up). But when i minimize app and start app from menu (clicking on app icon), it starts from launch activity (Activity A), like app restarts.How can i prevent that..Pls help

A: Well there is no 'android' general solution for this. You can mark it with some flags and prevent this , at least I do not know any flags. But the thing you can do is in your main (first) activity check some variable in shared preferences and start the activity B by your own.
you can save this needToGoToB in the shared preferences, for example when you enter in activity B you can set to be true.
if(needToGoToB){
startActivity(new Intent(this,B.class));
finish();
else{
//just normal flow
}

A: In B Activity
onCreate(){
 // Save int  preference "pref" 0 for B as not destroyed.
}

onDestroy(){
 // Save int preference "pref" as 1 for B as destroyed.
}

In A Activity

onCreate(){
 if (pref=0){
   //launch B Activity
 }else{
   // Do nothing
 }
}


text:
Q: Changes to the javascript file are not reflected I'm making an interactive decision flow chart that uses svg.js. I'm working from this example.
I'm editing the flowsvg.js file that I've linked to my HTML file. Nothing happens when I make changes to the .js file, but if I delete the file the flow chart doesn't work. What might be causing this?

A: Depending on which browser you are using in google chrome ,
Try clearing cache by right clicking on the page -> Inspect Element -> The right click the reload button and select Hard Reload.
Alternatively CTRL+Shift+I then clear cache


text:
Q: How to build pop up of TableViewer in SWT? I am new in Java and in SWT.
I created TableViewer to show data of tables.
class myTable : TableViewer

I want when I press on button to open dialog of myTable ( like pop up ) and to choose any item from the TableViewer.
The dialog should have two buttons "OK" and cancel.
Do you know how to do it in java? I mean to open dialog with TableViewer
Does there is standard widget for this?
which component do I need to use?
Do you have any example?

A: The simplest dialog would be one using org.eclipse.jface.dialog.Dialog - something like this:
import org.eclipse.jface.dialogs.Dialog;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Shell;

public class TestDialog extends Dialog
{
  public TestDialog(final Shell parentShell)
  {
    super(parentShell);
  }

  @Override
  protected Control createDialogArea(final Composite parent)
  {
    final Composite body = (Composite)super.createDialogArea(parent);

    final TableViewer viewer = new TableViewer(body, SWT.BORDER | SWT.V_SCROLL | SWT.H_SCROLL);

    viewer.getTable().setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));

    // TODO: Set TableViewer content and label providers
    // TODO: Set TableViewer input

    return body;
  }
}

In your code you do:
TestDialog dialog = new TestDialog(shell);

dialog.open();   // Displays the dialog in a popup window


text:
Q: Shuffling the digits of an integer so that the ratio between the resulting numbers is fixed. Suppose we have a 3-digit integer with all digits distinct. If we create its two shift numbers (resulting by rotation of the original digits), the ratio between the two subsequent numbers (if we order them in ascending or descending order) must be fixed.
Find this number.

Suppose the number is xyz and the two resulting numbers, if we shift the digits to the right, are yzx and zxy. Assuming $xyz<yzx<zxy$ (there is no equal, since all digits are distinct), we want $\frac{zxy}{yzx} = \frac{yzx}{xyz} = k$, where k: rational.

Furthermore, it is easy to deduce that 0 is excluded, or one of the resulting numbers would be 2-digit.
I have found 2 such sets of numbers, {243, 324, 432} and {486, 648, 864} and now I am trying to formulate an algebraic solution.
If xyz is the original number, the first rotation is yzx and can be found as follows:
$yzx = xyz*10+x-1000*x$.
Also $zxy= yzx*10+y-1000*y$.
Assuming wlg that $xyz<yzx<zxy$, we must have $\frac{xyz*10+x-1000*x}{xyz} = \frac{yzx*10+y-1000*y}{xyz*10+x-1000*x} = k$
I also noticed that if the 3 numbers are in ascending order $xyz<yzx<zxy$, then their differences
$yzx-xyz$ and $zxy-yzx$ have the same 3 digits in rotation.
but I don't think I can advance it any further...

A: We want to find triples of integers $(x,y,z)$ such that
$$0\lt x\le 9, 0\le y\le 9,0\le z\le 9\tag1$$
$$x\not=y,y\not=z,z\not=x\tag2$$
$$\frac{100z+10x+y}{100y+10z+x}=\frac{100y+10z+x}{100x+10y+z}\tag3$$
From $(3)$, we get
$$ yz-x^2=10(xz-y^2)\implies yz\equiv x^2\pmod{10}\tag4$$
and
$$x=-5z+\sqrt{25z^2+10y^2+yz}\implies \sqrt{25z^2+10y^2+yz}\ \in\mathbb Z\tag5$$
Also, if $y\lt z\lt x$, then $yz-x^2=10(xz-y^2)$ does not hold since LHS is negative while RHS is positve.
If $x\lt z\lt y$, then $yz-x^2=10(xz-y^2)$ does not hold since LHS is positive while RHS is negative.

*

*If $x^2\equiv 1\pmod{10}$, then $yz=21$ and so $(y,z)=(3,7),(7,3)$ each of which doesn't satisfy $(5)$.

*If $x^2\equiv 4\pmod{10}$, then $yz=4,14,24,54$ and so $(y,z)=(1,4),(4,1),(7,2),(3,8),(4,6),(6,4),(6,9),(9,6)$ where only $(y,z)=(6,4),(9,6)$ satisfy $(5)$ with $x=8,12$ respectively. (we don't need to consider the case $(y,z)=(2,7)$ since then $x=8$ for which $y\lt z\lt x$ holds. Also, we don't need to consider the case $(y,z)=(8,3)$ since then $x=2$ for which $x\lt z\lt y$ holds.)

*If $x^2\equiv 9\pmod{10}$, then $yz=9$ and so $(y,z)=(1,9),(9,1)$ each of which doesn't satisfy $(5)$.

*If $x^2\equiv 6\pmod{10}$, then $yz=6,16,36,56$ and so $(y,z)=(1,6),(6,1),(3,2),(2,8),(8,2),(4,9),(9,4),(7,8)$ where only $(y,z)=(3,2)$ satisfies $(5)$ with $x=4$. (we don't need to consider the case $(y,z)=(2,3)$ since then $x=4$ or $6$ for which $y\lt z\lt x$ holds. Also, we don't need to consider the case $(y,z)=(8,7)$ since then $x=4$ or $6$ for which $x\lt z\lt y$ holds.)

*If $x^2\equiv 5\pmod{10}$, then $x=5$ and one of $y,z$ is $5$, which does not satisfy $(2)$.
So, the only solutions are
$$\color{red}{(x,y,z)=(4,3,2),(8,6,4)}$$
where we have
$$\frac{243}{324}=\frac{324}{432}=\frac 34=\frac{486}{648}=\frac{648}{864}$$

A: Not a complete answer but can be open for further discussion
See one famous example for cyclic number:
$$\frac{1}{7}=0.\overline{142857}$$
we have
$$142857:285714:428571:571428:714285,857142=1:2:3:4:5:6$$

You may pick up $1:2:4$ for a case of $6$ digits.

In general for base $b$, the cyclic-permutation decimal can be in the form of
$$\frac{b^{p-1}-1}{p}$$
Besides the cyclic numbers mentioned in the above link, a number of subsets of $\dfrac{k}{37}$ give further kinds of cyclic numbers (including $0$):

*

*$k\in \{ 1,10,26 \}$ gives $0.\overline{027},0.\overline{270},0.\overline{702}$

*$k\in \{ 2,15,20 \}$ gives $0.\overline{054},0.\overline{405},0.\overline{540}$

*$k\in \{ 3,4,30 \}$ gives $0.\overline{081},0.\overline{108},0.\overline{810}$

*$k\in \{ 5,13,19 \}$ gives $0.\overline{135},0.\overline{351},0.\overline{513}$

*$k\in \{ 6,8,23 \}$ gives $0.\overline{162},0.\overline{216},0.\overline{621}$

*$k\in \{ 7,33,34 \}$ gives $0.\overline{162},0.\overline{216},0.\overline{621}$

*$k\in \{ 9,12,16 \}$ gives $0.\overline{243},0.\overline{324},0.\overline{432}$

*$k\in \{ 11,27,36 \}$ gives $0.\overline{297},0.\overline{729},0.\overline{972}$

*$k\in \{ 14,29,31 \}$ gives $0.\overline{378},0.\overline{783},0.\overline{837}$

*$k\in \{ 17,22,35 \}$ gives $0.\overline{459},0.\overline{594},0.\overline{945}$

*$k\in \{ 18,24,32 \}$ gives $0.\overline{486},0.\overline{648},0.\overline{864}$

*$k\in \{ 21,25,28 \}$ gives $0.\overline{567},0.\overline{675},0.\overline{756}$

Only subsets $\{ 9,12,16 \}$ and $\{ 18,24,32 \} $ are your favourable cases.

Note that $27\times 37=999$

*

*For $k=3n$, $$\frac{k}{27} = 0.\overline{n}$$

*For other $k$ values, there're $6$ triplets of cyclic numbers but there're no favourable cases here.


text:
Q: php - two file inputs two different folder I'm here to ask (cause I've searched today tons of internet for this)
Here's the case:
got one form with some fields,
and then it have 2 inputs type="file".
The point is that I want the file A go to folder A, and the file B go to folder B.
what I tried:
this is projs_upload.php
$uploaddirb = '../images/projects/';
$uploaddira = '../images/projects/thumb/';
$uploadfile = $uploaddira . basename($_FILES['min_img']['name']);
$uploadimg = $uploaddirb . basename($_FILES['img']['name']);

move_uploaded_file($_FILES['min_img']['tmp_name'], $uploadfile);
move_uploaded_file($_FILES['img']['tmp_name'], $uploadimg);

this is form:
require("common.php");
if($_POST){
    $query = "
        INSERT INTO projects (
            `idprojects`,
            `cat`,
            `name`,
            `desc`,
            `min_img`,
            `img`,
            `ext_url`
        ) VALUES (
            :idprojects,
            :cat,
            :name,
            :desc,
            :min_img,
            :img,
            :ext_url
        )
    ";
    $query_params = array(
        ':idprojects'=> "",
            ':cat' => $_POST['cat'],
            ':name' => $_POST['name'],
            ':desc' => $_POST['desc'],
            ':min_img' => $_FILES['min_img']['name'],
            ':img' => $_FILES['img']['name'],
            ':ext_url' => $_POST['exturl']
    );
    try
    {
        $stmt = $db->prepare($query);
        $result = $stmt->execute($query_params);
    }
    catch(PDOException $ex)
    {
        die("Failed to run query: " . $ex->getMessage());
    }
    include ("funcs/proj_uploads.php");
    header("Location: ?p=manage_projects");
    die("Redirecting done");
}
<form action="?p=manage_projects" method="post" enctype="multipart/form-data">
<input type="text" placeholder="kategoria" name="cat" />
<input type="text" placeholder="nazwa projektu" name="name" />
<input type="text" placeholder="link do projektu" name="exturl" />
<textarea placeholder="opis" name="desc" />
</textarea>
<input type="hidden" name="MAX_FILE_SIZE" value="512000" />
<input type="file" placeholder="miniatura" name="img" />
<input type="file" placeholder="duży" name="img" />
<button type="submit" class="expand">Zapisz</button>
</form>

and "?p=manage_projects" refers to the form page.

A: Your $uploaddirb path needs to end in a /, otherwise files will be uploaded into images/projects as files thumbsomename:
$uploaddirb = '../images/projects/thumb/';

If this doesn't solve it for you, update your question with more information, i.e. both HTML and PHP code, do both files not work?, have you checked the directories exist and have proper permissions?

A: Both your file input tags are called img.
You should have one called img and one called min_img
So do:
<input type="file" placeholder="miniatura" name="min_img" />
<input type="file" placeholder="duży" name="img" />

instead of:
<input type="file" placeholder="miniatura" name="img" />
<input type="file" placeholder="duży" name="img" />

NB: This should be easily spotted with a var_dump($_FILES) in your if($_POST) block.


text:
Q: Store maps in array C++ Is it possible to store maps in an array? Can you help me how can I do that?
It's obvious that I can store for example int, but I have no idea how I can do it with maps.
Thanks!

A: You can do it in exactly the same way. Say you want to map from std::string to int:
std::map<std::string, int> array[10];

This would give you an array of 10 of those maps. You might prefer to use the std::array container which encapsulates an array:
std::array<std::map<std::string, int>, 10> array;

Or if you want to be able to add maps to resize the array dynamically, you could use a std::vector:
std::vector<std::map<std::string, int>> array;

A: I suggest you to use std::vector for this. Then, you can easily create vector of maps with:
std::vector<std::map<std::string, int> > maps;

Note that there is no need for additional space between > characters in C++11.


text:
Q: What is a good value for CONN_MAX_AGE in Django? Django 1.6 now supports CONN_MAX_AGE to pool database connections.
By default, the value is 0 (no pooling).  What is a sensible value for this option?

A: This value depends on the traffic of your site, the more traffic the more seconds to retain the connection, I'd recommend setting a relatively small value like 60 and tuning it accordingly to the usage pattern.

Edit (2018):
Like @jcyrss pointed out, this method has its quirks, for future reference I'd recommend handing out pooling to something like pgbouncer instead.

A: Not as simple as "the more traffic the more seconds to retain the connection".
It also depend on how you run Django.
Now, one popular way to launch Django in gunicorn+greenlet(evenlet or gevent). And if you set CONN_MAX_AGE to 60 (even 5 in my case), you may get complain 'too many connections' from DB server.
See this for details.
https://github.com/benoitc/gunicorn/issues/996
https://serverfault.com/questions/635100/django-conn-max-age-persists-connections-but-doesnt-reuse-them-with-postgresq


text:
Q: Type mismatch returning an observable with fromCallable The following code does not compile:
override fun storeConnections(connections: List<Connection>): Observable<List<Connection>> =
    Observable.fromCallable<List<Connection>> {
        appDao.storeConnections(connections.map {
                            mapper.toDb(it)})

    }

The line with appDao.storeConnections indicates the following error:

Required List!
Found Unit

The storeConnections is done using Room:
@Dao
interface RoomDao {
    @Insert(onConflict = REPLACE)
    fun storeConnections(linkedInConnection: List<LinkedInConnectionEntity>)

}

The storeConnections is called from my rx stream:
val startPositions = BehaviorSubject.createDefault(0)

startPositions.flatMap { startPos -> App.context.repository.getConnections(startPos) }
    .flatMap { connections -> Observable.fromCallable(App.context.repository.storeConnections(connections)) }
    .doOnNext { ind -> startPositions.onNext(ind + 1) }
    .subscribe({ ind -> println("Index $ind") })

How do I properly implement this fromCallable?

A: Given your reply to your question:

storeConnections is returning nothing. But I need to wrap it in an observable in order to push it down the stream. So maybe my question is how to wrap an API call with an Observable when that api call returns nothing.

I will answer how you can wrap it in an observable in order to push it down the stream:
        .flatMap {
                connections ->
                    App.context.repository.storeConnections(connections)
                        .andThen(Observable.just(connections))
        }

Given that storeConnections returns a Completable:
    override fun storeConnections(connections: List<Connection>): Completable =
        Completable.fromAction {
            appDao.storeConnections(connections.map { mapper.toDb(it) } )
        }
    }

If storeConnections returns "nothing", you could simply move the Completable.fromAction to your stream:
        .flatMap {
                connections ->
                    Completable.fromAction { App.context.repository.storeConnections(connections) }
                        .andThen(Observable.just(connections))
        }

A: The key to getting it to work is using this:
return@fromCallable connections

So this is the corrected code:
override fun storeConnections(connections: List<Connection>): Observable<List<Connection>> =
    Observable.fromCallable<List<Connection>> {

        appDao.storeConnections(connections.map {
            mapper.toDb(it)
        })

        return@fromCallable connections
    }

And the rx stream that calls it:
val startPositions = BehaviorSubject.createDefault(0)

    startPositions.flatMap { startPos -> App.context.repository.getConnections(startPos) }
        .flatMap {
                connections -> App.context.repository.storeConnections(connections)
        }
        .doOnNext {
                connections -> startPositions.onNext(startPos++)
        }
        .subscribe({ ind -> println("Index $ind") })


text:
Q: WPF Data Binding: BindingOperations.SetBinding() do not use the value of the Dependency Property I have a own dependency property Target.Height bound to a normal property Source.Height using BindingOperations.SetBinding(). Updating the Target.Height property should update the Source.Height property.  But not the actual value of the dependency property is used rather the default value of the dependency property. Is this the intended behavior?
Thanks for any hints. Code I use:
public class Source
{
  private int m_height;
  public int Height
  {
    get { return m_height; }
    set { m_height = value; }
  }
}

public class Target : DependencyObject
{
  public static readonly DependencyProperty HeightProperty;

  static Target()
  {
    Target.HeightProperty =
      DependencyProperty.Register("Height", typeof(int), typeof(Target),
      new PropertyMetadata(666)); //the default value
  }

  public int Height
  {
    get { return (int)GetValue(Target.HeightProperty); }
    set { SetValue(Target.HeightProperty, value); }
  }
}

Source source = new Source();
Target target = new Target();

target.Height = 100;

Binding heightBinding = new Binding("Height");
heightBinding.Source = source;
heightBinding.Mode = BindingMode.OneWayToSource;

BindingOperations.SetBinding(target, Target.HeightProperty, heightBinding);

//target.Height and source.Height is now 666 instead of 100 ....

A: WPF puts Binding as values of dependency properties. When you setting up a binding you actually replaces your current property value with a new one. At the end of the DependencyObject.SetValueCommon you may find a code that did it. There we can see that WPF gets a default value, then set it as a current property value with expression marker, and then attach BindingExpression which updates the source using the current property value - the default value.
this.SetEffectiveValue(entryIndex, dp, dp.GlobalIndex, metadata, expression, BaseValueSourceInternal.Local);
object defaultValue = metadata.GetDefaultValue(this, dp);
entryIndex = this.CheckEntryIndex(entryIndex, dp.GlobalIndex);
this.SetExpressionValue(entryIndex, defaultValue, expression);
DependencyObject.UpdateSourceDependentLists(this, dp, array, expression, true);
expression.MarkAttached();
expression.OnAttach(this, dp);
entryIndex = this.CheckEntryIndex(entryIndex, dp.GlobalIndex);
effectiveValueEntry = this.EvaluateExpression(entryIndex, dp, expression, metadata, valueEntry, this._effectiveValues[entryIndex.Index)]);
entryIndex = this.CheckEntryIndex(entryIndex, dp.GlobalIndex);


text:
Q: Restart server if gateway is not responding I need to restart a windows 2008  server only if the gatwaay is not responding. Is there a way to conditionally ping the gateway and if the gateway is not reachable a restart is triggered?
Thank you

A: It might be a better option to contact the firewall vendor to see what you can't do to get those services started with out a reboot (seriously though). But to do what you're asking, you could try running this batch script, have it start up with Task Scheduler on reboot. You could either loop it with the "goto start" option listed. Or remove that and just have Task Scheduler run it every 5 minutes.
:start
ping [gatewayIP]
if %errorlevel%==1 shutdown /r
goto start


text:
Q: Using grep and logical operators for pattern matching within shell script Im trying to develop a script that finds a specific pattern in the output of the dig command running against a list of domains. To do this I'm using grep but  having difficulty implementing this using multiple logical operations.
I want to achieve something like this:
if output contains ("NXDOMAIN") and ("test1.com" or "test2.com"); then
echo output;

I have managed to get it working for the pattern "NXDOMAIN" by piping the output into grep but I am lost on how to implement the logical operators. My script so far:
#!/bin/bash
input="/root/subdomains.txt"
while IFS= read -r line
do
    output=$(dig "$line")
    if echo "$output" | grep "NXDOMAIN" >&/dev/null; then
        echo "$output";
    else
        echo " " >&/dev/null;
    fi
done < "$input"

Is using grep the best way to achieve this?

A: No need for grep or bash here.
#!/bin/sh -
input="/root/subdomains.txt"

contains() {
  case "$1" in
    (*"$2"*) true;;
    (*) false;;
  esac
}

while IFS= read <&3 -r line
do
    output=$(dig "$line")
    if
      contains "$output" NXDOMAIN && {
        contains "$output" test1.com || contains "$output" test2.com
      }
    then
      printf '%s\n' "$output"
    fi
done 3< "$input"

If you really wanted to use grep, you'd define contains as:
contains() {
  printf '%s\n' "$1" | grep -qFe "$2"
}

But that would be less efficient as it means spawning two extra processes and in most sh implementation executing an external grep utility.
Or:
#!/bin/sh -
input="/root/subdomains.txt"

match() {
  case "$1" in
    ($2) true;;
    (*) false;;
  esac
}

while IFS= read <&3 -r line
do
    output=$(dig "$line")
    if
      match "$output" '*NXDOMAIN*' &&
        match "$output" '*test[12].com*'
    then
      printf '%s\n' "$output"
    fi
done 3< "$input"

Or do without the intermediary function:
#!/bin/sh -
input="/root/subdomains.txt"

while IFS= read <&3 -r line
do
    output=$(dig "$line")
    case $output in
      (NXDOMAIN)
        case $output in
          (test1.com | test2.com) printf '%s\n' "$output"
        esac
    esac
done 3< "$input"

That would also work with bash, but there's no need to add a dependency to bash when your (presumably faster and leaner) standard sh can do it.

A: You can create a logical AND by piping into grep again, and a logical OR using regular expressions:
echo "$output" | grep "NXDOMAIN" | grep -E 'test1\.com|test2\.com'


text:
Q: Is there a way to make sure classes implementing an Interface implement static methods? First of all, I read erickson's useful reply to "Why can't I define a static method in a Java interface?". This question is not about the "why" but about the "how then?".

Edit: my original example was ill-posed, but I'll leave it below.

While I am now convinced that in most cases what I want to do is overkill, there is one scenario where it could be needed:
I'll take the ParametricFunction example again. Now let's take a complicated function, like the Bessel functions, where a lookup-table is appropriate. That has to be initialised, so the two options are passing the parameters directly to the constructor or providing a init(double[] parameters). The latter has the disadvantage that getValue(double x) must check the initialisation every call (or the ArrayIndexOutOfBoundsException must be considered as initialisation-check), so for time-critical applications I'd prefer the constructor-method:
interface ParametricFunction {
  public double getValue(double x);
}

class BesselFunction implements ParametricFunction {
  public BesselFunction(double[] parameters) { ... }
  public double getValue(double x) { ... }
}

Which touches another problem, the impossibility of constructors in interfaces. What would be a good solution there? I could of course use the init(double[] parameters) approach, but I mentioned my reason why not.
(Edit: OK, here an abstract class implementing the interface would do)
Now let's assume the ParametricFunction allows only certain parameters, e.g. positive integers. How to check the vailidity of parameters passed to the constructor? Throwing an IllegalArgument-exception would be a possibility, but a checkParametersValidity(double[] parameters) seems a lot more convenient. But checking the parameters needs to be done before construction, so it has to be a static method. And that's where I'd really like to know a way to make sure every class implementing the ParametricFunction interface does define this static method.
I know this example is rather artificial, and the reason for not simply using a init method through the interface is debatable, I'd still like to know the answer. Consider it an academic question if you don't like it.
(original example)
So basically I want one Interface to provide both usual methods and e.g. a getSimilarObject method. For (a made up) example
public interface ParametricFunction {
  /** @return f(x) using the parameters */
  static abstract public double getValue(double x, double[] parameters);

  /** @return The function's name */
  static abstract public String getName();

  /** @return Whether the parameters are valid  [added on edit] */
  static abstract public boolean checkParameters(double[] parameters);
}

and then
public class Parabola implements ParametricFunction {
  /** @return f(x) = parameters[0] * x² + parameters[1] * x + parameters[2] */
  static public double getValue(double x, double[] parameters) {
    return ( parameters[2] + x*(parameters[1] + x*parameters[0]));
  }
  static public String getName() { return "Parabola"; }
  // edit:
  static public boolean checkParameters(double[] parameters) {
    return (parameters.length==3);
  }
}

Since this is not allowed in the current Java standard, what is the closest thing to this?
The idea behind this is putting several ParametricFunctions in a package and use Reflection to list them all, allowing the user to pick e.g. which one to plot. Obviously one could provide a loader class containing an array of the available ParametricFunctions, but every time a new one is implemented one has to remember adding it there, too.
edit: An example to call it is
public double evaluate(String fnName, double x, double parameters) throws (a lot) {
  Class<ParametricFunction> c = (Class<ParametricFunction>) ClassLoader.getSystemClassLoader().loadClass(fnName);
  Method m = c.getMethod("getValue", x, parameters);
  return ((double) m.invoke(null));
}

and calling evaluate("Parabola", 1, new double[]{1,2,0});.

A: Why not try Java 5 enum? ie:
public enum ParametricFunctions implements ParametricFunction {
    Parabola() {
        /** @return f(x) = parameters[0] * x² + parameters[1] * x + parameters[2] */
        public double getValue(double x, double[] parameters) {
            return ( parameters[2] + x*(parameters[1] + x*parameters[0]));
        }

        public String getName() { return "Parabola"; }

        public boolean checkParameters(double[] parameters) {
            return (parameters.length==3);
        }
    },

    // other functions as enum members
}

With this you can look up the static function types easily, and with compile-time safety, but still allow the interface type to be referenced elsewhere. You could also place a method on the enum type to allow lookup of the function by name.

EDIT for concerns on file size with the enum way.
In that case you could define each function as it's own class, ie:
public class Parabola implements ParametricFunction {

    /** @return f(x) = parameters[0] * x² + parameters[1] * x + parameters[2] */
    public double getValue(double x, double[] parameters) {
        return ( parameters[2] + x*(parameters[1] + x*parameters[0]));
    }

    public String getName() { return "Parabola"; }

    public boolean checkParameters(double[] parameters) {
        return (parameters.length==3);
    }

}
Then you can have many separate, implementation files, and compose them into one, smaller, enum-like class through which the functions can be accessed statically. Ie:
public class ParametricFunctions {
    public static final ParametricFunction parabola = new Parabola(),
                                           bessel = new BesselFunction(),
                                           // etc
}

This allows a single place to look up the functions, with the implementation kept separate. You could also add them to a static collection for name lookup. You could then maintain readability in your functions as mentioned in another comment:
import static ...ParametricFunctions.parabola;
// etc

public void someMethodCallingFit() {
    fit(parabola, xValues, yValues);
}

A:
The idea behind this is putting
  several ParametricFunction's in a
  package and use Reflection to list
  them all, allowing the user to pick
  e.g. which one to plot.

That's going to fail for a more basic reason: reflection offers no way to list all classes in a package (because "all classes in a package" is not a well-defined set, due to the flexibility of the classloader mechanism).
The modern solution for this kind of thing is to make it part of the application configuration via a dependency injection framework.

Obviously one could provide a loader
  class containing an array of the
  available ParametricFunction's, but
  every time a new one is implemented
  one has to remember adding it there,
  too.

Well, with your concept, every time a new one is implemented, one is forced to put it into the same package. By putting it into a configuration file or a loader class (the same thing, really), you remove that restriction.

A: Your answer to your own question can be simplified further. Keep the ParametricFunction interface as-is, and change Parabola into a singleton that implements ParametricFunction:
public class Parabola implements ParametricFunction {
  private static Parabola instance = new Parabola();

  private Parabola() {}

  static public ParametricFunction getInstance() {
    return instance;
  }

  public double getValue(double x, double[] parameters) {
    return ( parameters[2] + x*(parameters[1] + x*parameters[0]));
  }
  public String getName() { return "Parabola"; }
  public boolean checkParameters(double[] parameters) {
    return (parameters.length==3);
  }
}

Indeed, if there is no particular reason why Parabola needs to be a singleton class, you could get rid of the static method and attribute and make the constructor public.
The purpose of creating an instance of Parabola is to simplify your application.
EDIT in response to your question below:
You cannot use standard Java constructs to force a class to implement a static method with a given signature.  There is no such thing as an abstract static method in Java.
You could check that a static method is implemented by writing a separate tool that runs as part of your build and checks either the source code or the compiled code.  But IMO, it is not worth the effort.  Any missing getInstance() will show up if you compile code that calls it, or at runtime if you try to use it reflectively.  That should be good enough, in my opinion.
Besides, I cannot think of a convincing reason why you need the class to be a singleton; i.e. why the getInstance method is necessary.

A: You cannot require classes to implement particular static methods through an interface. It just makes no sense in Java terms. Interfaces force the presence of particular non-static methods in the classes that implement the interface; that's what they do.
The easiest way is definitely to have some sort of factory class that produces instances of the others. Yes, this does mean that you have to remember to keep that factory up to date when you add new instances, but since the first thing you do when you make a new implementation is test it (you do test it, yes?) you'll pick up on that problem very quickly!

A:
The reason is readability:
  fit("Parabola", xValues, fValues)  vs.
  fit(Parabola.getInstance(), xValues,
  fValues) vs. fit(new Parabola(),
  xValues, fValues). Why would I want to
  have an Instance of function defined
  entirely by it's arguments with no
  internal data?

Actually you are missing something about oriented object programming basics...
If you define an object Parabola, this object should represent a Parabola, and not a toolbox to check parameters are ok etc...
Your Parabola item should contain the parameters (x, y ...) and you could pass them with constructor...
double x;
double [] parameters;
public Parabola(double x, double[] parameters) {
  this.x = x;
  this.parameters = parameters;
}

Thus you shouldn't use parameters on your function since the parameters are now declared as class member attributes...
public double getValue() {
  return ( this.parameters[2] + x*(this.parameters[1] + x*this.parameters[0]));
}

Then just call
parabolaInstance.getValue();

A: One solution - is make all methods non-static with requirement that class must have default constructor. Then you can instantiate it easily and call methods you need.

A: What you want to do is not ok...
You want to define static methods in an interface I and have some implementations A and B of this interface, with their own implementation of these static methods declared in the interface I.
Just imagine, how the computer would know what to do if you call I.staticMethod() ??? will it use the implementation of A or B?!!
The interest to declare a method in the interface is to use polymorphism and be able to call this method for different object implementations... But for static methods, since you don't call the method from an instance (actually you can but not really needed...) but with ClassName.xxxMethod, it absolutly has no interest...
Thus you don't have to put these static methods in the interface... just put them in the both implementations and call them with A.staticMethod() and B.staticMethod() (and they don't even need to share a same method name!)
I wonder how you want to call your static method, do you sample code to show?

A:
@Sebastien: Why is there no interest
  for both classes to share the exact
  same static method name? Using
  reflection this might be the only way
  to make sure the method exists. I
  would like getDescription()  to return
  the description of the class. Why
  should it change on different
  instances? That's why I'd like this
  method to be static and yet enforce in
  an Interface-like way that it is
  implemented. – Tobias Kienzler 3

As i already said declaring the method static means you can call it directly from the class and don't need a class instance. Since it has no sense to call I.staticMethod() (as already explained), you just can call A.staticMethod1() and B.staticMethod2(), their name doesn't matter at all since you call them from the A or B class, known at compile time!
If you want a getDescription to return the same description no matter the instance of ParametricFunction concerned, just make the ParametricFunction an abstract class and implement the static methods directly in this class. Then you'll be able to call A, I or B.getDescription(); (even a,i or b...). But it remains the same than implementing it in A and B and calling it threw A or B...
Calling a static method from an instance is not a good practice and has no interest, so you should call A.meth(), or B.meth() and not a.meth() or b.meth()

Because I wanted A and B to implement
  that staticMethod for sure and make
  sure someone else using the Interface
  for a new class will do so, too. –
  Tobias Kienzler 5 hours ago

Actually "someone else" will normaly not call a.meth() or b.meth() thus if he makes a class C and want to call the C.meth() he'll never be able to do that because C.meth() is not implemented or not static... so he will do it, or the C.meth() would never been called and then it is also non sense to force developpers to implement static functions that would never be used...
I don't know what i can add...

A: Constructor in interface? uh? Would you like to be able to call Interface i = new Interface(double[] parameters)? And the computer would another time choose himself the implementation? This is as much strange as static in interface :D
As you said, checking parameters should be done before construction...
But this doesn't mean you can't raise exception on construction if parameters are not ok. It's just a security you can add, that will ensure that the constructed object will be coherent. But such code doesn't allow you to bypass a previous validation: raising exception on construction will tell you "hey you have a bug!" while not validating the params will just tell you "hoho someone using GUI tried to set a bad value, we'll send him an error message..."
Actually, since you need to validate the values, and the object is not even constructed, why do you absolutly want to add this validation on the model object? Form/Gui/whatever validation could be done anywhere, in a validation java class...
Just set a static (or not) method, in another class called ParametricFunctionValidationHelper, where you add your method and the validation implementation.
public static boolean validateParametricFunction(String functionType, double[] parameters) {
  if ( functionType.equals("bessel") ) return validateBessel(parameters);
  if ( functionType.equals("parabola") ) return validateParabola(parameters);
}

It doesn't matter how is represented your functionType (i choose String because i suppose you get it from user interface, web or gui... it could have been Enum...
You can even validate the object after having constructed it:
public static boolean validateParametricFunction(ParametricFunction pamFunc) {
  if ( pamFunc instanceOf BesselFunction ) return validateBessel(pamFunc.getParameters);
  ......
}

You can even put static validation methods in function classes and then you'll have:
    public static boolean validateParametricFunction(ParametricFunction pamFunc) {
      if ( pamFunc instanceOf BesselFunction ) return BesselFunction.validateBessel(pamFunc.getParameters);
      if ( pamFunc instanceOf ParabolaFunction ) return ParabolaFunction.validateParabola(pamFunc.getParameters);
    }
Yes you won't be able to set the static method in the interface but anyway how would you call such a method?
With code like
public static boolean validateParametricFunction(ParametricFunction pamFunc) {
  return ParametricFunction.validate(pamFunc);
}

??? This as no sense because the JVM won't be able at all to know which implementation of the static method to use since you don't call the static method from an instance but from a class! It as only sense if you implement the validate method directly in the ParametricFunction class, but anyway if you do such a thing you'll have to do exactly the same that i've shown you before with the instanceOf, because the instance of the pamFunc is the only item you'll have to select which kind of validation you'll have to use...
That's why you'd better use a non static method and put it in the interface like:
public static boolean validateParametricFunction(ParametricFunction pamFunc) {
  return pamFunc.validate();
}

Actually what you should do is:
- Retrieve parameters (String?) from GUI / Web interface / anything
- Parse String parameters in good format (String to int...)
- Validate these parameters with a validation class (static method or not)
- If no validation -> print message to user
- Else construct object
- Use the object
I don't see anywhere a need of static method in interface...


text:
Q: Ambigious names for controller methods in ASP.NET MVC Image the following controller method:
public ActionResult ShipmentDetails(Order order)
{
    return View(new OrderViewModel { Order = order });
}

The incoming order parameter is filled from a custom model binder, that either creates a new order for this session and stores it in the session, or reuses an existing order from the current session. This order instace is now used to fill a shipment details form, where users can enter their address and so on.
When using @using(Html.BeginForm()) in the view. I cannot use the same signature for the post method again (because this would result in ambigious method names) and I found me adding a dummy parameter just to make this work.
[HttpPost]
public ActionResult ShipmentDetails(Order order, object dummy)
{
    if (!ModelState.IsValid)
        return RedirectToAction("ShipmentDetails");

   return RedirectToAction("Initialize", order.PaymentProcessorTyped + "Checkout");
}

What are the best practices for this? Would you simply rename the method to something like PostShipmentDetails() and use one of the overloads of BeginForm? Or does the problem originate from the point, that the first method has the order parameter?

A: You could use the ActionName attribuite:
[HttpPost]
[ActionName("ShipmentDetails")]
public ActionResult UpdateShipmentDetails(Order order) { ... }

or a more classic pattern:
public ActionResult ShipmentDetails(int orderId)
{
    var order = Repository.GetOrder(orderId);
    return View(new OrderViewModel { Order = order });
}

[HttpPost]
public ActionResult ShipmentDetails(Order order)
{
    if (!ModelState.IsValid)
        return RedirectToAction("ShipmentDetails");

   return RedirectToAction("Initialize", order.PaymentProcessorTyped + "Checkout");
}


text:
Q: Как сделать корзину php? Подскажите, пожалуйста, как можно сделать так, чтобы при нажатии на ссылку(кнопку) происходил переход в корзину, куда добавляется выбранный товар(бисквит)?
 <?php
    require 'functions/function.php';
    if (isset($_POST['korzina'])) {
        korzina();
        redirect();
    }
    ?>

    <meta charset="UTF-8">
    <title>Учёт заказов для кондитерского цеха</title>

    <link rel="stylesheet" href="css/frame.css">

Классический

Сладкий белый бисквит, пропитанный фирменным сметанным кремом. Классический десерт в классической форме.

Состав:
Яйца, сахар, мука, сметана.

        <a href="cart.php?kod_biskvita=<?php echo $biskvit['6']?>" name="korzina" style="margin-right: 250px; margin-left: 650px;   position:relative; top:-580px">
                    В корзину

Перерождённая классика

Ароматные медовые коржи, пропитанные сметанным кремом. Декорирован сметанным кремом, шоколадной глазурью и медовой крошкой.

Состав:
Яйца, сахар, мука, соль, сметана, мёд, шоколадная глазурь.

        <a href="cart.php?kod_biskvita=<?php echo $biskvit['7']?>" name="korzina" style="margin-right: 250px; margin-left: 650px;   position:relative; top:-695px">
                    В корзину

Ореховая нежность

Бисквит пропитанный сахарным сиропом и нежным кремом. Декорирован золотистым арахисом, кремовыми пампушками и жареной бисквитной крошкой.

Состав:
Яйца, сахарная пудра, сахар, миндальная мука, арахис жаренный, соль, сливочное масло.

        <a href="cart.php?kod_biskvita=<?php echo $biskvit['8']?>" name="korzina" style="margin-right: 250px; margin-left: 650px;   position:relative; top:-860px">
                    В корзину

Слабость королевы

Сладкий бисквит, пропитанный кремом. Оформлен ароматной клубникой, фруктовым желе и обожжённым белковым кремом с тонким карамельным ароматом.

Состав:
Яйца, сахар, мука, сливочное масло, экстракт ванили, цедра 1 лимона, взбитые сливки и клубника — для украшения.

        <a href="cart.php?kod_biskvita=<?php echo $biskvit['9']?>" name="korzina" style="margin-right: 250px; margin-left: 650px;   position:relative; top:-1010px">
                    В корзину

Сметанный

Сметанный шоколадный бисквит, пропитанный сахарным сиропом и сливочным сметанный кремом. Оформлен сливочным кремом и шоколадной глазурью.

Состав:
Яйца, сахар, мука, сметана, шоколад.

        <a href="cart.php?kod_biskvita=<?php echo $biskvit['10']?>" name="korzina" style="margin-right: 250px; margin-left: 650px;   position:relative; top:-1070px">
                    В корзину

Черепаха

Бисквитный торт, пропитанный сметанным кремом. Оформлен шоколадным покрытием и белковым кремом, декорирован под черепаху.

Состав:
Яйцо куриное, сахар, мука пшеничная х/п в/с, сливки на растительной основе, сметана, гель шоколадный, шоколадная глазурь, какао-порошок.

        <a href="cart.php?kod_biskvita=<?php echo $biskvit['11']?>" name="korzina" style="margin-right: 250px; margin-left: 650px;   position:relative; top:-1144px">
                    В корзину

Таблица biskvit в базе данных:

A: Вам нужно хранить где то содержимое корзины, это может быть база данных или сессия или куки например (с чем вам проще работать, думаю сессии нормальный вариант будет), т.е. за каждым пользователем числится корзина (можно хранить товар, выбранное количество).
При переходе на страницу корзины, у вас отображается весь список товаров которые выбрал текущий пользователь (можно добавить информацию что есть в наличии а что закончилось).
На странице товара делаете кнопку добавить в корзину, если по вашей логики то "добавить и перейти в корзину" в урле кнопки делаете параметр говорящий что идёт добавление в корзину товара и уникальный код товара (артикул, или id, например ?addProduct=12345).
Если кнопка нажата то происходит переход на страницу корзины. В начале кода страницы корзины  проверяется есть ли в урле addProduct если есть то добавляете в то место где хранятся все товары добавленные этим пользователем новый товар, далее можно сделать редирект на страницу корзины уже без этого параметра (что бы в итоге урл был красивый без лишних параметров), в итоге на странице у вас появляется список всего что добавлено в корзину (эта механика уже сделана на шагах выше).


text:
Q: Periodic waves traveling on an ideal flat sea and the reflection of the Sun Suppose sinusoidal parallel waves (with equal wavelengths and amplitudes) are traveling in different directions on an ideally flat sea. The Sun is shining, let's say, $30^0$ above the horizon and the sea, and the sky is crystal clear.
Does it matter for what pattern in time (concerning the reflected Sun on these waves) we see, in which way the waves are traveling? Will all the patterns we perceive (thus for the different directions of the waves) be the same but stretched in time? Or...? The coastline where we stand is parallel to the horizon.


text:
Q: How do you set up Ubuntu to see Windows Network? I've tried the various tutorials and no success so far.

*

*I can connect to the router and from there to the internet, but I cannot see any network shares.

*I'm connecting through wlan0.

*I would prefer to keep the dynamic IP address if possible.

In answer to heavyd, smbtree gives me:
WORKGROUP
     \\COMPUTER1
cli_start_connection: failed to connect to COMPUTER1<20> (0.0.0.0). Error    NT_STATUS_UNSUCCESSFUL
     \\MY-LAPTOP            my-laptop server (Samba, Ubuntu)
Server requested LANMAN password (share-level security) but 'client lanman auth' is disabled
failed tcon_X with NT_STATUS_ACCESS_DENIED
     \\COMPUTER2
 cli_start_connection: failed to connect to COMPUTER2<20> (0.0.0.0). Error NT_STATUS_UNSUCCESSFUL

The data above has been anonymized for my protection.
Also I can ping them, I just can't see them via smb://.

A: In Linux machine check /etc/samba/smb.conf.If you have in your shares option browseable = no this means that you can mount the share but you can't see it on your network ,it's like invisible share. You'll need to edit these..
Then  try to run     nmblookup \*
and do sudo gedit /etc/nsswitch.conf . Look for a line starts with hosts:. if the line doesnt contain the word "wins" change the line to: hosts: files wins dns
You may also need to grant share permissions on the Window machine. It works better when this is an intentionally shared folder and not a default share or a "Shared Documents" folder. In Vista and some XP you have to actually find the "Permissions" button on the Sharing tab and grant everyone permission. This is different than NTFS file permissions on the Security tab and can be a pain to figure out on the "Home" versions.
take a look at File and Printer Sharing in Windows.

A: I think that for most people, they have a local network and a router that connects them to the internet.  Then they have various machines on their local network.  If you're connected like that, then your dynamic IP is usually the one provided by your ISP and it is assigned to the router's internet side.  Your local machines would usually have addresses in the 192.168.X.Y or 10.X.Y.Z or 172.something ranges and those IP addresses can be static or dynamic.  If you are using "wlan0" as your network interface, then you are probably connecting wirelessly to a wireless router which usually, by default, will give you a dynamic IP address.
If you can "ping" the windows machines in your local network from the Ubuntu machine, then you should be able to share files on those windows machines with your Ubunty machine by using Samba.  You can put your windows machines in the same workgroup and configure Samba to use the same workgroup.  The Samba configuration file is usually in /etc/samba/smb.conf .  If you don't have Samba, you should install it:
 $ sudo apt-get update
 $ sudo apt-get install samba

There are comments in the samba configuration file, but reading the docs may be necessary.  Look in /usr/share/doc/samba for information and check the man pages for samba (man samba) and go from there.  I hope that helps a little.


text:
Q: Image Processing-pixel intensity Thanks @Ali Hashmi for help
I am new to using Mathematica. I haven't come across a post that would answer this issue. I would like to identify the 2 dyes (based on intensity against all the dyes used) which make up each segment. So when I have all the channels in a merged image I can assign each segment a specific pseudocolor for each dye combination. So for example I want to color all segments in the merged image which have channel green and channel blue signals green. Have used the ImageHistogram function but have no idea how to tackle this on an individual segment basis. I have attached only 1 channel and a mask as Im limited to the amount of links I can upload. The mask was formed from the merged image of all the channels to segment into ROIs outside of Mathematica.

A: lets say you have the following channels: channel1, channel2 and channel3. Provided we have the binarized mask (segmentation of your cell) stored as mask then we can do the following:
intensity1 = ImageMeasurements[channel1,"MeanIntensity", Masking -> mask];

you can do the same for others. Or better map the list of channels as:
{intensity1,intensity2,intensity3} =
ImageMeasurements[#,"MeanIntensity", Masking -> mask]&/@{channel1,channel2,channel3}


text:
Q: Unable to boot Mac. Single user mode not working I lost admin access when I tried to change user name on my Mac. I have entered into single user mode, entered all the commands suggested (including the spaces) and it isn't working. It continues to reboot with zero change. What can I do? I'm open to all suggestions.

A: did you do the single person commands?
did you type them correctly?
/sbin/mount -uw /
rm /var/db/.applesetupdone

A: I have been in the same state last year when I also did the same i.e. tried changing admin user name. I am not much of a software geek so I resorted to the brute force method, installing the new copy of the macOS. I was running High Sierra at that time.
I followed this apple support link and most probably installed a clean version of latest macOS available by holding cmd+R at startup.
If you can backup your Mac now, it would save a lot of work.
Follow this tutorial to backup to a hard disk. It uses disk utility, time machine and by holding cmd+R during startup, you can go to recover from a time machine backup.
Cheers!

A: Get the Mac to set up  an additional administrative account.  This will work in all releases of Mac OS X so far.
You need to get into single use mode for steps one and two that are listed below. Start with your computer power off.  Hold down command-s. Power on your computer. Continue holding down command-s until you see some text on the screen.
This page will give more details on how to get into single user mode.
http://support.apple.com/kb/HT1492
Type in the following:
The first two commands will depend on your release of Mac OS X.  Look at what is typed out in the console to determine the exact format. You do not need to type in the lines beginning with an ampersand, #, they are comments.
# Type the follow two instructions to access the startup disk in read/write.
# Press return after each command.
# in case of partial success repeat this command until errors go away.

/sbin/fsck -fy
/sbin/mount -uw /

# Get setup to activate a new administration account
cd /var/db
pwd
#List all files. The l is a lower case L.
ls -a

# The move command acts as a rename command in this format.
# In Yosemite, this file is zero bytes.
# the disappearance of .AppleSetupDone causes a new administration account
# to be added the next reboot.
mv -i  .AppleSetupDone .AppleSetupDone.old

# reboot  your mac
shutdown -r now

Once you've done that the computer reboots and it's like the first time you used the machine. Your old accounts are all safe. From there you just change all other account passwords in the account preferences!!   macOS will ask you to create a new admin account.
Limnos adds a detailed explanation:
http://discussions.apple.com/message.jspa?messageID=8441597#8441597


text:
Q: Print fibonacci numbers up tp 15,000 C# I have seen similar questions(but in C) -- Calculating Fibonacci Numbers Recursively in C about my issue.
I am a bit stuck on how to keep on printing fibonacci numbers until it reaches about 40,000, in C# in my console application, How can I achieve this?
E.G, I want the application to do this:
0
1
1
2
3
5
8

and so on.

Thanks.
I'd hate to say this, but I had a brainwave, and solved it!
Here is what I did:
static void Main(string[] args)
{
    int num1 = 0;
    int num2 = 1;
    int sum = 1;
    while (num1 <= 15000)
    {
        sum = num1 + num2;
        num1 = num2;
        num2 = sum;
       Console.WriteLine(num2);
    }
    Console.ReadLine();
}

A: Just for fun, thought I'd throw in a fun way to do this with LINQ extension methods and a generator (infinite sequence):
// A utility class that holds math utility functions.
public static class MathUtility
{
    // This method returns the fibonacci sequence which is an
    // infinite sequence of numbers where each result is the
    // sum of the previous two results.
    public static IEnumerable<int> GetFibonacciSequence()
    {
        int first = 0;
        int second = 1;

        // first and second result are always 1.
        yield return first;
        yield return second;

        // this enumerable sequence is bounded by the caller.
        while(true)
        {
            int current = first + second;
            yield return current;

            // wind up for next number if we're requesting one
            first = second;
            second = current;
        }
    }
}

This generates an infinite (theoretically) sequence (it will eventually overflow if you let it go past range of int).
You can then call:
foreach(var num in MathUtility.GetFibonacciSequence().TakeWhile(num => num <= 40000))
{
    Console.WriteLine(num);
}

In this way, you have your presentation (the output) separate from the data generation.

A: How about something that has a loop in it? Like:
    static void main()
    {
        int num1 = 0;
        int num2 = 1;
        int sum = 1;
        Console.WriteLine(num1);
        while (sum < 40000)
        {
           sum = num1 + num2;
           num1 = num2;
           num2 = sum;
           Console.WriteLine(num2);
        }
    }

A: static int Fibonacci(int n)
{
    if(n <= 1) return n;
    else return Fibonacci(n - 1) + Fibonacci(n - 2);
}

static void PrintAllFibonacci()
{
    int n = 0;
    while(true)
        Console.WriteLine(Fibonacci(n++));
}

EDIT:
a different approach using a stack
static ulong Fibonacci(int n, IList<ulong> stack)
{
    ulong fibonacci;

    if (n <= 1)
    {
        fibonacci = (ulong)n;
    }
    else
    {
        ulong n1, n2;
        if (n < stack.Count)
            n1 = stack[n - 1];
        else
            n1 = Fibonacci(n - 1, stack);
        if (n - 1 < stack.Count)
            n2 = stack[n - 2];
        else
            n2 = Fibonacci(n - 2, stack);

        fibonacci = n1 + n2;
    }

    if (n >= stack.Count)
        stack.Add(fibonacci);

    return fibonacci;
}

static void PrintAllFibonacci()
{
    var stack = new List<ulong>();
    var n = 0;
    while(n < 50)
        Console.WriteLine(n + ") " + Fibonacci(n++, stack));
}

A: You can't do that recursively - remember, that each method call uses you stack. Google about, huh, stack overflow :)
You'll need to find iterating version of the algorithm, it's everywhere on the internet. And, of course, while fib numbers are quite quickly running up, it's impossible to output them forever.

A: Use the Closed form solution
    public static long ClosedFormFibonacci(int i)
    {
        const double phi = 1.61803398874989; // or use your own or calculate it
        const double sqrt5 = 2.23606798; // same as above
        return (long)Math.Round(Math.Pow(phi, i) / sqrt5);
    }

It looks like it overflows a long at about the 92nd Fibonacci number

A: C# doesn't easily support tail recursion so doing a simple recursion algorithm will cause a stack overflow with large enough numbers.  For this problem it would be simplest to use a loop instead of recursion.  If you're really stuck on recursion, here is a blog post that investigates both faking recursion and converting C# generated IL code to use tail recursion.

A: There are 2 major mistakes in your program:

*

*Multiple use of main()

*fibonacci_recursive is not created, though it is declared at the start of program.


text:
Q: What does it mean that a function is unbounded below in every neighborhood? In this paper Strong Convexity Does Not Imply Radial Unboundedness

In [3], Tapia gives this result showing that a strongly convex functional is either
radially unbounded (and so minima-existence results for bounded domains may be
applied to unbounded domains) or it is unbounded below in every neighborhood (in
which case the functional has no local minima and is unsuited for optimization).

I don't quite understand about a function is unbounded below in every neighborhood, could someone help to clarify? Thanks!

A: The example in this paper is of the form
$$ \|x\|^2 - \ell(x),$$
where $\ell$ is a linear discontinuous functional. You will have to require your underlying space to be infinite-dimensional for this weirdness to occur.
$f$ is unbounded below in every neighborhood – presumably of a point $x_0$ –  means that for every $\varepsilon>0$, we have $\inf f\big(B(x_0;\varepsilon)\big) = -\infty$, where $B(x_0;\varepsilon)$ is the ball entered at $x_0$ of radius $\varepsilon$.

A: It means just what it sounds like - that no matter how small you make the neighborhood around a point, you can always find some value in there where the function is extremely deep negative, no matter how small and no matter how deep you want to imagine it.
This can actually occur with a function on the real numbers, too. Such functions are not continuous. An example is
$$f(x) := \begin{cases} -q && \text{if $x = \frac{p}{q}$, rational in reduced form}\\ 0 && \text{otherwise} \end{cases}$$
Suppose $x = 3$. Note that $3 \approx 3 + 10^{-10000} = \frac{3 \times 10^{10000} + 1}{10^{10000}}$. This last fraction is in reduced form due to Bézout's lemma: taking $x = 1$ and $y = -3$ yields that $px + qy = 1$ (where $p$ and $q$ are the numerator and denominator of that fraction). Hence, the value of $f(x)$ at the point $3 + 10^{-10000}$ is $-10^{10000}$, and that will also work in general for $3 + 10^{-n}$ for any integer $n > 0$ by the same logic, e.g. we can even force $f$ to be deeper than negative Graham's number, in that same tiny neighborhood of $3$.
Your example does just the same thing, but in function spaces. Of course, to do that, we need some way to say that functions are/aren't "close together", but that's what the topology (which provides the neighborhoods) does. Then, we have a function of functions $F[f]$, and then it means that, for a given function and functions suitably "close" in that sense, we can do the same thing - no matter how close, we will always be able to find one that pounds the value into the ground as deep as we'd like it to.


text:
Q: Check if multiple tables exist The idea is to select 2 column response representing the table name and a boolean flag if it exists in the database for predefined list of tables. Is it possible to make such request in a single query?

A: You can use USER_TABLES dictionary view.
This view contains detail of the all tables that is owned by the current user.
You can achieve the desired result using following query:
WITH PREDEFINED_LIST_TABLES AS
(SELECT 'TABLE1' TABLE_NAME FROM DUAL UNION ALL
....
....)
SELECT P.TABLE_NAME ,
CASE WHEN U.TABLE_NAME IS NOT NULL THEN 1 ELSE 0 END AS TAB_EXISTS
FROM PREDEFINED_LIST_TABLES P
LEFT JOIN USER_TABLES U
ON (P.TABLE_NAME = U.TABLE_NAME);

Cheers!!


text:
Q: Solve the following equation. Question: $3^{x^2-5} - 9^{x-1} = 0$
$3^{x^2 -5} - 9^{x-1} = 0$
$3^{x^2 -5} = 9^{x-1}$
if $x = 3$
$3^{9-5} = 9^2$
$3^4 = 9^2$
$81 = 81$
and $x = 3$
Is this the right way to solve it?

A: HINT:
Using Exponent law, $\displaystyle(a^x)^y=a^{xy}$
We have, $$3^{x^2-5}=9^{x-1}=(3^2)^{x-1}$$
$$\implies 3^{x^2-5}=3^{2(x-1)}$$
Now if $\displaystyle a^x=a^y\implies a^{x-y}=1$ (assuming $a$ to be non-zero finite number)
either $a=1$
or $a=-1,x-y$ is even
or $x=y$ for real $a$

A: That approach certainly works, but you missed a root $x=-1$.  A more general approach to the problem is noting that $9 = 3^2$ and that $(x^a)^b = x^{ab}$.  Then we have
$$3^{x^2-5} - 9^{x-1} = 3^{x^2-5} - (3^2)^{x-1} = 3^{x^2-5} - 3^{2x-2} = 0 \implies 2x-2 =x^2 -5$$
We can just solve for $x$ now:
$$2x-2 = x^2 - 5 \implies x^2-2x-3 = (x-3)(x+1) = 0 \implies x=-1 \text{ or } x=3$$


text:
Q: How to remove duplicate tweets in Python? I am trying to retrieve about 1000 tweets from a search term like 'NFL' using tweepy and storing the tweets into a DataFrame using pandas. My issue is I can't find a way to remove duplicated tweets, I have tried df.drop_duplicates but it only gives me about 100 tweets to work with. Help would be appreciated!
num_needed = 1000
tweet_list = [] # Lists to be added as columns( Tweets, usernames, and screen names) in our dataframe
user_list = []
screen_name_list = []
last_id = -1 # ID of last tweet seen
while len(tweet_list) < num_needed:
    try:
        new_tweets = api.search(q = 'NFL', count = num_needed, max_id = str(last_id - 1), lang = 'en', tweet_mode = 'extended') # This is the criteria for collecting the tweets that I want. I want to make sure the results are as accurate as possible when making a final analysis.
    except tweepy.TweepError as e:
        print("Error", e)
        break
    else:
        if not new_tweets:
            print("Could not find any more tweets!")
            break
        else:
            for tweet in new_tweets:

                # Fetching the screen name and username

                screen_name = tweet.author.screen_name
                user_name = tweet.author.name

                tweet_text = tweet.full_text
                tweet_list.append(tweet_text)
                user_list.append(user_name)
                screen_name_list.append(screen_name)

df = pd.DataFrame()  #Create a new dataframe (df) with new columns
df['Screen name'] = screen_name_list
df['Username'] = user_list
df['Tweets'] = tweet_list

A: Well, yes, when you use .drop_duplicates(), you only get 100 tweets because that's how many duplicates there are. Doesn't matter what technique you use here, there are 900 or so duplicates with how your code runs.
So you might be asking, why? It by default returns only 100 tweets, which I am assuming you are aware of since you are looping and you try to get more by using the max_id parameter. However, your max_id, is always -1 here, you never get the id and thus never change that parameter. So one thing you can do, is while you iterate through the tweets, also collect the ids. Then after you get all the ids, store the minimum id value as last_id, then it'll work in your loop:
Code:
num_needed = 1000
tweet_list = [] # Lists to be added as columns( Tweets, usernames, and screen names) in our dataframe
user_list = []
screen_name_list = []
tw_id = [] #<-- ADDED THIS
last_id = -1 # ID of last tweet seen
while len(tweet_list) < num_needed:
    try:
        new_tweets = api.search(q = 'NFL -filter:retweets', count = num_needed, max_id = str(last_id - 1), lang = 'en', tweet_mode = 'extended') # This is the criteria for collecting the tweets that I want. I want to make sure the results are as accurate as possible when making a final analysis.
    except tweepy.TweepError as e:
        print("Error", e)
        break
    else:
        if not new_tweets:
            print("Could not find any more tweets!")
            break
        else:
            for tweet in new_tweets:

                # Fetching the screen name and username

                screen_name = tweet.author.screen_name
                user_name = tweet.author.name

                tweet_text = tweet.full_text
                tweet_list.append(tweet_text)
                user_list.append(user_name)
                screen_name_list.append(screen_name)

                tw_id.append(tweet.id)  #<-- ADDED THIS
    last_id = min(tw_id)  #<-- ADDED THIS

df = pd.DataFrame({'Screen name':screen_name_list,
                   'Username':user_list,
                   'Tweets':tweet_list})
df = df.drop_duplicates()

This returns to me aprox 1000 tweets.
Output:
print (len(df))
1084


text:
Q: Is restlet + simple combination suitable for production environment? I have a processing application which accepts REST requests and doesn't include a GUI such as a web front-end. Processing is light but the number of requests is quite high (more than 10,000 requests in a second).
I wonder if Restlet + Simple combination is appropriate for this scenario or do I have to use a Java EE edition?
Does anyone have experience with Restlet + Simple combination?

A: In Restlet, you have the concept of server connectors. This means that you could choose the appropriate connector for your need in a JSE environment (edition jse). It's clear that the default connector isn't suitable for production (it was even not present within org.restlet in the last version 2.3). So you can choose to use the Jetty extension (simply put the extension org.restlet.ext.jetty in your classpath - no impact in your application code) to use it as transport. We use successfully this approach in production (with load balancy in front of this) for one of our application.
If you don't want to handle load balancing, ... by yourself, you could prefer to use an application server to let it handle this.
Hope it helps you,
Thierry


text:
Q: Pandas dot-format date I want to get a column called Datetime with entries like 28.4.2014 12:20:49 into datetime format. When I do
df = pd.read_csv('LOG.TXT', delim_whitespace=True, names=['Datetime', 'x'])
df['Datetime'] = pd.to_datetime(df['Datetime'])
print(df['Datetime'])

I get 28.4.2014   2014-05-30 12:20:49
because Pandas does not parse the dot-format. What is the best solution?

A: Normally pandas should be able to parse this automatically, so I think something went wrong with you read_csv: you have a space in the datetimes, but you are also using whitespace as the delimiter, therefore it will put the date and time in different columns.
To illustrate this:
In [67]: s = """28.4.2014 12:20:49 1
   ....: 29.4.2014 12:20:49 2"""

In [68]: from StringIO import StringIO

In [69]: df = pd.read_csv(StringIO(s), delim_whitespace=True, names=['Datetime', 'x'])

In [70]: df
Out[70]:
           Datetime  x
28.4.2014  12:20:49  1
29.4.2014  12:20:49  2

In [71]: df['Datetime'][0]
Out[71]: '12:20:49'

In [72]: pd.to_datetime(df['Datetime'][0])
Out[72]: Timestamp('2014-05-30 12:20:49')

The date is set as the index, and the time is in the Datetime column. When converting this time with to_datetime, it will use the date of today.
To solve this, one possibility (I read it in as three columns, and say with parse_dates=[['Date', 'time']] to parse those two columns together to one datetime):
In [92]: df = pd.read_csv(StringIO(s), delim_whitespace=True,
   ....:                 names=['Date', 'time', 'x'], parse_dates=[['Date', 'time']])

In [93]: df
Out[93]:
            Date_time  x
0 2014-04-28 12:20:49  1

But if you have a more special format, you can always use the format keyword:
In [66]: pd.to_datetime("28.4.2014 12:20:49", format="%d.%m.%Y %H:%M:%S")
Out[66]: Timestamp('2014-04-28 12:20:49')


text:
Q: How can I define metafont functions in one file to avoid redefining them each time I make a new file? I have a metafont diagram that is generated by calling 4 functions that I know I will use multiple times with different parameters.
To avoid copy pasting like a madman, I'd like to have these function in their own file and include them only in a tex file if relevant or necessary.
However, right now I don't even know how to make them their own command, let alone including them from other files:
Result:

code:
\documentclass[border=10cm]{standalone}

\usepackage{luamplib}
\mplibnumbersystem{double}
\usepackage[margin=0.5cm]{geometry}

\begin{document}
{\centering
\begin{mplibcode}
u:=1cm;

% Draw a lattice layer upside down
% parameters are: horizontal offset, level (height), thickness of % the lines, color of the lines
vardef inverted_layer(expr n,l,s,c)=
     %declare variables
    save parent, lc, rc;
    pair parent, lc, rc;
    parent:=(n, l);
    % assign values of left and child nodes, forming a 'v' pattern
    lc :=  (n-1, l+1);
    rc :=  (n+1, l+1);
    draw u*parent--u*rc withpen pencircle scaled s withcolor c;
    draw u*parent--u*lc withpen pencircle scaled s withcolor c;
enddef;

% Draw and inverted lattice
% parameters are: horizontal offset, number of layers, thickness
% of the lines, color of the lines
vardef inverted_lattice(expr n,l, size, color)=
    for i=0 upto l:
        for j=0 upto i:
            inverted_layer((j + n)*2 - i, i-(l+1), size, color);
        endfor;
    endfor;
enddef;

% Similar as above except the lattice isn;t upside down
vardef layer(expr n,l,s,c)=
    save parent, lc, rc;
    pair parent, lc, rc;
    parent:=(n, l);
    lc :=  (n-1, l-1);
    rc :=  (n+1, l-1);
    draw u*parent--u*rc withpen pencircle scaled s withcolor c;
    draw u*parent--u*lc withpen pencircle scaled s withcolor c;
enddef;

vardef lattice(expr n,l, size, color)=
for i=0 upto l:
    for j=0 upto i:
            layer((j + n)*2 - i, -i, size, color);
        endfor;
    endfor;
enddef;

% Start figure
beginfig(0);
% Create labels for the bottom level
for i=-3 upto 7:
    save j;
    numeric j;
    j := i - 2;
    % No plus symbol for egatives
    if j<0:
        label.top(textext("\huge$K_{i"& decimal j &"}$"), (i*u*2 + 1*u,-6*u));
    % no arithmetic symbols for 0
    elseif j=0:
        label.top(textext("\huge$K_{i}$"), (i*u*2+1*u,-6*u));
    % regular labeling
    else:
        label.top(textext("\huge$K_{i+"& decimal j &"}$"), (i*u*2+1*u,-6*u));
    fi
endfor;
for i=0 upto 5:
    %create labels for the top level
    if i-3<0:
        label.top(textext("\huge$C_{i"& decimal(i-3)&"}$"), (i*u*2,0));
    elseif i-3=0:
        label.top(textext("\huge$C_{i}$"), (i*u*2,0));
    else:
        label.top(textext("\huge$C_{i+"& decimal(i-3) &"}$"), (i*u*2,0));
    fi
    % draw 5 regular lattices in black at different offsets
    % so that they partially overlap
    lattice(i,4,1, black);
endfor;

% draw the inverted red lattice with thick lines
inverted_lattice(2.5,4,3, red);

z0=u*(2,0);
z1=u*(3,-1);
z2=u*(2,-2);
z3=u*(1,-3);
z4=u*(0,-4);
z5=u*(1,-5);
z6=u*(2,-6);

% draw the blue path
draw z0--z1--z2--z3--z4--z5--z6 withpen pencircle scaled 3bp withcolor blue;
for i=0 upto 6:
    fill fullcircle scaled 4bp shifted z[i];
endfor;
endfig;
\end{mplibcode}
\par}
\end{document}

A: You can do so using an input command, i.e. input myfilewithmymacros.mp; at the start of the mplibcode environment in which you would like them available.  If you will be doing so often, then you can use the \everymplib command (as below) to input the file at the start of every mplibcode environment.  I also enabled textext labels, so that the \textext command isn't required.
\documentclass{article}
\begin{filecontents*}{makogandefs.mp}
% Draw a lattice layer upside down
% parameters are: horizontal offset, level (height), thickness of % the lines, color of the lines
vardef inverted_layer(expr n,l,s,c)=
     %declare variables
    save parent, lc, rc;
    pair parent, lc, rc;
    parent:=(n, l);
    % assign values of left and child nodes, forming a 'v' pattern
    lc :=  (n-1, l+1);
    rc :=  (n+1, l+1);
    draw u*parent--u*rc withpen pencircle scaled s withcolor c;
    draw u*parent--u*lc withpen pencircle scaled s withcolor c;
enddef;

% Draw and inverted lattice
% parameters are: horizontal offset, number of layers, thickness
% of the lines, color of the lines
vardef inverted_lattice(expr n,l, size, color)=
    for i=0 upto l:
        for j=0 upto i:
            inverted_layer((j + n)*2 - i, i-(l+1), size, color);
        endfor;
    endfor;
enddef;

% Similar as above except the lattice isn;t upside down
vardef layer(expr n,l,s,c)=
    save parent, lc, rc;
    pair parent, lc, rc;
    parent:=(n, l);
    lc :=  (n-1, l-1);
    rc :=  (n+1, l-1);
    draw u*parent--u*rc withpen pencircle scaled s withcolor c;
    draw u*parent--u*lc withpen pencircle scaled s withcolor c;
enddef;

vardef lattice(expr n,l, size, color)=
for i=0 upto l:
    for j=0 upto i:
            layer((j + n)*2 - i, -i, size, color);
        endfor;
    endfor;
enddef;
\end{filecontents*}
\usepackage{luamplib}
    \everymplib{input makogandefs.mp;}
    \mplibtextextlabel{enable}
\begin{document}

\begin{mplibcode}
% Start figure

beginfig(0);
u:=1cm;
% Create labels for the bottom level
for i=-3 upto 7:
    save j;
    numeric j;
    j := i - 2;
    % No plus symbol for egatives
    if j<0:
        label.top("\huge$K_{i"& decimal j &"}$", (i*u*2 + 1*u,-6*u));
    % no arithmetic symbols for 0
    elseif j=0:
        label.top("\huge$K_{i}$", (i*u*2+1*u,-6*u));
    % regular labeling
    else:
        label.top("\huge$K_{i+"& decimal j &"}$", (i*u*2+1*u,-6*u));
    fi
endfor;
for i=0 upto 5:
    %create labels for the top level
    if i-3<0:
        label.top("\huge$C_{i"& decimal(i-3)&"}$", (i*u*2,0));
    elseif i-3=0:
        label.top("\huge$C_{i}$", (i*u*2,0));
    else:
        label.top("\huge$C_{i+"& decimal(i-3) &"}$", (i*u*2,0));
    fi
    % draw 5 regular lattices in black at different offsets
    % so that they partially overlap
    lattice(i,4,1, black);
endfor;

% draw the inverted red lattice with thick lines
inverted_lattice(2.5,4,3, red);
endfig;
\end{mplibcode}

\end{document}

Once you have compiled the above, try the following document:
\documentclass{article}

\usepackage{luamplib}
    \mplibtextextlabel{enable}
\begin{document}

\begin{mplibcode}
input makogandefs.mp;

beginfig(0);
u:=1cm;
inverted_lattice(2.5,4,3, red);
endfig;
\end{mplibcode}

\end{document}

If you get tired of typing input makogandefs.mp; at the start of each mplibcode block, then the \everymplib command can be used as above and it will be inserted automatically.


text:
Q: Writing 2 lists to a csv as column names and subsequent values I have 2 lists and I am trying to create a csv from them. I want to write the values of the 1st list as column names and the entries from 2nd list as the corresponding values for those columns. For e.g.:
1st list = ['A', 'B', 'C','D','E']
2nd list = [['1','2','3','4','5'], ['6','7','8','9','10']]

I want the csv to look like:
A     B     C     D     E
1     2     3     4     5
6     7     8     9     10

I tried writing the 1st list as a single row using csv writer.writerows and it successfully came as the column names. However, when I try to write the 2nd list to the same csv file, it overwrites the column names. I also tried to zip both the lists and then write them to the file but that also didn't help.
Could you please suggest me the way to approach this problem? I would appreciate the suggestions. Thanks!

A: In[2]: one = ['A', 'B', 'C','D','E']
  ...: two = [['1','2','3','4','5'], ['6','7','8','9','10']]
In[3]: import csv
  ...:
  ...: with open('outfile.csv', 'w') as f:
  ...:     writer = csv.writer(f)
  ...:     writer.writerow(one)
  ...:     writer.writerows(two)
  ...:
In[4]: with open('outfile.csv', 'r') as f:
  ...:     print(f.read())
  ...:
A,B,C,D,E
1,2,3,4,5
6,7,8,9,10


text:
Q: javascript push duplicating values I have a single input row that needs to be expanded to create multiple rows, with 6 fields being repeated on each row, and one unique field added to each row.  The unique fields are stored in arrparentjobs array, and I know that they have unique values.
When the code runs, the resulting rows all contain the exact same data, which happens to be the values of the last items being pushed.
What am I doing wrong here?
Thanks much,
Joe
var dataRowsOutput = [];
arrVolDataOutput.playerid = volDataRow.playerId;
arrVolDataOutput.timestamp = volDataRow.timestamp;
arrVolDataOutput.playername = volDataRow.playerName;
arrVolDataOutput.parentname = volDataRow.parent1Name;
arrVolDataOutput.parentphone = volDataRow.parent1Phone;
arrVolDataOutput.parentemail = volDataRow.parent1Email;
for (var j = 0; j < arrparentjobs.length; ++j) {
  arrVolDataOutput.parentjob = arrparentjobs[j];
  dataRowsOutput.push(arrVolDataOutput);
  continue;
}

A:
the resulting rows all contain the exact same data

Yes they do and they do because push pushes a reference – not a deep or even shallow copy – onto the array and you're simply changing the parentjob while pushing the exact same arrVolDataOutput object onto the array over and over again.
You need to create a new object on each iteration, something like this:
var dataRowsOutput = [];
for (var j = 0; j < arrparentjobs.length; ++j) {
  dataRowsOutput.push({
    parentjob:   arrparentjobs[j],
    playerid:    volDataRow.playerId,
    timestamp:   volDataRow.timestamp,
    playername:  volDataRow.playerName,
    parentname:  volDataRow.parent1Name,
    parentphone: volDataRow.parent1Phone,
    parentemail: volDataRow.parent1Email
  });
}

If there are other fields in your arrVolDataOutput then you'll need to include those in the object literal as well.


text:
Q: Adding Angular 5 to ASP.Net MVC 5 application breaks build The setup:

*

*ASP.Net MVC 5 application (v4.5.2).

*Angular (v5.2.0) using angular-cli(v1.7.4) inside the MVC application.

*Angular app runs on www.mydomain.com/app.

*The angular application is loaded in the Index view of the AppController.

*The necessary JS and CSS output files in the dist folder are referenced using BundleConfig.cs.

*The build process has been modified to build the Angular application using the .csproj file.

*ng build is using -extract-css(-ec) so that the Index.cshtml file does not have to change between dev and production.

*Everything works correctly up to this point.

.csproj:
<Target Name="NgDebug" BeforeTargets="Build" Condition="'$(Configuration)' == 'Debug'">
    <Exec WorkingDirectory="$(ProjectDir)admin-client" Command="ng build -ec" />
  </Target>
  <Target Name="NgRelease" BeforeTargets="Build" Condition="'$(Configuration)' == 'Release'">
    <Exec WorkingDirectory="$(ProjectDir)admin-client" Command="ng build --prod" />
  </Target>

The problem:

*

*When --watch (-w) is added to the Command="ng build -ec" the build hangs indefinitely and doesn't throw any errors.

*Build output hangs: 1>------ Build started: Project: CorpNet.Admin.Web, Configuration: Debug Any CPU ------
My solution:
After the application starts I run ng build -ec -w via the command line and everything works correctly.
Question:
How do you add the --watch (-w) to ng build -ec as part of the build process instead of running it manually from the command line?

A: You shouldn't.
A build needs the command to complete. Even if you spawn a watching process from the build, you have no way to control the lifecycle of that application.
So a single build during a csproj build is okay but after the build completes, no additional processes should be left over. Depending on which tool you use to build, a csproj file may even be built multiple times (design-time builds vs. actual builds).
You could however run angular commands from inside your application so the Angular Cli can rebuild your client side part while your application is running.
For ASP.NET Core, this is readily set up using the SPA Services that take care of integrating the Angular CLI with the ASP.NET Core pipeline (installable templates for 2.0, integrated in upcoming 2.1 tooling). See Use the Angular project template with ASP.NET Core


text:
Q: Expected catch() or return (promise/catch-or-return) I am new to JavaScript.This is my first function in javascript to deploy a function on the firebase.
Got this error:
 - [eslint] Unexpected function expression. (prefer-arrow-callback)
 - [eslint] Expected catch() or return (promise/catch-or-return)

What is wrong with this function?
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);

exports.grantSignupReward = functions.database.ref('/users/{uid}/last_signin_at')
  .onCreate(event => {
  var uid = event.params.uid;

  admin.database().ref('users/${uid}/referred_by')
    .once('value').then(function(data) {
    var referred_by_somebody = data.val();

    if (referred_by_somebody) {
      var moneyRef = admin.database()
      .ref('/users/${uid}/inventory/pieces_of_eight');

      moneyRef.transaction(function(current_value) {
        return (current_value || 0) + 50;
      });
    }
  });
});

A: In order to solve promise/catch-or-return, just add a .catch(() => null) at the end of the line. And of course, don't forget to actually implement the error handling logic at some point in the not-so-distant future.

A: The first error suggests you to use an arrow function as a callback. So you need to replace the regular functions, (function() { ... }), with arrow functions, (() => { ... }).
The second error suggests that you either need to catch the promise rejection, or return the promise itself. I am not too sure about your code but I believe that this method:
admin.database().ref('users/${uid}/referred_by').once('value')

returns a promise. So it needs to be returned like this:
return admin.database().ref('users/${uid}/referred_by').once('value')

or handle the error like this:
admin.database().ref('users/${uid}/referred_by').once('value')
  // ... your code here
  .catch(error => { ... });

As @Bergi pointed out in the comments that returning the promise is not preferable here, you may just add a catch block to your promise.