text:
Q: Define F# '**' operator in C# I see that F# uses the ** operator for powers, so 2 ** 5 = 32. This is different from C#, where you have the option to use the '^' operator in your custom types, but for some reason isn't used by the built in number types.
But how do you implement the ** operator in C# for use in an F# project?
If I do this in C#:
public static Integer operator ^(Integer left, Integer right)
{
    if (Integer.IsNaN(left) || Integer.IsNaN(right)) return NaN;
    return left.RaiseToPower(right);
}

It compiles fine, and I can use it the same way as the '+' operator, but neither of these work in F#:
let intgr3 = intgr1 ** intgr2

let intgr3 = intgr1 ^ intgr2

And in C#, this doesn't work:
public static Integer operator **(Integer left, Integer right)
{
    if (Integer.IsNaN(left) || Integer.IsNaN(right)) return NaN;
    return left.RaiseToPower(right);
}

So how do I define the F# equivalent of the ** operator in C#?
Thanks.

A: As I said in my comments, C# does not let you define new operators and ** is not an operator in C#. ^ is an operator, however it is the logical XOR operator, NOT the exponentiation operator. This gave me a hint that F# might be translating your C# operator into native F# (^^^ for logical XOR).
So, I created a couple test projects and using your definition of ^, here's what I found  in F#:
open CSLib // CSLib is the C# library

let ( ** ) (x : Integer) (y : Integer) = x.RaiseToPower y

let x = new Integer()
let y = new Integer()

let a = x ^ y // error
let b = x ^^^ y // compiles, but looks like XOR
let c = x ** y // compiles

You can define new global operators in F#, however if you want this to be a general library that may not be acceptable.
You can define the Exponentiation operator for use in F# by defining a public static method Pow in the Integer type in your C# library:
public static Integer Pow(Integer left, Integer right)
{
    if (Integer.IsNaN(left) || Integer.IsNaN(right)) return NaN;
        return left.RaiseToPower(right);
}

Then, you are able to use it directly in F# as **. I will note that overloaded operators in C# are not idiomatic so having a Pow method will seem quite natural to C# users.

A: I believe the reason why you can't define a ** operator for your object is that this is not one of the operators supported by the language. It's not a recognized operator..
Why not just use the Math library
http://msdn.microsoft.com/en-us/library/system.math.pow.aspx


text:
Q: JavaFX Button which adds and removes Checkboxes I was trying to create a button which deletes checked CheckBox but don't know how to make "cb" the same as in the Adding button.
package sample;

import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.control.Button;
import javafx.scene.control.CheckBox;
import javafx.scene.control.TextField;
import javafx.scene.layout.VBox;

public class Controller {

    @FXML
    private Button add;
    @FXML
    private Button delete;
    @FXML
    private VBox vbox;
    @FXML
    private TextField text;
    @FXML
    private CheckBox cb;

    @FXML
    void initialize() {

    }

    @FXML
    public void onAdd(ActionEvent e) {
        CheckBox cb = new CheckBox(text.getText());
        vbox.getChildren().add(cb);
        if (text.getText().matches("")) {
            vbox.getChildren().remove(cb);
        }

    }
    @FXML
    public void onDelete(ActionEvent e) {

        if(cb.isSelected()){
                vbox.getChildren().remove(cb);
            }
        }

    }

The "cb" in onAdd event isn't the same as in onDelete event. How can i solve it ?

A: Note that it's possible to add multiple CheckBoxes with the code you've posted. It's unclear which one should be removed. Of course you can access the children the way you access any other list elements. You deed to add a cast of course, since children is a List<Node>. If all children of vbox are CheckBoxes, you could simply iterate through all the children and remove all those CheckBoxes that are selected (assuming this is the functionality you're trying to achieve).
vbox.getChildren().removeIf(child -> ((CheckBox) child).isSelected());

If this is not the case, you could store the elements in a List<CheckBox> field:
private final List<CheckBox> checkBoxes = new ArrayList<>();

@FXML
public void onAdd(ActionEvent e) {
    if (text.getText().isEmpty()) { // alternative: text.getText().equals(""); matches is for regular expressions
        CheckBox cb = new CheckBox(text.getText());
        vbox.getChildren().add(cb);
        checkBoxes.add(cb);
    }
}

@FXML
public void onDelete(ActionEvent e) {

    Iterator<CheckBox> iter = checkBoxes.iterator();
    while (iter.hasNext()) {
        CheckBox cb = iter.next();
        if (cb.isSelected()) {
            // remove from both vbox and checkBoxes
            vbox.getChildren().remove(cb);
            iter.remove();
        }
    }
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Why some circuits uses additional resistor with pot in dividers? Are there any profits of using the first circuit for divider instead of the second one?

simulate this circuit – Schematic created using CircuitLab

A: The circuit on the right will have the full range of the voltage connected. The circuit on the left will have the maximum given by the voltage divider of  \$R_1\$ and \$R_2\$. This is if you want to limit the maximum voltage to a lower value than the maximum voltage in the circuit.

A: Yes: it has a different range. Depending on the application, that may be what you want.

A: The primary reason one does this (left hand side) in the real world is to prevent hazardous conditions from arising. In some pots if you move the wiper off of the end of the track it can short out or open circuit (it very much depends upon the construction).
Some op-amps don't want heir inputs being driven to the rail, so you'd put a series resistor in there to ensure that it always stay within the operational range of the op-amp input.
In some cases if the pot shorts you want to prevent high currents from running through the pot and collapsing the rail, over heating etc.
So yes, it can be bad and limit your range of operation, but it is primarily used to protect for faults.
Of course there are uses where it makes sense to only vary resistance between certain values. In that case it is not a problem.

A: Safety.  A series resistor is connected so that the load resistance cannot become \$ 0\Omega\$.

simulate this circuit – Schematic created using CircuitLab
If you connect a load to the wiper of your pot, a portion of the pot (top) is in series with the load (wiper) and the remainder is in parallel with the load.  As the pot is adjusted, Load Voltage varies from 0V to 12V.
But if you connect the wiper to one end of the pot, you effectively have a resistance which varies from 0\$\Omega\$ to rated resistance.

simulate this circuit
As you move the wiper to the top, the series resistance will decrease to \$ 0\Omega\$, which would mean \$\infty\$ current.  So to protect the pot from burning up or overloading the source, a series resistance is added.

A: In your example, consider what the output would be:
In the first circuit, the output ranges from \$0 \Leftrightarrow(V-I_{R1}R1)\$
In the second circuit, the output ranges from \$0 \Leftrightarrow V\$
So, if you need a variable divider with some hard limits, external resistors are the way to go.


text:
Q: How can I detect the proximity between two images I am trying to make a game for a school project. I am trying to detect when two images are 5 pixels apart. I cant seem to find an algorithm to determine what the distance is. Any help is appreciated.
import javax.swing.JFrame;

public class Main extends JFrame {
    Screen screen;

    public Main() {

        setSize(500, 400);
        setResizable(false);
        setTitle("The Adventures of BLANK") ;
        setLocationRelativeTo(null) ;

        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        init();

    }

    public static void main(String[] args) {
        Main main = new Main();
    }

    public void init() {
        screen = new Screen();
        add(screen);
        addKeyListener(screen);
        setVisible(true);
    }
}

The Second Class
public void loadImages() {
    try {
        awesomeFace = ImageIO.read(getClass().getResource("/AwesomeFace.png"));
        Trollface = ImageIO.read(getClass().getResource("/Trollface.png")) ;
    } catch (IOException e) {
        e.printStackTrace();
    }
}
public Screen() {
    loadImages();
    Thread thread = new Thread(this);
    thread.start();
}

public void run() {
    while(running) {
        //Game Loop Start
        if (trolly+trollx > x + y) {
            proximity = trolly+trollx - x + y ;
        } else {
            proximity = x+y - trollx +trolly ;
        }

        if(left) {
            if (proximity <= 3) {
                y = 700 ;
                x = 700 ;
            }
            if (x == 0) {

            } else {
                x--;
            }
        }

        if(right) {
            if (proximity - x <= 3) {
                y = 700 ;
                x = 700 ;
            }
            if (x >=450) {

            } else {
                x++;
            }
        }

        if(up) {
            if (proximity - x <= 3) {
                y = 700 ;
                x = 700 ;
            }
            if (y == 0) {
            } else {
            y--;
            }
        }

        if(down) {
            if (proximity - x <= 3) {
                y = 700 ;
                x = 700 ;
            }
            if (y == 325) {
            } else {
            y++;
            }
        }

        if (trollup) {
            if (proximity - x <= 3) {
                y = 700 ;
                x = 700 ;
            }
        if (trolly == 0) {
            } else {
            trolly -- ;
            }
    }
        if (trolldown) {
            if (proximity - x <= 3) {
                y = 700 ;
                x = 700 ;
            }
            if (trolly == 325) {
                } else {
                trolly ++ ;
                }
        }
        if (trollleft) {
            if (proximity <= 3) {
                y = 700 ;
                x = 700 ;
            }
            if (trollx == 0) {
                } else {
                trollx -- ;
                }
        }
        if (trollright == true) {
            if (trollx - x <= 3) {
                y = 700 ;
                x = 700 ;
            }if (trollx == 450) {
                } else {
                trollx ++ ;
                }

        }

        //Game Loop End
        try {
            Thread.sleep(2);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

protected void paintComponent(Graphics g) {
    super.paintComponent(g);
    //Graphical loop start
    g.drawImage(awesomeFace, x, y, null);
    g.drawImage(Trollface, trollx, trolly, null) ;

    //Graphical loop end
    repaint();
}

@Override
public void keyPressed(KeyEvent e) {

    if(e.getKeyCode() == 87) {
        trollup = true;
    }

    if(e.getKeyCode() == 65){
        trollleft = true;
    }

    if(e.getKeyCode() == 83) {
        trolldown = true;
    }

    if(e.getKeyCode() == 68) {
        trollright = true;
    }

    if(e.getKeyCode()==37) {
        //Left
        left = true;
    }

    if(e.getKeyCode()==38) {
        //Up
        up = true;
    }

    if(e.getKeyCode()==39) {
        //Right
        right = true;
    }
    if(e.getKeyCode()==40) {
        //Down
        down = true;
    }
}

public void keyReleased(KeyEvent e) {
    if(e.getKeyCode()==37) {
        //Left
        left = false;
    }

    if(e.getKeyCode()==38) {
        //Up
        up = false;
    }

    if(e.getKeyCode()==39) {
        //Right
        right = false;
    }
    if(e.getKeyCode()==40) {
        //Down
        down = false;
    }
    if(e.getKeyCode() == 87) {
        trollup = false;
    }

    if(e.getKeyCode() == 65){
        trollleft = false;
    }

    if(e.getKeyCode() == 83) {
        trolldown = false;
    }

    if(e.getKeyCode() == 68) {
        trollright = false;
    }
}

@Override
public void keyTyped(KeyEvent e) {

}


text:
Q: IO Operations in Conduit? This is probably a pretty obscure case, but please bear with me.
I'm writing a web crawler that needs to download webpages and save them to local disk.  Meanwhile, being a crawler, it needs to find the hyperlinks on each page and download those linked pages as well.
Right now I'm looking at the first sample code given on this page.  I'm trying to write a conduit of this type:
processLink :: Conduit S.ByteString IO S.ByteString

And then I will replace this line in the sample code:
responseBody res $$+- sinkFile "foo.txt"

with this line:
responseBody res $= processLinks $$+ sinkFile

So what I'm trying to do is to implement a conduit called processLink, which processes a ByteString, extracks links from them, and then pass the original ByteString along to sinkFile so that the page can be saved.  Then I can call functions on those links recursively to download those linked pages.
However, since processLink is a pure function, it seems like I can't do any IO operations inside processLink, and therefore cannot do the things I need like downloading those linked pages.  Or can I?  What could I do to get around this problem?

A: Alright I figured it out.... I think what I need is just liftIO lol.  Sorry I'm kinda new to Haskell :P


text:
Q: Mapping RGB Values to color names MATLAB I've been working on performing K-means clustering on images in different color spaces. The cluster centers are representative of the color value and I would like to describe the color value by a color name.
Example of the results of the clustering operation :

I would now like to describe the color names of these 3 pixels (RGB values) from the segmented img:
 134.2263  146.4977  194.6406
 137.5899   78.5631   50.4859
 111.6383  131.4764   36.3863

to get outputs like : dark green, brown, light purple etc.
I'm thinking this is similar to using HTML color codes but I am not sure how to apply this in matlab.
There are similar questions on stackoverflow but related to python,java etc not matlab. Is there any matlab functionality which would make this feasible?
Thank you!

A: A solution sketch:
Download a web page containing information about rgb values and matching names:
ctable = urlread('https://en.wikipedia.org/wiki/List_of_colors_%28compact%29');

Parse rgb values, each value happens to appear twice:
rgb_vals = regexp(ctable,'rgb\([0-9]+,[0-9]+,[0-9]+\)','match')';
rgb_vals = rgb_vals(1:2:end);

Parse color names: this might be a little bit more tricky, but possible. Just make sure the order matches the parsed list of rgb values, by examining a few pairs.
Finally, construct a KNN classifier, that is given a new rgb value find the closest rgb value in your table, and output the matching name. You can use Matlab's knn.
Another similar option is to look for an online rgb-to-name converter, and send a request to it each time you need.
EDIT
It might be easier to first split the content in ctable by line-endings, then when you find a line with rgb value you can look for the name in the following line.


text:
Q: compare values using regex sql Does anyone knows how to say if val1 = X/state/Amercia/LA/ or X/state/ the val2 = 'LA'.
code
 when TRIM(val1) like '^X*/state/' or TRIM(val1) like '^X*/LA/' then 'LA'

Thank you

A: Given these results (please note I preserved the spelling of 'Amercia'):
select trim('X/state/Amercia/LA/') ~ '^X/state/($|Amercia/LA/$)';
 ?column?
----------
 t
(1 row)

select trim('X/state/Amercia/LA/') ~ '^X/state/($|Amercia/LA/$)';
 ?column?
----------
 t
(1 row)

select trim('X/state/') ~ '^X/state/($|Amercia/LA/$)';
 ?column?
----------
 t
(1 row)

select trim('X/state/SomethingElse') ~ '^X/state/($|Amercia/LA/$)';
 ?column?
----------
 f
(1 row)

select trim('Xother') ~ '^X/state/($|Amercia/LA/$)';
 ?column?
----------
 f
(1 row)

select trim('X/state/Amercia/VA') ~ '^X/state/($|Amercia/LA/$)';
 ?column?
----------
 f
(1 row)

Your when should be:
  when trim(val1) ~ '^X/state/($|Amercia/LA/$)' then 'LA'


text:
Q: I'm trying to scrape stock prices off of Yahoo Finance, and I'm targeting the price. But when I run my code I get "None" in my output Here's my code.
import requests
from bs4 import BeautifulSoup
url = 'https://ca.finance.yahoo.com/quote/AAPL?p=AAPL'
r= requests.get(url)
soup = BeautifulSoup(r.text, 'html.parser')
price = soup.find('span', {'class': 'Trsdu(0.3s) Fw(b) Fz(36px) Mb(-4px) D(ib)'})
print(price)

The output just returns "None"

A: You need to set the user agent in the header, here's my working code:
import requests
from bs4 import BeautifulSoup
url = 'https://ca.finance.yahoo.com/quote/AAPL?p=AAPL'
headers = {
    'User-agent': 'Mozilla/5.0',
}
r= requests.get(url, headers=headers)
print(r.status_code)
soup = BeautifulSoup(r.text, 'html.parser')
price = soup.find("span", {"class":['Trsdu(0.3s)', 'Fw(b)', 'Fz(36px)', 'Mb(-4px)', 'D(ib)'] })
print(price.contents)

#output
# 200
# ['20,475.42']

As other commenters has mentioned, you could use some wrapper library or yahoo finance api.

A: Your request is being returned a 404 by the server (probably because it is not very legitimate looking). Because of this the html parser can't find what you're looking for hence the output None. You can get around this by adding a user-agent to your request like such.
import requests
from bs4 import BeautifulSoup
url = 'https://ca.finance.yahoo.com/quote/AAPL?p=AAPL'
headers = {"User-Agent": "Mozilla/5.0 (platform; rv:geckoversion) Gecko/geckotrail Firefox/firefoxversion"}
r = requests.get(url, headers=headers)
soup = BeautifulSoup(r.text, 'html.parser')
price = soup.find('span', {'class': 'Trsdu(0.3s) Fw(b) Fz(36px) Mb(-4px) D(ib)'})
print(price)

But as the commenters mentioned you should really check out their api since Yahoo provides a tool for what you are trying to do.

A: You can get the stock data with the yfinancelibrary: https://pypi.org/project/yfinance/
It is really useful!. It lets you obtain the information from the different stocks with the ticker. You'll see that it is better than creating a custom scraper.


text:
Q: R's padr package claiming the "datetime variable does not vary" when it does vary library(tidyverse)
library(lubridate)
library(padr)

df
#> # A tibble: 828 x 5
#>    Scar_Id      Code     Type         Value      YrMo
#>    <chr>        <chr>    <chr>        <date>     <date>
#>  1 0070-179     AA       Start_Date   2020-04-22 2020-04-01
#>  2 0070-179     AA       Closure_Date 2020-05-23 2020-05-01
#>  3 1139-179     AA       Start_Date   2020-04-23 2020-04-01
#>  4 1139-179     AA       Closure_Date 2020-05-23 2020-05-01
#>  5 262-179      AA       Start_Date   2019-08-29 2019-08-01
#>  6 262-179      AA       Closure_Date 2020-05-23 2020-05-01
#>  7 270-179      AA       Start_Date   2019-08-29 2019-08-01
#>  8 270-179      AA       Closure_Date 2020-05-23 2020-05-01
#>  9 476-179      BB       Start_Date   2019-09-04 2019-09-01
#> 10 476-179      BB       Closure_Date 2019-11-04 2019-11-01
#> # ... with 818 more rows

I have an R data frame named df shown above. I want to concentrate on row numbers 5 and 6. I can usually use the package padr to pad the months in between rows 5 and 6. The pad() function of the padr will basically add rows at intervals the user specifies, best shown as the added rows "X" below.
#>  1 0070-179     AA       Start_Date   2020-04-22 2020-04-01
#>  2 0070-179     AA       Closure_Date 2020-05-23 2020-05-01
#>  3 1139-179     AA       Start_Date   2020-04-23 2020-04-01
#>  4 1139-179     AA       Closure_Date 2020-05-23 2020-05-01
#>  5 262-179      AA       Start_Date   2019-08-29 2019-08-01
#>  X 262-179      NA       NA           NA         2019-09-01
#>  X 262-179      NA       NA           NA         2019-10-01
#>  X 262-179      NA       NA           NA         2019-11-01
#>  X 262-179      NA       NA           NA         2019-12-01
#>  X 262-179      NA       NA           NA         2020-01-01
#>  X 262-179      NA       NA           NA         2020-02-01
#>  X 262-179      NA       NA           NA         2020-03-01
#>  X 262-179      NA       NA           NA         2020-04-01
#>  6 262-179      AA       Closure_Date 2020-05-23 2020-05-01
#>  7 270-179      AA       Start_Date   2019-08-29 2019-08-01
#>  8 270-179      AA       Closure_Date 2020-05-23 2020-05-01
#>  9 476-179      BB       Start_Date   2019-09-04 2019-09-01
#> 10 476-179      BB       Closure_Date 2019-11-04 2019-11-01

To get there I usually issue a command, such as is shown below, and it works fine in padr. But it doesn't work in my specific example, and instead yields the warning shown below.
df %>% pad(group = "Scar_Id", by = "YrMo", interval = "month")

#> # A tibble: 828 x 5
#>    Scar_Id      Code     Type         Value      YrMo
#>    <chr>        <chr>    <chr>        <date>     <date>
#>  1 0070-179     AA       Start_Date   2020-04-22 2020-04-01
#>  2 0070-179     AA       Closure_Date 2020-05-23 2020-05-01
#>  3 1139-179     AA       Start_Date   2020-04-23 2020-04-01
#>  4 1139-179     AA       Closure_Date 2020-05-23 2020-05-01
#>  5 262-179      AA       Start_Date   2019-08-29 2019-08-01
#>  6 262-179      AA       Closure_Date 2020-05-23 2020-05-01
#>  7 270-179      AA       Start_Date   2019-08-29 2019-08-01
#>  8 270-179      AA       Closure_Date 2020-05-23 2020-05-01
#>  9 476-179      BB       Start_Date   2019-09-04 2019-09-01
#> 10 476-179      BB       Closure_Date 2019-11-04 2019-11-01
#> # ... with 818 more rows
#> Warning message:
#> datetime variable does not vary for 537 of the groups, no padding applied on this / these group(s)

Why does it claim that "the datetime variable does not vary" for rows 5 and 6, when the datetime does indeed vary. The datetime for row 5 variable YrMo is "2019-08-01" and the datetime for row 6 variable YrMo is "2020-05-01". Let me state the obvious that "2019-08-01" varies from "2020-05-01".
Any ideas what went wrong? I tried to create a reproducible example and could not. The basic examples I created all work as expected (as I describe). Hopefully these clues can help somebody determine what is going on.


text:
Q: Change scrollbar style only when horizontal I have a horizontal scroll section on my website but i want to change the scroll style, iv'e managed to change the scroll bar style using '''::-webkit-scrollbar''' tag but it also affects the vertical scroll. I only want to change the scroll bar when its to slide content horizontally.
Any responses are greatly appreciated.

A: You can use ::webkit-scrollbar with particular class.
For example:
Let the container be '.scroll-content'
.scroll-content::-webkit-scrollbar-track{-webkit-box-shadow: inset 0 0 6px rgba(0,0,0,0.1);box-shadow: inset 0 0 6px rgba(0,0,0,0.1);background-color: #ccc;}
.scroll-content::-webkit-scrollbar{width: 5px;height: 5px;background-color: #ccc;}
.scroll-content::-webkit-scrollbar-thumb{background-color: #ff7043;}

But this method is not applicable in Mozilla Firefox

A: Use the pseudo-class selectors:
:horizontal
:vertical
:decrement
:increment
:start
:end
:double-button
:single-button
:no-button
:corner-present
:window-inactive

Working demo: Codepen.
More info here.
Note: this only works on webkit browsers.


text:
Q: Loading data from the json file into treepanel
In my data.json file I have static data which is to be loaded in the treepanel.According to this link reference, I have changed "children" to "data".But still I am not geting data in my tree panel grid.

My data.json file
      {
        "data":
            [
             {
               "App": "active"
               "iconCls":"task-folder",
               "expanded":"false",
               "data": [
                        {
                          "AppReport1": "active",
                          "leaf": "true"
                         }
                       ]
             }
           ]
        }

Here Is what I am doing:
    initComponent: function () {
    var me = this;
    Ext.log("initComponent()", me);

    me.treeStore = Ext.create("Ext.data.TreeStore", {
        proxy: {
            type: "ajax",
            model   : 'EPH.model.DBStatusModel',
            autoLoad: true,
            type: 'ajax',
            url:'app/data/data.json',
            reader: {
                      type: 'json',
                      root : 'data'
                    }

             },
             root: {
                   expanded: true
              }
      });
      this.down('treepanel').setRootNode(store.getRootNode());

}

I think I have problem in my data.json file.Is it correct or do I need to change something.Please help me out resolving this issue.Thanks.

A: Childen it's a important part of configuration for Node interface.
Sencha api: children
This config param say you what data root node has.
EDIT:
and what happend with "defaultRootProperty":
Sencha api: treeStore

For the tree to read nested data, the Ext.data.reader.Reader must be
  configured with a root property, so the reader can find nested data
  for each node (if a root is not specified, it will default to
  'children'). This will tell the tree to look for any nested tree nodes
  by the same keyword, i.e., 'children'. If a root is specified in the
  config make sure that any nested nodes with children have the same
  name. Note that setting defaultRootProperty accomplishes the same
  thing.

A: In the reference link the first data appears to be JSON Object and in your JSON file is an JSON Array. I think this it should look.
 {
"data": //root
      {
        "data"://children
            [
             {
               "App": "active"
               "iconCls":"task-folder",
               "expanded":"false",
               "data": [
                        {
                          "AppReport1": "active",
                          "leaf": "true"
                         }
                       ]
             }
           ]
      }
}

Note: This code was taken from the original JSON file of the author.


text:
Q: Angular material table with form for each row I have a material table like following:
https://i.stack.imgur.com/afTM2.png
On click of the pen, user can modify name and description of specific row, as those two fields become input fields:
https://i.stack.imgur.com/PWgEc.png
After changing those values, he has to click "save" button on the right side.
My question is how can I make form for each row? Because two input fields and submit button are not "together" in html, I cannot put them in same < form >.
Here is my code:

  <ng-container matColumnDef="name">
     Name

{{element.name}}

          <mat-form-field>
            <input name="name" [ngModel]="element.name" required maxlength=20 matInput autocomplete="off">
          </mat-form-field>

    </ng-container>

    <ng-container matColumnDef="description">
       Description

{{element.description}}

          <mat-form-field class="full-width">
            <input [ngModel]="element.description" maxlength=80 matInput autocomplete="off">
          </mat-form-field>

    </ng-container>

    <ng-container matColumnDef="modifiedTime">
       Modified Time
       {{element.modifiedTime | date: 'dd MMMM yyyy, HH:mm'}}
    </ng-container>

    <ng-container matColumnDef="modifiedBy">
       Modified By
       {{element.modifiedByUsername}}
    </ng-container>

    <ng-container matColumnDef="del_mod">

          <button mat-icon-button color="primary" (click)="editRowId = element.maintenanceTypeId">
            <mat-icon>edit</mat-icon>
          </button>
          <button mat-icon-button color="warn" (click)="deleteRecord(element)">
            <mat-icon>delete</mat-icon>
          </button>

          <button type="submit" mat-icon-button color="primary">

            <mat-icon>save</mat-icon>
          </button>
          <button mat-icon-button color="warn" (click)="editRowId = -1">
            <mat-icon>clear</mat-icon>
          </button>

    </ng-container>

A: You can use Reactive forms with FormArray.
Example: https://stackblitz.com/edit/angular-formarray-example-1?file=src%2Fapp%2Fapp.component.ts


text:
Q: Django Selenium test works in local Docker container but not on Jenkins server When I run the Docker image locally in interactive mode and then do the test manually it works. But when I push to GitHub, Jenkins pulls and runs the tests and then times out when trying to initiate the Firefox browser.
I tried with different Docker base images. I tried with giving executable_path to local file, and also without(while adding system path).
I am new to Docker and Jenkins and I'm not sure what I'm doing wrong.
Thanks in advance for any help.
dockerfile:
FROM ubuntu:bionic

COPY BS_PM2021_TEAM_27/requirements.txt requirements.txt
RUN apt-get update
RUN su -
RUN apt-get install sudo -y
RUN sudo apt-get install -y xvfb
RUN sudo apt-get install -y firefox
RUN sudo apt-get install -y wget
RUN wget https://github.com/mozilla/geckodriver/releases/download/v0.24.0/geckodriver-v0.24.0-linux64.tar.gz
RUN tar -xvzf geckodriver*
RUN chmod +x geckodriver
RUN sudo mv geckodriver /usr/local/bin/
RUN export GECKODRIVER=$PATH:/user/local/bin/geckodriver
RUN sudo apt-get install -y python3.8
RUN sudo apt-get install -y python3-pip
RUN pip3 install -r requirements.txt
RUN Xvfb &
RUN export DISPLAY=localhost:0.0

WORKDIR .

COPY . .

requirements.txt:
asgiref==3.3.4
Django==3.2.3
EasyProcess==0.3
filter-profanity==1.0.9
pytz==2021.1
PyVirtualDisplay==2.2
selenium==3.141.0
sqlparse==0.4.1
urllib3==1.26.5

Jenkinsfile:
pipeline {
    environment {
        OUTPUT1 = "foo"
        OUTPUT2 = 'bar'
    }
    agent {
        dockerfile true
    }
    triggers {
        githubPush()
    }
    stages {
        stage('Build') {
            steps {
                sh """
                    cd BS_PM2021_TEAM_27
                    chmod 555 geckodriver-linux64
                    python3 manage.py makemigrations
                    python3 manage.py migrate
                """
            }
        }
        stage('Run Unit Tests') {
            steps {
                dir("BS_PM2021_TEAM_27"){
                    script{
                        try{
                            sh(returnStdout: true, script: "python3 manage.py test Preschool_Play.tests_integration.TestIntegrationWithSelenium.test_login_then_add_and_delete_new_child 2>&1 | xargs echo > out1.txt")
                        }finally{
                            OUTPUT1 = sh(returnStdout: true, script: "cat out1.txt")
                            OUTPUT2 = sh(returnStdout: true, script: "tail -4 geckodriver.log")
                        }
                    }
                }
            }
        }
    }
    post{
        always{
            echo 'Sending test report email...'
            dir("BS_PM2021_TEAM_27"){
                sh """
                     python3 manage.py email_report -s "Tests Report" -b "${OUTPUT1}"
                     python3 manage.py email_report -s "Log" -b '${OUTPUT2}'
                """
            }
            echo 'Email sent.'
        }
    }
}

test file:
import time
from django.contrib.staticfiles.testing import StaticLiveServerTestCase
from django.test.utils import override_settings
from selenium import webdriver
from selenium.webdriver import FirefoxOptions
from .models import *
import os
from pyvirtualdisplay import Display

class TestIntegrationWithSelenium(StaticLiveServerTestCase):

    def setUp(self):
        if os.name != 'nt':
            opts = FirefoxOptions()
            opts.add_argument("--headless")
            opts.add_argument('--disable-gpu')
            self.display = Display(visible=False, size=(800, 600))
            self.display.start()
            self.browser = webdriver.Firefox(executable_path='./geckodriver-linux64', options=opts)
        else:
            self.browser = webdriver.Firefox(executable_path='./win-geckodriver.exe')
        ...

    def tearDown(self):
        self.browser.close()
        self.display.stop()

    @override_settings(DEBUG=True)
    def test_login_then_add_and_delete_new_child(self):
        ...

Jenkins build console output:
Started by user eilonco
Obtained BS_PM2021_TEAM_27/Jenkinsfile from git https://github.com/RotemLibrati/BS_PM2021_TEAM_27
Running in Durability level: MAX_SURVIVABILITY
[Pipeline] Start of Pipeline
[Pipeline] node
Running on Jenkins in /var/jenkins_home/workspace/Team_27/Team27Pipe
[Pipeline] {
[Pipeline] stage
[Pipeline] { (Declarative: Checkout SCM)
[Pipeline] checkout
No credentials specified
 > git rev-parse --is-inside-work-tree # timeout=10
Fetching changes from the remote Git repository
 > git config remote.origin.url https://github.com/RotemLibrati/BS_PM2021_TEAM_27 # timeout=10
Fetching upstream changes from https://github.com/RotemLibrati/BS_PM2021_TEAM_27
 > git --version # timeout=10
 > git fetch --tags --progress -- https://github.com/RotemLibrati/BS_PM2021_TEAM_27 +refs/heads/*:refs/remotes/origin/* # timeout=10
 > git rev-parse refs/remotes/origin/master^{commit} # timeout=10
 > git rev-parse refs/remotes/origin/origin/master^{commit} # timeout=10
Checking out Revision bbd3426db88b2b6c0f463462d047c5dd5dac5053 (refs/remotes/origin/master)
 > git config core.sparsecheckout # timeout=10
 > git checkout -f bbd3426db88b2b6c0f463462d047c5dd5dac5053 # timeout=10
Commit message: "ubuntu2"
 > git rev-list --no-walk bbd3426db88b2b6c0f463462d047c5dd5dac5053 # timeout=10
[Pipeline] }
[Pipeline] // stage
[Pipeline] withEnv
[Pipeline] {
[Pipeline] stage
[Pipeline] { (Declarative: Agent Setup)
[Pipeline] isUnix
[Pipeline] readFile
[Pipeline] sh
+ docker build -t 13639d9ab6390428bae282a0c7bbd0a0cdd1b696 -f Dockerfile .
Sending build context to Docker daemon  97.69MB

Step 1/20 : FROM ubuntu:bionic
 ---> 81bcf752ac3d
Step 2/20 : COPY BS_PM2021_TEAM_27/requirements.txt requirements.txt
 ---> Using cache
 ---> b848b4fa92dc
Step 3/20 : RUN apt-get update
 ---> Using cache
 ---> bae0ca787abd
Step 4/20 : RUN su -
 ---> Using cache
 ---> f301a6b617a1
Step 5/20 : RUN apt-get install sudo -y
 ---> Using cache
 ---> 3e273f710455
Step 6/20 : RUN sudo apt-get install -y xvfb
 ---> Using cache
 ---> 9d9a38840300
Step 7/20 : RUN sudo apt-get install -y firefox
 ---> Using cache
 ---> 434e2720c7a4
Step 8/20 : RUN sudo apt-get install -y wget
 ---> Using cache
 ---> 81e448f0eda5
Step 9/20 : RUN wget https://github.com/mozilla/geckodriver/releases/download/v0.24.0/geckodriver-v0.24.0-linux64.tar.gz
 ---> Using cache
 ---> 02e07299c327
Step 10/20 : RUN tar -xvzf geckodriver*
 ---> Using cache
 ---> 0371bbbf3016
Step 11/20 : RUN chmod +x geckodriver
 ---> Using cache
 ---> d23fe7800069
Step 12/20 : RUN sudo mv geckodriver /usr/local/bin/
 ---> Using cache
 ---> b63dd57bc1eb
Step 13/20 : RUN export GECKODRIVER=$PATH:/user/local/bin/geckodriver
 ---> Using cache
 ---> ee6e81e81a6a
Step 14/20 : RUN sudo apt-get install -y python3.8
 ---> Using cache
 ---> 9b61093b0eb9
Step 15/20 : RUN sudo apt-get install -y python3-pip
 ---> Using cache
 ---> 7a647ad74b43
Step 16/20 : RUN pip3 install -r requirements.txt
 ---> Using cache
 ---> 0d17d8da547e
Step 17/20 : RUN Xvfb &
 ---> Using cache
 ---> 201fb5ca7b65
Step 18/20 : RUN export DISPLAY=localhost:0.0
 ---> Using cache
 ---> c0fab92bf6d6
Step 19/20 : WORKDIR .
 ---> Using cache
 ---> 7738a4afa668
Step 20/20 : COPY . .
 ---> 7fea506200d5
Successfully built 7fea506200d5
Successfully tagged 13639d9ab6390428bae282a0c7bbd0a0cdd1b696:latest
[Pipeline] }
[Pipeline] // stage
[Pipeline] isUnix
[Pipeline] sh
+ docker inspect -f . 13639d9ab6390428bae282a0c7bbd0a0cdd1b696
.
[Pipeline] withDockerContainer
Jenkins seems to be running inside container 1b8310761f551fe6f780ed06f030c1bfa7f8f94aaec42df21ceb958a5f8a9417
$ docker run -t -d -u 1000:1000 -w /var/jenkins_home/workspace/Team_27/Team27Pipe --volumes-from 1b8310761f551fe6f780ed06f030c1bfa7f8f94aaec42df21ceb958a5f8a9417 -e ******** -e ******** -e ******** -e ******** -e ******** -e ******** -e ******** -e ******** -e ******** -e ******** -e ******** -e ******** -e ******** -e ******** -e ******** -e ******** -e ******** -e ******** -e ******** -e ******** -e ******** -e ******** -e ******** -e ******** -e ******** -e ******** -e ******** 13639d9ab6390428bae282a0c7bbd0a0cdd1b696 cat
$ docker top 00492076b546b5a216713f20e47a2399bd87b3186226bbc8cb53abdba42c6f4f -eo pid,comm
[Pipeline] {
[Pipeline] withEnv
[Pipeline] {
[Pipeline] stage
[Pipeline] { (Build)
[Pipeline] sh
+ cd BS_PM2021_TEAM_27
+ chmod 555 geckodriver-linux64
+ python3 manage.py makemigrations
No changes detected
+ python3 manage.py migrate
Operations to perform:
  Apply all migrations: admin, auth, contenttypes, sessions
Running migrations:
  No migrations to apply.
[Pipeline] }
[Pipeline] // stage
[Pipeline] stage
[Pipeline] { (Run Unit Tests)
[Pipeline] dir
Running in /var/jenkins_home/workspace/Team_27/Team27Pipe/BS_PM2021_TEAM_27
[Pipeline] {
[Pipeline] script
[Pipeline] {
[Pipeline] sh
+ python3 manage.py test Preschool_Play.tests_integration.TestIntegrationWithSelenium.test_login_then_add_and_delete_new_child
+ xargs echo
[Pipeline] sh
+ cat out1.txt
[Pipeline] sh
+ tail -4 geckodriver.log
[Pipeline] }
[Pipeline] // script
[Pipeline] }
[Pipeline] // dir
[Pipeline] }
[Pipeline] // stage
[Pipeline] stage
[Pipeline] { (Declarative: Post Actions)
[Pipeline] echo
Sending test report email...
[Pipeline] dir
Running in /var/jenkins_home/workspace/Team_27/Team27Pipe/BS_PM2021_TEAM_27
[Pipeline] {
[Pipeline] sh
+ python3 manage.py email_report -s Tests Report -b Creating test database for alias default... System check identified no issues (0 silenced). E ====================================================================== ERROR: test_login_then_add_and_delete_new_child (Preschool_Play.tests_integration.TestIntegrationWithSelenium) ---------------------------------------------------------------------- Traceback (most recent call last): File /var/jenkins_home/workspace/Team_27/Team27Pipe/BS_PM2021_TEAM_27/Preschool_Play/tests_integration.py, line 20, in setUp self.browser = webdriver.Firefox(executable_path=./geckodriver-linux64, options=opts) File /usr/local/lib/python3.6/dist-packages/selenium/webdriver/firefox/webdriver.py, line 174, in __init__ keep_alive=True) File /usr/local/lib/python3.6/dist-packages/selenium/webdriver/remote/webdriver.py, line 157, in __init__ self.start_session(capabilities, browser_profile) File /usr/local/lib/python3.6/dist-packages/selenium/webdriver/remote/webdriver.py, line 252, in start_session response = self.execute(Command.NEW_SESSION, parameters) File /usr/local/lib/python3.6/dist-packages/selenium/webdriver/remote/webdriver.py, line 321, in execute self.error_handler.check_response(response) File /usr/local/lib/python3.6/dist-packages/selenium/webdriver/remote/errorhandler.py, line 242, in check_response raise exception_class(message, screen, stacktrace) selenium.common.exceptions.TimeoutException: Message: Connection refused (os error 111) ---------------------------------------------------------------------- Ran 1 test in 61.588s FAILED (errors=1) Destroying test database for alias default...

+ python3 manage.py email_report -s Log -b [GFX1-]: glxtest: libpci missing
[GFX1-]: glxtest: libEGL missing
[GFX1-]: glxtest: libEGL missing
[GFX1-]: RenderCompositorSWGL failed mapping default framebuffer, no dt

[Pipeline] }
[Pipeline] // dir
[Pipeline] echo
Email sent.
[Pipeline] }
[Pipeline] // stage
[Pipeline] }
[Pipeline] // withEnv
[Pipeline] }
$ docker stop --time=1 00492076b546b5a216713f20e47a2399bd87b3186226bbc8cb53abdba42c6f4f
$ docker rm -f 00492076b546b5a216713f20e47a2399bd87b3186226bbc8cb53abdba42c6f4f
[Pipeline] // withDockerContainer
[Pipeline] }
[Pipeline] // withEnv
[Pipeline] }
[Pipeline] // node
[Pipeline] End of Pipeline
Finished: SUCCESS

Django console output:
Creating test database for alias default...
System check identified no issues (0 silenced).
E ======================================================================
ERROR: test_login_then_add_and_delete_new_child (Preschool_Play.tests_integration.TestIntegrationWithSelenium)
----------------------------------------------------------------------
Traceback (most recent call last): File /var/jenkins_home/workspace/Team_27/Team27Pipe/BS_PM2021_TEAM_27/Preschool_Play/tests_integration.py,
line 20, in setUp self.browser = webdriver.Firefox(executable_path=./geckodriver-linux64, options=opts)
File /usr/local/lib/python3.6/dist-packages/selenium/webdriver/firefox/webdriver.py,
line 174, in __init__ keep_alive=True) File /usr/local/lib/python3.6/dist-packages/selenium/webdriver/remote/webdriver.py,
line 157, in __init__ self.start_session(capabilities, browser_profile) File /usr/local/lib/python3.6/dist-packages/selenium/webdriver/remote/webdriver.py,
line 252, in start_session response = self.execute(Command.NEW_SESSION, parameters) File /usr/local/lib/python3.6/dist-packages/selenium/webdriver/remote/webdriver.py,
line 321, in execute self.error_handler.check_response(response) File /usr/local/lib/python3.6/dist-packages/selenium/webdriver/remote/errorhandler.py,
line 242, in check_response raise exception_class(message, screen, stacktrace) selenium.common.exceptions.TimeoutException: Message: Connection refused (os error 111)
----------------------------------------------------------------------
Ran 1 test in 61.588s FAILED (errors=1)
Destroying test database for alias default...

geckodriver.log:
[GFX1-]: glxtest: libpci missing
[GFX1-]: glxtest: libEGL missing
[GFX1-]: glxtest: libEGL missing
[GFX1-]: RenderCompositorSWGL failed mapping default framebuffer, no dt

When I run on a local container the test passes and the geckodriver.log is:
# cat geckodriver.log
1622651926935   mozrunner::runner       INFO    Running command: "/usr/bin/firefox" "-marionette" "--headless" "--disable-gpu" "-foreground" "-no-remote" "-profile" "/tmp/rust_mozprofile.jh7CncJfRv6O"
*** You are running in headless mode.
[GFX1-]: glxtest: libpci missing
[GFX1-]: glxtest: libEGL missing
[GFX1-]: glxtest: Unable to open a connection to the X server
[GFX1-]: glxtest: libEGL missing
[GFX1-]: No GPUs detected via PCI
1622651927369   Marionette      INFO    Marionette enabled

(/usr/lib/firefox/firefox:81): GLib-GObject-CRITICAL **: 16:38:47.908: g_object_set: assertion 'G_IS_OBJECT (object)' failed

(/usr/lib/firefox/firefox:101): GLib-GObject-CRITICAL **: 16:38:47.998: g_object_set: assertion 'G_IS_OBJECT (object)' failed
console.warn: SearchSettings: "get: No settings file exists, new profile?" (new Error("", "(unknown module)"))
1622651929513   Marionette      INFO    Listening on port 45265

(/usr/lib/firefox/firefox:163): GLib-GObject-CRITICAL **: 16:38:49.575: g_object_set: assertion 'G_IS_OBJECT (object)' failed
1622651929580   Marionette      WARN    TLS certificate errors will be ignored for this session
1622651936233   Marionette      INFO    Stopped listening on port 45265

Here it also succeeds when I run it in Ubuntu server:
ubuntu@primary:~$ cat /etc/os-release
NAME="Ubuntu"
VERSION="20.04.2 LTS (Focal Fossa)"
ID=ubuntu
ID_LIKE=debian
PRETTY_NAME="Ubuntu 20.04.2 LTS"
VERSION_ID="20.04"
HOME_URL="https://www.ubuntu.com/"
SUPPORT_URL="https://help.ubuntu.com/"
BUG_REPORT_URL="https://bugs.launchpad.net/ubuntu/"
PRIVACY_POLICY_URL="https://www.ubuntu.com/legal/terms-and-policies/privacy-policy"
VERSION_CODENAME=focal
UBUNTU_CODENAME=focal
ubuntu@primary:~$ docker container start -a -i eager_cartwright
root@68abe3dfecd3:/# cd BS_PM2021_TEAM_27/
root@68abe3dfecd3:/BS_PM2021_TEAM_27# rm geckodriver.log
root@68abe3dfecd3:/BS_PM2021_TEAM_27# python3 manage.py test Preschool_Play.tests_integration.TestIntegrationWithSelenium.test_login_then_add_and_delete_new_child
Creating test database for alias 'default'...
System check identified no issues (0 silenced).
Not Found: /favicon.ico
Not Found: /favicon.ico
[<Child: Name: kid2. Parent: parent>]
.
----------------------------------------------------------------------
Ran 1 test in 14.417s

OK
Destroying test database for alias 'default'...
root@68abe3dfecd3:/BS_PM2021_TEAM_27#
root@68abe3dfecd3:/BS_PM2021_TEAM_27# cat geckodriver.log
1622660833134   geckodriver     INFO    Listening on 127.0.0.1:32959
1622660834143   mozrunner::runner       INFO    Running command: "/usr/bin/firefox" "--marionette" "--headless" "--disable-gpu" "-foreground" "-no-remote" "-profile" "/tmp/rust_mozprofilePskEQC"
*** You are running in headless mode.
[GFX1-]: glxtest: libpci missing
[GFX1-]: glxtest: libEGL missing
[GFX1-]: glxtest: Unable to open a connection to the X server
[GFX1-]: glxtest: libEGL missing
[GFX1-]: No GPUs detected via PCI
1622660834624   Marionette      INFO    Marionette enabled

(/usr/lib/firefox/firefox:73): GLib-GObject-CRITICAL **: 19:07:15.322: g_object_set: assertion 'G_IS_OBJECT (object)' failed

(/usr/lib/firefox/firefox:88): GLib-GObject-CRITICAL **: 19:07:15.523: g_object_set: assertion 'G_IS_OBJECT (object)' failed
console.warn: SearchSettings: "get: No settings file exists, new profile?" (new Error("", "(unknown module)"))
1622660838023   Marionette      INFO    Listening on port 45137
1622660838185   Marionette      WARN    TLS certificate errors will be ignored for this session

(/usr/lib/firefox/firefox:151): GLib-GObject-CRITICAL **: 19:07:18.187: g_object_set: assertion 'G_IS_OBJECT (object)' failed
1622660846356   Marionette      INFO    Stopped listening on port 45137

UPDATE: As I suspected my college's servers have no display options and no GPUs which is why Selenium couldn't find any. However I don't know the reason it still works on my Ubuntu server with no GUI. Perhaps it's because the Ubuntu server still recognizes my laptops GPU.

A: The problem is the frame buffer which is the X server, test on Ubuntu Server and you will get the same issue


text:
Q: No entra en la funcion cuando le doy click var imagenes = ['imagenes/vis1.jpg', 'imagenes/vis2.jpg', 'imagenes/vis3.jpg']
cont = 0;

function carrousel(visitanos) {
    visitanos.addEventListener('click', e => {
        let atras = visitanos.querySelector('.atras'),
        adelante = visitanos.querySelector('.adelante'),
        img = visitanos.querySelector('.visis'),
        tgt = e.target;
        if(tgt == atras) {
            if(cont > 0) {
                img.src = imagenes[cont -1];
                cont--;
            } else {
                img.src = imagenes[imagenes.lengt -1];
                cont = imagenes.length -1;
            }
        } else if(tgt == adelante) {

            if(cont < imagenes.lengt -1) {
                img.src = imagenes[cont +1];
                cont++;
                confirm("mensaje");
            } else {
                img.src = imagenes[0];
                cont = 0;
            }
        }
    });
}

document.addEventListener("DOMContentLoader", () => {
    confirm("mensaje");
    let visitanos = document.querySelector('.visitanos');
    carrousel(visitanos);
});

A: El evento al que te suscribes está mal escrito. Es DOMContentLoaded.
Aquí tienes la documentación.
document.addEventListener("DOMContentLoaded", () => {
    // ...
});

Y, como mencionaba en el comentario, tienes un typo al acceder a la property length, te falta la "h".
Espero que sirva.


text:
Q: Make new lines in CSS in form for each label I have HTML code
<form id="answers">
blue
<input id="0" type="radio">
red
<input id="1" type="radio">
pink
<input id="2" type="radio">
<input type="submit">
</form>

and I want to have each element in the new line. I don't want to use stuff like
. In CSS file I tried do this: display: block but nothing's changed.

A: #answers input {display: block;}

this will make every input in its own line.
If you wish to have every input with its label together in a line you should do something like
<form id="answers">
    blue <input id="0" type="radio">
    red <input id="1" type="radio">
    pink <input id="2" type="radio">
    <input type="submit">
</form>

css:
    #answers label {display: block;}
http://jsfiddle.net/barakedry/y6p54vzg/

A: You may need to use box-sizing:border-box;.
There's more information on this very topic in this thread: input with display:block is not a block, why not?


text:
Q: how to open image in our android application..? i have create app ,in this app i have edit image.in gallery when we select any image so we have get some option like "BLUETOOTH","Email","SHARE",so how i can add my application option in that list.?

A: By simply adding intent filter with send action and mimeType.
Example
<activity android:name="Main" >
    <intent-filter>
        <action android:name="android.intent.action.MAIN" />
        <category android:name="android.intent.category.DEFAULT" />
    </intent-filter>
</activity>
<activity android:name="MediaShare" >
    <intent-filter>
        <action android:name="android.intent.action.SEND" />
        <data android:mimeType="image/*" />
    </intent-filter>
</activity>


text:
Q: Search-Filtering GridView control results in no records found I'm trying to filter-search the data from a GridView control which is bound to a SQL data connection but i'm not having any success. Whenever I try to search for something, it results in no records found. Here is my main searching code:
    public void FilterGridView(string column, string terms) //SELECT * FROM [Table_1] WHERE [First Name] LIKE '%valuetosearchfor%' is the format to use here
    {
        DataTable filterTable = new DataTable(); //create a datatable to hold the data while we retrieve it
        SqlConnection connection = new SqlConnection("Data Source=TAMUWINPART\\SQLEXPRESS;Initial Catalog=phpMyWorkers;Integrated Security=True"); //connect to SQL
        try
        {
            connection.Open(); //open the connection

            string filterStatement = "SELECT * FROM [Table_1] WHERE @column LIKE '%@terms%'"; //select all from table_1 with the correct column name / terms

            SqlCommand sqlCmd = new SqlCommand(filterStatement, connection); //make a sql command
            sqlCmd.CommandType = CommandType.Text; //make it an average joe sql text command

            //define the @ sql variables
            sqlCmd.Parameters.AddWithValue("@column", column);
            sqlCmd.Parameters.AddWithValue("@terms",  terms);

            SqlDataAdapter filterAdapter = new SqlDataAdapter(sqlCmd); //make a data adapter to get all the data from the command and put it into the data table

            filterAdapter.Fill(filterTable);  //fill the data table with the data from the SQL connection

            if(filterTable.Rows.Count > 0)  //if records were found relating to the terms
            {
                //if records WERE found
                workersView.DataSource = filterTable; //set the data source to this instead
                workersView.DataBind(); //refresh the data
            }
            else
            {
                //no records were found in this case, do not be an inneficient guy who will refresh the gridview for no reason
                FilterSearchTerms.Text = "0 Records Found!"; //notify the user that he/she won't get anything
            }
        }
        catch (System.Data.SqlClient.SqlException ex) //if the thing just decides that it doesn't want to work today
        {
            string msg = "myWorkers had a problem fetching the data : ";
            msg += ex.Message;
            throw new Exception(msg);
        }
        finally
        {
            connection.Close(); //close the connection
        }
    }

    public void FilterSearchButton_Click(object sender, EventArgs e) //when someone clicks the button to filtersearch the gridviews
    {
        string column = FilterSearchDropdown.SelectedValue.ToString(); //get the column that the user wants to filter by and make sure it's a string
        string terms = FilterSearchTerms.Text;    //get the terms to search by - verified string for sure

        FilterGridView(column, terms);
    }

    public void FilterRemoveButton_Click(object sender, EventArgs e) //when someone decides to remove the filter
    {
        BindGridView(); //refresh the gridview based on all of the data
        FilterSearchTerms.Text = ""; //remove the text from the filter search terms box
    }

Here is a picture of what the layout looks like.

Even if I search for real data it results  in this being called
        else
        {
            //no records were found in this case, do not be an inneficient guy who will refresh the gridview for no reason
            FilterSearchTerms.Text = "0 Records Found!"; //notify the user that he/she won't get anything
        }

meaning that the datatable's row count is 0...
Does anyone know why? Thank you.

A: I suspect that your SQL LIKE code is incorrect. Take a look at how to use like with SQL parameter in this question:how-to-get-like-clause-to-work-in-ado-net-and-sql-server. It would also help to display the final sql command text that gets sent to the database.

A: Replace this line :
 string column = FilterSearchDropdown.SelectedValue.ToString();

with this:
 string column = FilterSearchDropdown.SelectedText;

Also, you need correct your command string  and command  parameters as Emmad Kareem suggested in other answer. Your string and parameter should be like below:
  string filterStatement = "SELECT * FROM [Table_1] WHERE [{0}] LIKE @terms"; //select all from table_1 with the correct column name / terms
  filterStatement = string.Format(filterStatement, column);
  ....      ....      ....      ....      ....      ....

 // sqlCmd.Parameters.AddWithValue("@column", column );
  sqlCmd.Parameters.AddWithValue("@terms", "%" + terms + "%");

A: You only need to replace this query:
string filterStatement = "SELECT * FROM [Table_1] WHERE @column LIKE '%"+terms+"%'";

And you should be able to find your data.


text:
Q: Number of 1 in binary representation of n Let $1(n)$ be the number of digits $1$ in binary representation of number $n$.
For example, $13=1101_2$ so $1(13)=3\\$
Is there explicit form of $\,\,\sum{1(i)x^i} $?
I checked OEIS and didn't find information about this sequence (1,1,2,2,2,3,1,2,2,3,...)

A: By the way, the reason why the OP did not find the sequence in the OEIS is that he/she wrote down the first few terms incorrectly.  They are 0,1,1,2,1,2,2,3, ..., which is sequence http://oeis.org/A000120 .

A: The generating function you ask about, more typically written as $\sum_{i\ge 0} s_2(i) x^i$, can be expressed as
$$\frac{1}{1-x} \sum_{m\ge 0} \frac{x^{2^m}}{1+x^{2^m}}$$
The number of 1's in the binary expansion is just the sums of digits; there also exists a generalization for sums of digits function in other bases. For details, references and further information, see for example  "Generating Functions for the Digital Sum and Other Digit Counting Sequences" by Adams-Watters and Ruskey (Journal of Integer Sequences, 2009)


text:
Q: I want to monitor wildfly 9.0.1 (heap used , non heap used etc)through zabbix 3.0.2, I want to monitor wildfly 9.0.1 (heap used , non heap used etc) from zabbix 3.0.2.

A: Please see my simple app that will give you a clue how to fetch such information. https://github.com/stankay/zabbix-jboss-probe
Steps:

*

*Make the app running against your instance of Wildfly

*Prepare Zabbix probe that will use this app to fetch necessary numbers (currently only heap/nonheap supported)

Michal


text:
Q: AngularJS date in controller undefined I'm trying to add a date that defaults to the current day to my page. Below is the angular script for this but when I click add day I get error of undefined? I don't understand I believe it's been defined correctly.

$scope.today= new Date();
$scope.add = {};

       if($scope.today){
           var today= new Date($scope.today)
           $scope.add.today=
                today.getFullYear()+'-'+(today.getMonth() + 1)+'-'+today.getDate();
       }else{
           $scope.add.today= null;
       }

      Date
      <input type="date" class="form-control" name="add_row_today" id="add_row_today" ng-model="today">

This is what my code looks like.
this is the stack trace from console
TypeError: Cannot set property 'today' of undefined
    at m.$scope.add_list (angularScripts.js?v=1.3:8741)
    at fn (eval at compile (_bower.js?v=1.2:10467), <anonymous>:4:220)
    at b (_bower.js?v=1.2:10360)
    at e (_bower.js?v=1.2:10510)
    at m.$eval (_bower.js?v=1.2:10379)
    at m.$apply (_bower.js?v=1.2:10380)
    at HTMLInputElement.<anonymous> (_bower.js?v=1.2:10510)
    at HTMLInputElement.dispatch (_bower.js?v=1.2:5201)
    at HTMLInputElement.elemData.handle (_bower.js?v=1.2:5009)

A: You have a typo.
property 'today' of undefined means something has .today, which doesn't exists. In your case it's either $scope.add or $scope.edit
I think while changing your code, you forgot to replace one of them. Try changing:
$scope.edit.today = null;

to
$scope.add.today = null;

Or initialise it, if you are missing it with $scope.edit = {};

Given your edited code, you have a working solution

var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
  $scope.today = new Date();
  $scope.add = {};

  if ($scope.today) {
    var today = new Date($scope.today)
    $scope.add.today =
      today.getFullYear() + '-' + (today.getMonth() + 1) + '-' + today.getDate();
  } else {
    $scope.add.today = null;
  }
});
<!DOCTYPE html>

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

      Date
      <input type="date" class="form-control" name="add_row_today" id="add_row_today" ng-model="today">


text:
Q: Travis: "Got an error creating the test database: permission denied to create database" This is my travis.yml file:
language: python
python:
  - "2.7"
addons:
  postgresql: "9.3"
env:
  - SECRET_KEY=test DB_NAME=dbtest DB_USER=test DB_PASS=test
before_install:
  - export DJANGO_SETTINGS_MODULE=settings.local
  - export PYTHONPATH=$HOME/builds/me/myrepo
install:
 - pip install -r requirements.txt
before_script:
 - psql -U postgres -c 'CREATE DATABASE dbtest;'
 - psql -U postgres -c "CREATE EXTENSION postgis" -d dbtest
 - psql -U postgres -c "CREATE EXTENSION postgis_topology" -d dbtest
 - psql -U postgres -c "CREATE USER test WITH PASSWORD 'test';"
 - psql -U postgres -c "GRANT ALL PRIVILEGES ON DATABASE dbtest to test;"
 - cd myapp && python manage.py migrate
script:
 - python manage.py test

But when I deploy the repo and Travis runs, it outputs this error:
10.96s$ pip install -r requirements.txt
0.24s$ psql -U postgres -c 'CREATE DATABASE dbtest;'
0.77s$ psql -U postgres -c "CREATE EXTENSION postgis" -d dbtest
0.09s$ psql -U postgres -c "CREATE EXTENSION postgis_topology" -d dbtest
0.01s$ psql -U postgres -c "CREATE USER test WITH PASSWORD 'test';"
0.01s$ psql -U postgres -c "GRANT ALL PRIVILEGES ON DATABASE dbtest to test;"
1.89s$ cd myapp && python manage.py migrate
$ python manage.py test
Creating test database for alias 'default'...
Got an error creating the test database: permission denied to create database
Type 'yes' if you would like to try deleting the test database 'test_dbtest', or 'no' to cancel:

I tried adding psql -U postgres -c "ALTER USER django CREATEDB;" so that the django user would have permission to create a database, but that fails with:
ERROR:  role "django" does not exist
The command "psql -U postgres -c "ALTER USER django CREATEDB;"" failed and exited with 1 during .

A: The answer: I had to make the test user a superuser:
CREATE USER test WITH PASSWORD 'test';

and then give the user permissions to create databases:
ALTER USER test CREATEDB;


text:
Q: Examples of Measures that are Equivalent to their Self-Convolution I'm interested in seeing (or generating) lots of examples of measures $\mu$ on $\mathbb{R}$ such that $\mu \sim \mu * \mu$.  I'd love a reference (or even just a name) for these measures or, alternatively, a way to make up examples.  I'd like to at least know that there are many measure classes whose representatives satisfy $\mu \sim \mu * \mu$, if we can't explicitly generate a family of examples.
At first, I thought it might be easier to think about these measures through the Fourier transform $\hat{\mu}$, since the Fourier transform of $\mu * \mu$ is just the product of $\hat{\mu}$ with itself, but I don't know how to determine equivalence of the measures $\mu$ and $\mu * \mu$ in terms of their Fourier transforms.
In my actual application, I also want the Fourier transform to decay at infinity, i.e. $\lim_{|t|\rightarrow \infty} \hat{\mu}(t) = 0$, so I would also appreciate comments/references about generating those examples in particular, but I'm interested in any examples where $\mu \sim \mu * \mu$, whether they meet my decay condition or not.  If it's not easy to generate examples, I'd still like to see whether there's a "large" set of measure classes with these properties.


text:
Q: replace the LAST ',' in a CSV with a tab? In a large and wide CSV table, how can I replace the LAST ',' with a tab in vi?  An awk command would be just as useful, but I don't know awk well enough.  (I'd do it in PERL but I don't want to write a script).
Ex. Replace the comma before the last value with a tab.  It's easy to do at the beginning of the line, but not at the end.  Any ideas?
chr9,5971307,…,2,2,2,2,2,0,5881595,6007901,KIAA2026,20605
chr9,5971313,…,0,0,0,0,0,0,5881595,6007901,KIAA2026,20605
chr9,5971416,…,2,2,2,2,2,0,5881595,6007901,KIAA2026,20605

Note: the number of CSV values is > 1000. The values are not fixed as they appear above, so I cannot rely on the data or a fixed column number.  This is dependent on the field separators (,).
Thanks for any help you can supply.
Cheers,
Joe White

A: You can do this with a substitute command.
:%s/,\ze[^,]*$/\t

The \ze piece will cause everything after it (that is, the [^,]*$) to not get replaced, but it still needs to match. So this means:

*

*:%s/ Substitute on every line...

*, a comma

*\ze Followed by, (but don't replace this part)

*[^,]* Any number of characters that aren't commas.

*$ and then the end of the line

*/ with

*\t a tab.

This is effectively the same as
:%s/,\([^,]*\)$/\t\1

You could also do this with a normal mode command, but this will not work if the last character on a line is a comma.
:%norm $F,r<C-v><tab>

(Note that <C-v> means ctrl-v and <tab> means a literal tab character)


text:
Q: HttpContext.Current.User.Identity.Name empty when debugging in visual studio Below is the web.config
<authentication mode="Windows" />
    <authorization>
            <allow users="*"/>
            <deny users="?" />
    </authorization>

But when I debug in visual studio, the HttpContext.Current.User.IsAuthenticated is false and the HttpContext.Current.User.Identity.Name remains empty
Why this happen?

When I change the web.config to this, a 401 error shows...
 <authorization>

      <deny users="?" />
    </authorization>

A: Just now solved the problem by changing "Use Local IIS Web server to "Use Visual Studio Development Server in the "Properties" page

A: Your configuration allows anonymous users. You'll only get usernames for authenticated users.
<authorization>
    <!-- Deny anonymous users -->
    <deny users="?" />

    <!-- Allow everyone else (authenticated users) -->
    <allow users="*" />
</authorization>

Make sure that you have the Windows Authentication component installed and activated in IIS.

A: Since as of Visual Studio 2013 "Visual Studio Development Server" is no longer available, we will need to choose IIS Express and make sure we have enabled windows authentication in the applicationhost.config file
<windowsAuthentication enabled="true">

Besides of configuring our IIS Express as @sisve's answer describes.


text:
Q: PowerBI DAX How to get records with selected values and startdate and enddate I have 4 selected values connected to dimDate and dimDate2 (copy)

*

*dimdate(startyear,startmonth,

*dimdate2 (endyear, endmonth)

connected to 2 columns startdate and enddate in another table
Here is the data

I want to be able to filterout rows (keep) that are in the selected period (Green) and exclude rows that haven't been open between this selected values.

-The easy answer here is to use Filter on this visualobject with startdate and enddate but you cant do that becouse if dynamic values
, and you cant use created table becouse the is a dynamic selected values, you can't use new column to create a filter becouse the dynamic selected value
Whats left to do? I dont know maybe messurement.
I have tyed to figuere this out for months, i have got some answer that is not right.
The I have the logic in SQL but i dont know how i can filterout rows using PowerBI with DAX.
I can solve it with the things i said above (Without dynamic values) that you cant use.
Please help me figure out how i can filterout rows from a table. You don't need to solve the logic that i can do, just how i get rid of rows with logics.

A: Working in HR, your business requirement here is almost verbatim with how we develop headcount measures. Headcounts, similarly need to be able to consider dynamic start and end dates, as applied via slicers.
Between your fact table and date-dimension table, establish two inactive relationships between your start and end date columns with the date column of your date table. (You only need one date table.) Once you have done that, you can create a measure similar to this one:
Active Timeframes =
CALCULATE(
    (SOME EXPRESSION HERE), // e.g. COUNTROWS( 'Some Table' )
    FILTER(
        VALUES( 'Table'[Start Date] ),
        'Table'[Start Date] <= MAX( 'Date'[Date] )
    ),
    FILTER(
        VALUES( 'Table'[End Date] ),
        'Table'[End Date] >= MIN( 'Date'[Date] ) ||
        ISBLANK( 'Table'[End Date] ) // Can exclude if needed.
    )
)

While this example may not be 100% specific to your use case, it should be able to get you in the right ballpark. For more information on this implementation, see this YouTube video by Enterprise DNA.


text:
Q: pom.xml third party import issue I am using ServiceMix 4, and am trying to modify the cxf-jaxrs demo. The following is my pom.xml

http://maven.apache.org/maven-v4_0_0.xsd">
<!--

    Licensed to the Apache Software Foundation (ASF) under one or more
    contributor license agreements.  See the NOTICE file distributed with
    this work for additional information regarding copyright ownership.
    The ASF licenses this file to You under the Apache License, Version 2.0
    (the "License"); you may not use this file except in compliance with
    the License.  You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.
-->

<modelVersion>4.0.0</modelVersion>
<parent>
    <groupId>org.apache.servicemix.examples</groupId>
    <artifactId>examples</artifactId>
    <version>4.2.0</version>
</parent>
<groupId>com.demo</groupId>
<artifactId>calendar-service</artifactId>
<packaging>bundle</packaging>
<name>Calendar Api Demo :: CXF JAX-RS OSGI</name>
<repositories>
<repository>
    <id>mandubian-mvn</id>
    <url>http://mandubian-mvn.googlecode.com/svn/trunk/mandubian-mvn/repository</url>
</repository>
</repositories>
<dependencies>
    <dependency>
        <groupId>com.google.collections</groupId>
        <artifactId>google-collections</artifactId>
        <version>1.0-rc5</version>
    </dependency>
    <dependency>
        <groupId>net.sourceforge.findbugs</groupId>
        <artifactId>jsr305</artifactId>
        <version>1.3.2</version>
    </dependency>
    <dependency>
        <groupId>com.google.gdata</groupId>
        <artifactId>gdata-client-1.0</artifactId>
        <version>1.41.5</version>
    </dependency>
    <dependency>
        <groupId>com.google.gdata</groupId>
        <artifactId>gdata-calendar-2.0</artifactId>
        <version>1.41.5</version>
    </dependency>
    <dependency>
        <groupId>com.google.gdata</groupId>
        <artifactId>gdata-core-1.0</artifactId>
        <version>1.41.5</version>
    </dependency>
    <dependency>
        <groupId>com.google.gdata</groupId>
        <artifactId>gdata-base-1.0</artifactId>
        <version>1.41.5</version>
    </dependency>
    <dependency>
        <groupId>org.apache.servicemix.specs</groupId>
        <artifactId>org.apache.servicemix.specs.jsr311-api-1.0</artifactId>
        <version>1.3.0</version>
    </dependency>
    <dependency>
        <groupId>org.apache.servicemix.specs</groupId>
        <artifactId>org.apache.servicemix.specs.jaxb-api-${jaxb.api.version}</artifactId>
        <version>${servicemix.specs.version}</version>
    </dependency>
   <dependency>
        <groupId>org.apache.servicemix.bundles</groupId>
        <artifactId>org.apache.servicemix.bundles.commons-httpclient</artifactId>
        <version>${commons-httpclient.version}</version>
    </dependency>
</dependencies>

<build>
    <plugins>
        <plugin>
            <groupId>org.apache.felix</groupId>
            <artifactId>maven-bundle-plugin</artifactId>
            <extensions>true</extensions>
            <configuration>
                <instructions>
                    <Bundle-SymbolicName>${pom.artifactId}</Bundle-SymbolicName>
                    <Import-Package>
                            javax.wsdl,
                            javax.xml.bind,
                            javax.xml.bind.annotation,
                            javax.ws.rs,
                            META-INF.cxf,
                            META-INF.cxf.osgi,
                            org.apache.cxf.bus,
                            org.apache.cxf.bus.spring,
                            org.apache.cxf.bus.resource,
                            org.apache.cxf.resource,
                            org.apache.cxf.configuration.spring,
                            org.apache.cxf.binding,
                            org.apache.cxf.jaxrs.utils,
                            org.apache.cxf.transport.http_osgi,
                            org.springframework.beans.factory.config,
                            org.apache.commons.httpclient,
                            org.apache.commons.httpclient.methods,
                            com.google.gdata.client.calendar;resolution:=optional,
                            com.google.gdata.data;resolution:=optional,
                            com.google.gdata.data.calendar;resolution:=optional,
                            com.google.gdata.data.extensions;resolution:=optional,
                            com.google.gdata.util;resolution:=optional
                    </Import-Package>
                    <Require-Bundle>org.apache.cxf.bundle</Require-Bundle>
                    <Export-Package>com.demo.*;</Export-Package>
                    <DynamicImport-Package>javax.ws.rs.*</DynamicImport-Package>
                 </instructions>
            </configuration>
        </plugin>
        <plugin>
            <groupId>org.codehaus.mojo</groupId>
            <artifactId>exec-maven-plugin</artifactId>
            <configuration>
                <mainClass>edu.berkeley.api.client.Client</mainClass>
                <includePluginDependencies>false</includePluginDependencies>
            </configuration>
        </plugin>
    </plugins>
</build>

Maven builds successfully, but when I try to deploy it on servicemix, I get:
Caused by: java.lang.ClassNotFoundException: com.google.gdata.data.calendar.CalendarEntry
    at org.apache.felix.framework.ModuleImpl.findClassOrResourceByDelegation(ModuleImpl.java:814)
    at org.apache.felix.framework.ModuleImpl.access$100(ModuleImpl.java:61)
    at org.apache.felix.framework.ModuleImpl$ModuleClassLoader.loadClass(ModuleImpl.java:1733)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:248)
    ... 42 more
Am I missing a step? Any insight is appreciated.

A: Try to remove the ";resolution:=optional" from "com.google.gdata.data.calendar" so that OSGi can inform you when the required import is missing.
I had a look at the manifest of the JAR "gdata-calendar-2.0-1.41.5.jar" and it is lacking OSGi data. This means that you need to wrap the JAR as OSGi bundle. You can do this in the Karaf console with the wrap command:
osgi:install -s wrap:mvn:com.google.gdata/gdata-calendar-2.0/1.41.5


text:
Q: Why do I get the base class methods via reflection when the subclass overrides them? I have super class as:
class MyClass<T> {
  public void setValue(T value){
    //insert code
  }

  public T getValue(){
    return null;
  }
}

then I have a a specific derivation
class MyClassImp extends MyClass<String> {
  @Override
  public void setValue(String value){
    //insert code
  }

  @Override
  public String getValue(){
    return null;
  }
}

On reflection on MyClassImpl as:
Class clazz = MyClassImpl.class;
Method[] methods = clazz.getDeclaredMethods();

I get both superclass implementation java.lang.Object getValue(), void setValue(java.lang.Object) and java.lang.String getValue(), void setValue(java.lang.String).
According to the Java documentation of Class.getDeclaredMethods() vis-a-viz

Returns an array of Method objects reflecting all the methods declared by the class or interface represented by this Class object. This includes public, protected, default (package) access, and private methods, but excludes inherited methods. The elements in the array returned are not sorted and are not in any particular order. This method returns an array of length 0 if the class or interface declares no methods, or if this Class object represents a primitive type, an array class, or void. The class initialization method <clinit> is not included in the returned array. If the class declares multiple public member methods with the same parameter types, they are all included in the returned array.

Why am I getting the super type implementation?
Is there something I am missing?
The reason why I need this is that I reflectively invoke setValue on base class implementation, which I have added some special annotation comments and of course additional constraints.

A: It's because the compiled class actually does declare setValue(Object). That method will cast to String, and then call the strongly typed method. Likewise getValue(Object) calls getValue(String).
Basically this is required because the JVM doesn't really know about generics (at least not in a deep way) - in order to override the superclass method at the JVM level, it has to have the same signature.
Have a look at the class with javap -c MyclassImp you'll see the extra synthetic methods:
public java.lang.Object getValue();
  Code:
   0:   aload_0
   1:   invokevirtual   #3; //Method getValue:()Ljava/lang/String;
   4:   areturn

public void setValue(java.lang.Object);
  Code:
   0:   aload_0
   1:   aload_1
   2:   checkcast       #4; //class java/lang/String
   5:   invokevirtual   #5; //Method setValue:(Ljava/lang/String;)V
   8:   return

}

A: As Jon had said earlier, type information is lost at runtime for generics.
So whenever you use generics, the compiler puts all those "generic" inherited methods in the subclass. The same is not true with non-generic code.
I just checked: when I removed the generic related code (the <T> part) from the superclass and the reflection code gave me exactly two methods in the subclass even though it overrides them. It implies that the documentation should have been a little bit explicit for generic-related code.


text:
Q: How to repeat certain lines conditionally in Python? I have an array like:
arr=[[1,2,3,4,'a,b,c,d'],[5,6,7,8,'e,f,g,h']]
I want to be:
arr=[[1,2,3,4,'a'],[1,2,3,4,'b'],[1,2,3,4,'c'],[1,2,3,4,'d'],[5,6,7,8,'e'],[5,6,7,8,'f'],[5,6,7,8,'g'],[5,6,7,8,'h']]
can somebody helps to gives me a suggestion? Many thanks.

A: you can iterate through the string (last element in list) and append the answer onto everything but the last element
new_arr = [[li[:-1]+[letter] for letter in li[-1].split(',')] for li in arr]
# Flatten
out = [item for sublist in new_arr for item in sublist]


text:
Q: how to get an openlayers map to show inside twitter bootstrap? In a twitter bootstrap page, I have a 12 wide column inside a row. Above the 12 wide column is the navbar. In the column is an open layers map and I need that column to take up the entire vertical space that remains under the navbar. This does not work. the map div shows up with 0px height. The only work around I found online is to add a width of 100% on html, body and the map div. that makes the map div span the entire document not just the column it is in. Thanks for any helpful pointers.
bootstrap version : 3.0.3
ol version: 2.13.1
This does not help http://openlayers.org/dev/examples/bootstrap.html
<!DOCTYPE html>

<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="">
<meta name="author" content="">

<title>Fixed Top Navbar Example for Bootstrap</title>

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

    Nav

A: The example you refer to use Bootstrap version 2.2.1. your are using Bootstrap 3.0.3. There are many changes between version 2 and 3 of Twitter's Bootstrap, see also: Updating Bootstrap to version 3 - what do I have to do?
In your case start reading: http://getbootstrap.com/getting-started/#third-parties
The Openlayers' javascript add a class olMap to

 use CSS to set it's height / width, like:
div.olMap
{
  cursor: default;
  height: 500px;
  margin: 0 !important;
  padding: 0 !important;
  width: 100%;
  z-index: 0;
}

NB your html for the row and column looks strange, try:


text:
Q: how to keep only two specific words after each other I want my dataframe start with Login then followed with Logout, and continues with Login  and Logout only.
for exammple (before):

output (after):

A: Try this code:
df.drop(df[df['B'] == "View"].index, inplace=True)

A: First remove View rows and then filter consecutive Login, Logout rows:
df = df[df['B'].ne("View")]

m1 = df['B'].eq('Login') & df['B'].shift(-1).eq('Logout')
m2 = df['B'].eq('Logout') & df['B'].shift().eq('Login')

df2 = df[m1 | m2]

print (df2)
        B         C
0   Login  02:29:04
2  Logout  02:29:14
7   Login  02:38:45
9  Logout  02:39:05


text:
Q: Integrability of $f(t) =\frac{2^{\frac{it+1}{1.5}}}{2^{\frac{it+1}{2}}} \frac{\Gamma \left( \frac{it+1}{1.5} \right) }{\Gamma \frac{ it+1}{2} }$ Can we show that the following  function is integrable
\begin{align}
f(t) =\frac{2^{\frac{it+1}{1.5}}}{2^{\frac{it+1}{2}}} \frac{\Gamma \left( \frac{it+1}{1.5} \right) }{\Gamma \left(\frac{ it+1}{2} \right)},
\end{align}
where $t \in \mathbb{R}$ and $i=\sqrt{-1}$.
That is can we show that
\begin{align}
\int_{-\infty}^{\infty} |f(t)| dt<\infty.
\end{align}
I was wondering if Stirling's approximation can be used, since this is a complex case?
Note if Stirling's approximation can be used than
\begin{align}
f(t) \approx  \sqrt{\frac{1.5}{2}}\frac{2^{\frac{it+1}{1.5}}}{2^{\frac{it+1}{2}}} \frac{ \left( \frac{it+1}{1.5 e} \right)^{\frac{1+it}{1.5}} }{ \left(\frac{ it+1}{2 e} \right)^{\frac{1+it}{2}}}.
\end{align}
Note that
\begin{align}
|f(t)| &\approx \left| \frac{2^{\frac{it+1}{1.5}}}{2^{\frac{it+1}{2}}}\right| \left|  \frac{ \left( \frac{it+1}{1.5 e} \right)^{\frac{1+it}{ 1.5}} }{ \left(\frac{ it+1}{2 e} \right)^{\frac{1+it}{2}}}\right|\\
&=\left| \frac{2^{\frac{it+1}{1.5}}}{2^{\frac{it+1}{2}}}\right| \left|  \frac{ \left( it+1\right)^\frac{1+it}{1.5} }{ \left( it+1 \right)^{\frac{1+it}{2}}}\right|    \left|\frac{ \left(2 e\right)^{\frac{1+it}{2 }}} {(1.5 e)^{\frac{1+it}{ 1.5}}} \right|
\end{align}
Also we have that
\begin{align}
&\left|\frac{2^{\frac{it+1}{1.5}}}{2^{\frac{it+1}{2}}}\right|= 2^{\frac{2}{3}-\frac{1}{2}} \\
& \left|\frac{ \left(2 e\right)^{\frac{1+it}{2 }}} {(1.5 e)^{\frac{1+it}{ 1.5}}} \right| =\frac{ \left(2 e\right)^{\frac{1}{2 }}} {(1.5 e)^{\frac{1}{ 1.5}}}
\end{align}
So, in the end we if everthing is corect we have to show that
\begin{align}
g(t)=\left|  \frac{ \left( it+1\right)^\frac{1+it}{1.5} }{ \left( it+1 \right)^{\frac{1+it}{2}}}\right|
\end{align}
is integrable, but I am not sure how to show if the above equation is integrable or not?
Any ideas would be greatly appreciated. Thank you.
Edit
The integrability of $g(t)$ has been shown in one of the answers.
My question now is the following: Since we have that
\begin{align}
|f(t)| =|g(t)| +e
\end{align}
and $g(t)$ is integrable does this mean that $f(t)$ is inegrable?  Can we prove that the error term $e$ is also integrable?

A: We have $$\left|  \frac{ \left( it+1\right)^\frac{1+it}{1.5} }{ \left( it+1 \right)^{\frac{1+it}{2}}}\right| = |(1+it)^{\frac{1+it}{6}}|= \left|\exp\left(\left(\frac{1+it}{6}\right)\ln(1+it)\right)\right|.$$ Remember that $|e^z|=e^{\Re(z)}$ and $$\Re\left(\left(\frac{1+it}{6}\right)\ln(1+it)\right)=\frac{\ln(\sqrt{1+t^2})}{6}-\frac{t\arg(1+it)}{6}.$$ (Here we have used the definition of the complex logarithm $\ln(z) = \ln|z|+i\arg(z)$.) Hence $$g(t) = (1+t^2)^{1/12} e^{-\arg(1+it)t/6}.$$ If $t>0$ is big enough, we can assume that $\arg(1+it)>\pi/4$, hence $$g(t) < (1+t^2)^{1/12} e^{-\frac{\pi t}{24}}$$ is clearly integrable at $+\infty.$ You can procede in a same way for $-\infty.$


text:
Q: Firebase onDisconnect и RemovalValue выдают ошибку (Java, Android) При нажатии на выход из аккаунта приложение показывает ошибку в строке: currentref.onDisconnect().removeValue();

java.lang.NullPointerException: Attempt to invoke virtual method
  com.google.android.gms.tasks.Task
  com.google.firebase.database.DatabaseReference.removeValue()' on a
  null object reference             at com.gulov.map.ListOverflow.onOptionsItemSelected(ListOverflow.java:125)

import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.ViewGroup;

import com.firebase.ui.database.FirebaseRecyclerAdapter;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;

public class ListOverflow extends AppCompatActivity {
    DatabaseReference onlineRef, currentUserRef, counterRef;
    FirebaseRecyclerAdapter<User, ListOnlineViewHolder> adapter;

    RecyclerView listOnline;
    RecyclerView.LayoutManager  layoutManager;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_list_overflow);

        listOnline = (RecyclerView)findViewById(R.id.listOnline);
        listOnline.setHasFixedSize(true);
        layoutManager = new LinearLayoutManager(this);
        listOnline.setLayoutManager(layoutManager);

        Toolbar toolbar  = (Toolbar)findViewById(R.id.toolbar);
        toolbar.setTitle("Systeme location");
        setSupportActionBar(toolbar);

        onlineRef = FirebaseDatabase.getInstance().getReference().child(".info/connected");
        counterRef = FirebaseDatabase.getInstance().getReference("lastOnline");
        counterRef = FirebaseDatabase.getInstance().getReference("lastOnline").child(FirebaseAuth.getInstance().getCurrentUser().getUid());

        setUpSysytem();
        updateList();

    }

    private void updateList() {
       adapter = new FirebaseRecyclerAdapter<User, ListOnlineViewHolder>(User.class, R.layout.card_layout, ListOnlineViewHolder.class, counterRef) {
            @Override
            protected void populateViewHolder(ListOnlineViewHolder viewHolder, User model, int position){
                viewHolder.txtEmail.setText(model.getEmail());
            }
        };

        adapter.notifyDataSetChanged();
        listOnline.setAdapter(adapter);
    }

   private void setUpSysytem() {
         onlineRef.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                if (dataSnapshot.getValue(Boolean.class)){

                    currentUserRef.onDisconnect().removeValue();
                    counterRef.child(FirebaseAuth.getInstance().getCurrentUser().getUid()).setValue(new User(FirebaseAuth.getInstance().getCurrentUser().getEmail(), "Online"));
                    adapter.notifyDataSetChanged();

                }

            }

            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {

            }
        });
        counterRef.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                for (DataSnapshot postSnapshot:dataSnapshot.getChildren()){
                    User user = postSnapshot.getValue(User.class);
                    Log.d("LOG", "" +user.getEmail()+" is" + user.getStatus());
                }
            }

            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {

            }
        });

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.main_menu, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()){
            case R.id.action_join:
                counterRef = FirebaseDatabase.getInstance().getReference("lastOnline").child(FirebaseAuth.getInstance().getCurrentUser().getUid());
                break;
            case R.id.action_logout:
                currentUserRef.removeValue();

                break;

        }
        return super.onOptionsItemSelected(item);
    }
}


text:
Q: Maperitive won't open on my Mac: Unhandled Exception: System.TypeInitializationException Is there anyone who can tell me what's going on here?  When I enter "mono Maperitive.exe" in the Terminal, I get this:
Unhandled Exception:
System.TypeInitializationException: An exception was thrown by the type initializer for System.Drawing.KnownColors ---> System.TypeInitializationException: An exception was thrown by the type initializer for System.Drawing.GDIPlus ---> System.DllNotFoundException: /Library/Frameworks/Mono.framework/Versions/3.12.1/lib/libgdiplus.dylib
  at (wrapper managed-to-native) System.Drawing.GDIPlus:GdiplusStartup (ulong&,System.Drawing.GdiplusStartupInput&,System.Drawing.GdiplusStartupOutput&)
  at System.Drawing.GDIPlus..cctor () [0x00000] in :0
  --- End of inner exception stack trace ---
  at System.Drawing.KnownColors..cctor () [0x00000] in :0
  --- End of inner exception stack trace ---
  at System.Drawing.SystemColors.get_ControlLightLight () [0x00000] in :0
  at Deska.Theming.Theme..ctor () [0x00000] in :0
  at (wrapper managed-to-native) System.Reflection.MonoCMethod:InternalInvoke (System.Reflection.MonoCMethod,object,object[],System.Exception&)
  at System.Reflection.MonoCMethod.InternalInvoke (System.Object obj, System.Object[] parameters) [0x00000] in :0
[ERROR] FATAL UNHANDLED EXCEPTION: System.TypeInitializationException: An exception was thrown by the type initializer for System.Drawing.KnownColors ---> System.TypeInitializationException: An exception was thrown by the type initializer for System.Drawing.GDIPlus ---> System.DllNotFoundException: /Library/Frameworks/Mono.framework/Versions/3.12.1/lib/libgdiplus.dylib
  at (wrapper managed-to-native) System.Drawing.GDIPlus:GdiplusStartup (ulong&,System.Drawing.GdiplusStartupInput&,System.Drawing.GdiplusStartupOutput&)
  at System.Drawing.GDIPlus..cctor () [0x00000] in :0
  --- End of inner exception stack trace ---
  at System.Drawing.KnownColors..cctor () [0x00000] in :0
  --- End of inner exception stack trace ---
  at System.Drawing.SystemColors.get_ControlLightLight () [0x00000] in :0
  at Deska.Theming.Theme..ctor () [0x00000] in :0
  at (wrapper managed-to-native) System.Reflection.MonoCMethod:InternalInvoke (System.Reflection.MonoCMethod,object,object[],System.Exception&)
  at System.Reflection.MonoCMethod.InternalInvoke (System.Object obj, System.Object[] parameters) [0x00000] in :0

A: Try these steps:

*

*Install Mono Framework via Homebrew's Cask:
brew cask install mono-mdk
After this step you should have the Mono Framework accesible at
/Library/Frameworks/Mono.framework

*Run mono with a PATH to your installation:
env PATH=/Library/Frameworks/Mono.framework/Commands:$PATH mono Maperitive.exe
Extras:

*

*If you don't have Homebrew installed, run:
ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"
More info at Homebrew's homepage.

*If you don't have Cask, run:
brew install caskroom/cask/brew-cask
More info at Cask's homepage.
By the way, consider to just run Windows XP in a virtual machine, like Virtual Box. In my personal experience it's way better.


text:
Q: React-Native, Render H5 Canvas and EaselJS shapes in Webview I created an HTML page that can draw with Canvas and EaselJS, I can draw in canvas with mouse in Web app. Also,  I want to embed the page into React-native Webview.
In iOS, it is embedded into Webview successful, but, can't draw with finger touch. I can't find the reason and figure out how to solve it.
In Web browser:
See html in browser(picture)
In iOS app, it can render in Webview, but, can't use pen to draw with touch.
the HTML code below (I have added touch event listen):
<!DOCTYPE html>

    <title></title>

        <input type="button" id="circle" value="Add Circle">
        <input type="button" value="Add Square" onclick="createShape('rect');">
        <input type="button" value="Add Line" onclick="createShape('line');">
        <input type="button" id="pen" value="Use Pen">
        <input type="button" value="Erase" onclick="createShape('erase');">
        <input type="text" id="input_text">
        <input type="button" value="Input text" onclick="createShape('text', getText());">

the React native code snippet is:
render() {
              return (
                <View style={styles.container}>
                  <WebView source={
                Platform.OS === 'ios' ?       require('../../server/public/index.html') : {uri: 'file:///android_asset/index.html'}}
                  javaScriptEnabled={true}
                  ref={c => { this.webview = c; }}
                  onLoad={this.injectJavaScript}
                  startInLoadingState={true}
                  mediaPlaybackRequiresUserAction={true}
                  scrollEnabled={ this.props.scrollEnabled || false } />
                </View>
              )
            }

It's ok to create shapes into stage, can't draw with finger touch!
See html in iOS emulator(picture)
At the same time, the HTML page is rendered successfully in iOS, but, unable to load js both of js code and js reference link in the HTML.
like issue 8089 / 505 in React-native.
any helps?
Thanks.

A: You should add the code to enable the touch event. Add the below code to enable it
 createjs.Touch.enable(stage);

For further please refer below document
http://www.createjs.com/docs/easeljs/classes/Touch.html


text:
Q: How to break out of an inner loop back to an outer loop? I have 4 entities"
ObjectA, ObjectB, ObjectC, ObjectD
foreach(ObjectA objectA in listObjectA)
if (relationAB)
  foreach(ObjectB objectB in listObjectB)
  if (relationBC)
    foreach(ObjectC objectC in listObjectC)
    if (relationCD)
      foreach(ObjectD objectD in listObjectD)
        if (I found what I'm looking for)
        Do something

So, when I will found what I wass looking for, I want to go to the first line, to the first for, but to the second element from the list. How can I do this? Whit goto?
Later Edit: This question is for C#.
P.S. Could you think a better way to do what I'm trying to do, whithout using 4 fors?

A: Well, since this is just a "programming languages" question, the general answer would be to use your language's facility for naming loops, and then put the proper name on the "break" statement.
Sadly, I don't think the current versions of C and C++ support such a thing, so you would indeed have to resort to a goto when using them. A good way to avoid that would be to put the loop you want to break out of into its own subroutine, and just do a return when you are done instead of a break. That's what I generally do when working in those poor languages.
Your revised example would be:
void find_whatever (/* probably pass in the lists or objects to search for*/)
  foreach(ObjectA objectA in listObjectA)
    if (relationAB)
      foreach(ObjectB objectB in listObjectB)
        if (relationBC)
          foreach(ObjectC objectC in listObjectC)
            if (relationCD)
              foreach(ObjectD objectD in listObjectD)
                if (I found what I'm looking for)
                Do something
                return;

Note: The tag was changed from "programming languages" to "C#". That was the right thing to do for the question, but a lot of people liked this answer so I'm not making major mods to it.

A: Depending on the language, you can generally add break labels. I'd avoid this, however, and suggest the following:
function main() {
    foreach (ObjectA a in listA) {
        if (relationAB) {
            processA(a)
        }
    }
}

function processA(ObjectA a) {
    foreach (b) {
        foreach (c) {
            foreach (d) {
                if (found) {
                    doSomething();
                    return;
                }
            }
        }
    }
}

It can be hard to read code that has break labels and gotos. Breaking it into functions can make it easier to read and (probably) easier to write and debug.

A: The simplest option is to put it all in a function and use the return statement instead of the break statement.

A: Better to use return in such cases.
Just put some of your inner for in a method and return from it when necessary. It will be much more readable then a chain of
if (found) {
 break;
}

inside your loops.


text:
Q: App Sandbox related I am developing apps (for MAC) which will NOT be hosted on the app store.These apps will be installed by dmg file. Can someone please confirm my assumptions?

*

*Even if I dont sandbox the apps, app will still work on OSX 10.7 and above (provided see point 2 below)

*If the security setting is "Mac Appstore and identified developer", in a non sandboxed scenario, user needs to right click and open the dmg file instead of double click it and installer can install apps to Application folder. Once installed applications can -
-Interact each other
-Access files

A: *

*Yes, out of the app store apps don't have to run in sandbox.

*The security setting has nothing to do with how your app is installed. If you build a installer (Xcode can do it for you) or you if you send the .app bundle in a dmg to be dragged into applications folder is a thing of your choice. An app that is not running in sandbox can interact with any other app and with any system resource, only limit is user permissions. OS X is still Unix and the fact that app store has rules about sandbox doesn't change the world out of app store.


text:
Q: What does '@' in a Lambda expression mean
Possible Duplicate:
What does placing a @ in front of a C# variable name do?

I am trying to learn C# lambda expressions. As I search for examples I am seeing the below code
Where(@t => string.Compare(@t.Code, argument.Code, StringComparison.CurrentCultureIgnoreCase) == 0)

I am wondering what does the '@' symbole before the t mean?

A: Nothing unusual.  You can prefix  varible names with @ as a sort of escape if the varible is a key word.
For example you can also do 'var @class = 5' .  Normally you'd not be able to compile as class is a keyword, but prefixing with @ allows you to use it as a varible.


text:
Q: Setting a *next list pointer to NULL I have a list with a few nodes. I'm trying to mark the final node by declaring it's current->next value as NULL.
So, let's say that my current is pointing at the final node. Do the two following code snippets work in a different way, and if yes, how?
 current->next = NULL;

and
 current = current->next;
 current = NULL;

I have been experimenting with these for a while now but I cannot really understand what is going on in there. I would say they are doing the same thing, as the second one first points my current to where next points and then sets it to NULL.
EDIT : Oh, I understand what the answers are saying, and it looks quite obvious to me too now :).  So if I do not use the first way, but opt to go for current = current->next is there a way for me to put the NULL value where I ought to? How can I use my new current to point where my old next was pointing at?

A: Yes, those are different, and it is the first version that you want.
In the second, you're only changing the value of the local variable current (to NULL), while the next pointer of the final node stays the same (it probably should be initialized to NULL in the first place, but maybe that's what you're doing).

A: The former snippet assigns the next field of the struct pointed to by current to NULL.  The second snippet makes the current pointer point at the next field of the struct pointed to by current and then sets current to NULL.
I don't really understand the usefulness of the second unless you have some other way to get a reference to the struct, since you essentially cut yourself off from the struct by losing your pointer to it.
So in the former case:
current -> struct
           next -> NULL

In the latter case:
current -> NULL

           struct
           next -> ????