text:
Q: Python HTML Email : How to insert list items in HTML email I tried hard to find solution to this issues but all in vein, finally i have to ask you guys. I have HTML email (using Python's smtplib). Here is the code
Message = """From: abc@abc.com>
To: abc@abc.com>
MIME-Version: 1.0
Content-type: text/html
Subject: test

Hello,
Following is the message
""" + '\n'.join(mail_body)  + """
Thank you.
"""

In above code, mail_body is a list which contains lines of output from a process. Now what i want is, to display these lines (line by line) in HTML email. What is happening now its just appending line after line. i.e.
I am storing the output(of process) like this :
for line in cmd.stdout.readline()
    mail_body.append()

Current Output in HTML email is:
Hello,
abc
Thank you.

What i want :
Hello,
a
b
c
Thank you.

I just want to attach my process output in HTML email line by line. Can my output be achieved in any way?
Thanks and Regards

A: You could generate the email content to send using email package (from stdlib) e.g.:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from cgi import escape
from email.header import Header
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from smtplib import SMTP_SSL

login, password = 'me@example.com', 'my password'

# create message
msg = MIMEMultipart('alternative')
msg['Subject'] = Header('subject…', 'utf-8')
msg['From'] = login
msg['To'] = ', '.join([login,])

# Create the body of the message (a plain-text and an HTML version).
text = "Hello,\nFollowing is the message\n%(somelist)s\n\nThank you." % dict(
    somelist='\n'.join(["- " + item for item in mail_body]))

html = """<!DOCTYPE html><title></title>
Hello,
Following is the message

%(somelist)s

Thank you. """ % dict(
    somelist='\n'.join(["
 " + escape(item) for item in mail_body]))

# According to RFC 2046, the last part of a multipart message, in this case
# the HTML message, is best and preferred.
msg.attach(MIMEText(text, 'plain', 'utf-8'))
msg.attach(MIMEText(html, 'html', 'utf-8'))

# send it
s = SMTP_SSL('smtp.mail.example.com', timeout=10) # no cert check on Python 2

s.set_debuglevel(0)
try:
    s.login(login, password)
    s.sendmail(msg['From'], msg['To'], msg.as_string())
finally:
    s.quit()

A: in HTML, a new line is not \n it is
 for "line break" but since you are also not using HTML tags in this email, you also need to know that in MIME messages, a newline is \r\n and not just \n
So you should write:
'\r\n'.join(mail_body)

For newlines that deal with the MIME message, but if you are going to use the HTML for formatting, then you need to know that
 is the line break, and it would be:
'
'.join(mail_body)

To be comprehensive, you could try:
'\r\n
'.join(mail_body)

But I do now know what that would like like...


text:
Q: Adding labels over bars in ggplot2 I am using ggplot2 to plot bar chart. I want to add labels over bars in bar chart but the label name of the bar with the highest value gets hidden. I tried to set margin but the label value still not get visible.
library(ggplot2)
x <- c(1:27)
y <- c(988,1195,804,574,414,309,234,196,169,125,95,73,57, 63 ,31,32 ,28 ,29 ,37 ,37 ,21 ,20 ,5,4,2,1,4)
z <- c(11233,7856,5926,4615,3714, 3037, 2548, 2156, 1842, 1610, 1436, 1302, 1177,1066  ,1000 ,936,882,828,760,697,659,621,611,603,599,597,591)
dat <- data.frame(x,y,z)

g <- ggplot(dd, aes(x = dat$x, y = dat$y)) +
  geom_bar(stat = "identity", colour = "black", fill = "pink", width = .5,
           position = position_dodge()) +
  geom_text(aes(label = dat$z, hjust = 0), position = position_dodge(width = 0.9),
            angle = 90)
g
g + theme_bw() +
  theme(panel.grid.major = element_blank(),
        panel.background = element_blank(),
        plot.margin=unit(c(0.5, 1, 1, 2), "lines")) +
  scale_y_continuous(expand = c(0, 0))

And the barplot I get is

A: Try using a different value for the expand parameter within scale_y_continuous:
g <- ggplot(dat, aes(x = x, y = y)) +
  geom_bar(stat = "identity", colour = "black", fill="pink", width = .5,
           position = position_dodge()) +
  geom_text(aes(label = z, hjust=0),
            position = position_dodge(width = 0.9), angle = 90) +
  scale_y_continuous(expand = c(0.15, 0))
g

A: Or adjust the limits:
+ scale_y_continuous(expand = c(0,0), limits = c(0, max(y) * 1.15))

redpajama_set_name: RedPajamaStackExchange


text:
Q: Problem with opencv puttext function in c++ When I use the openCV putText() function and the string contains a "2" there is an additional line printed on the image. For strings that do not contain a 2 everything works fine.
#include <iostream>
#include <opencv2/opencv.hpp>

using namespace cv;
using namespace std;

int main() {

    Mat image = imread("../test.jpg");

    Point pt1(225, 170);
    Point pt2(456, 546);
    Scalar color(100,200,100);
    rectangle(image, pt1, pt2, color, 2);

    putText(image, "Tag 2", pt1 - Point(0,5), FONT_HERSHEY_SIMPLEX, 0.5, color, 2);

    namedWindow("Test",WINDOW_AUTOSIZE);
    imshow("Test", image);
    waitKey(0);

    return 0;
}

When the string that I want to display on the image contains a "2" there is an additional line that crosses the string. With other numbers for example "1" everything looks normal.


text:
Q: Typing context as a monad for multicategories In some ways simple type theory matches up nicer with multicategories than with categories.
A hom
$$ f \colon o_1 ; \ldots o_n \rightarrow o'$$
Matches up nicely with a well typed term
$$ x_1 \colon t_1 , \ldots x_n \colon t_n \vdash v \colon t' $$
However, there are some technical difficulties especially with constructively mechanizing things.
A nameless style such as with de Bruijn indices works okay but it'd be nice to have an explicitly named style. Using the definition of generalized multicategories one wants some sort of key value map monad.
You would probably also expect a functor from "named multicategories" to list multicategories.
My intuition says to me you would end up with ordered lists of variable object pairs and list of variables indexed identity (variable reference) and compose (multisubstitution) operations.
$$\text{id}_{[x]} \colon \text{Hom}(x \mapsto A; A)$$
$$\circ_{x, y} \colon
\text{Hom}(y_j \mapsto B_j ;  C) \rightarrow
[y_j \mapsto \text{Hom}(x_i \mapsto A_{ij} ; B_{ij})] \rightarrow
\text{Hom}(x_{ij} \mapsto A_{ij} ; C)$$
I think you would need to base things around graded multicategories though and I don't know about those.
Also I think you might need to ban duplicate variables/variable shadowing or use quotients which is icky.
In general this is getting into category theory stuff I don't know or getting ugly.
I wonder if there's been any work on "named multicategories" and if there are nicer ways of doing things.
I've been thinking about this stuff for a while but specifically I have a renewed interest because I suspect it can help illuminate hereditary substitution for me.


text:
Q: How to change border color of the html input when For the sake of learning, I am making a login-registration system in HTML, CSS, and PHP. There would be different HTML text boxes and stuff.
What I want to achieve is when I write something in one text box, then take out my cursor and click on another textbox, I want to change the border color of the first text box to green.
I know how to change the border color through CSS but I want to do this only when such an event happens. Any help would be greatly appreciated.

A: Attach blur event to the input.

document.querySelectorAll('input').forEach((input) => {
  input.addEventListener('blur', function() {
    this.classList.toggle('green', this.value.length > 0);
  });
});
.green {
    border: 2px solid green;
}
<input type="text">
<input type="text">
<button>Click Me</button>

A: You can add a class through Jquery and give the styles in CSS. It will also help you later when you try to add validations then you can just change class name for showing red borders to indicate errors.
You can also add a class when you are in focus to show your multiple state changes.
$(document).ready(function($) {
    $(".text").focus(function(){
       $(this).addClass("Yellow");
    }).blur(function(){
       $(this).addClass("success");
    })
});

A: here The code is :

input {
  border: 1px solid #ccc;
  border-radius: 5px;
  padding: 5px;
  outline: none;
  height: 25px;
  width: 150px;
}

input:focus {
  border-color: green;
}
<input type="text" />


text:
Q: JCombobox not refreshing Hi i have two class Banque and Succursale, Bank has a list of Succursale and each time that list changes i want Succursale to get it and then using it to refresh the JCombobox of its view, problem is that the JComboBox is not refreshing while its item count is incrementing, here are the class
import java.io.IOException;
import java.net.ServerSocket;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Observable;

public class Banque extends Observable {
private List<Succursale> listSucc = new ArrayList<Succursale>();
private int sommeTotale;
private int nbSuccInit = 4;

public void ajouteSucc(Succursale suc){

}
public Banque(){
    initialiserServeur();
}
private void initialiserServeur() {
    ServerSocket serverSocket = null;
    try {
        serverSocket = new ServerSocket(10118);
    }
    catch (IOException e)
    {
        System.err.println("On ne peut pas ecouter au  port: 10118.");
        System.exit(1);
    }
    System.out.println ("Le serveur est en marche, Attente de la connexion.....");
    int i = 0;
    while(i<5){
        try {
            UtilMultiTh mt = new UtilMultiTh(serverSocket.accept());
            Thread t = new Thread(mt);
            t.start();
            t.join();
            Succursale s = mt.getSuc();
            listSucc.add(s);
            this.addObserver(s);
            this.setChanged();
            this.notifyObservers(this.listSucc);

            //System.out.println(listSucc.size());

           /* for(int j =0; j<listSucc.size();j++){
                System.out.println("La succursale "+(j+1)+" est:"+listSucc.get(j).getName());
            }
            i++;
            System.out.println("FLAGPOSTban");*/
        }
        catch (IOException | InterruptedException e)
        {
            System.err.println("Accept a echoue.");
            System.exit(1);
        }
    }

    System.out.println ("connexion reussie");
    System.out.println ("Attente de l'entree.....");

}

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

The class Succursale
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;
import java.util.Observable;
import java.util.Observer;

import javax.swing.ComboBoxModel;

public class Succursale implements Serializable, Observer {
private String coordonnees;
private String name;
private int sommeDepart;
private int sommeRecue;
private int sommeEnvoyee;
private List<Succursale> listSuccAc = new ArrayList<Succursale>();
private GuiSuccursale succView;

public Succursale (){
    succView = new GuiSuccursale(Constantes.sommeDepart,1);
    this.sommeDepart=Constantes.sommeDepart;
    this.name="Succursale: "+(1);
    connexionBanque();
}
public void connexionBanque(){
    String host = Constantes.adrBanque[0];
    int port = Constantes.portBanque[0];
    Socket echoSocket = null;
    try {
        echoSocket = new Socket(host, port);
        ObjectOutputStream oos = new ObjectOutputStream(echoSocket.getOutputStream());
        oos.writeObject(this);
        //System.out.println("FLAGPOSTSUcc");
    } catch (UnknownHostException e) {
        System.err.println("Hôte inconnu: " + host);
        System.exit(1);
    } catch (IOException e) {
        e.printStackTrace();
        System.err.println("Ne pas se connecter au serveur: " + host);
        System.exit(1);
    }
}
public void connexionSuccursales(){

}
public void envoiManuel(){

}
public String getName() {
    return name;
}
public void envoiPeriodique(){

}
public static void main (String[] args){
    Succursale suc = new Succursale();
}
@Override
public void update(Observable arg0, Object arg1) {
    this.listSuccAc= (List)arg1;
    this.succView.setListeSucc(listSuccAc);
    //this.succView.validate();
    //System.out.println("Mes succ connectees sont:"+this.listSuccAc.size());
    //System.out.println("Mes succ connectees sont:"+this.getName());

}
}

and the view of Succursale
import java.awt.Font;
import java.awt.GridLayout;
import java.util.List;

import javax.swing.ComboBoxModel;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

public class GuiSuccursale extends JFrame{

private JLabel labelSum = new JLabel("Montant:");
private JIntField champMontant = new JIntField(0, 0, Integer.MAX_VALUE);
private JLabel labelSumDispo = new JLabel ("Somme Disponible");
private JIntField champSumDispo;
private JLabel labelSucc = new JLabel("Vers la Succursale:");
private ComboBoxModel cbm;
private JComboBox listeSucc = new JComboBox<>();
private JPanel pan = new JPanel();
private JButton btnTransferer = new JButton("Transferer");
private JButton btnEffacer = new JButton("Effacer");
public  GuiSuccursale(int sumDepart, int num){
    init(sumDepart, num);
}
public void init(int sumDepart, int num){

    GridLayout gl = new GridLayout();
    gl.setColumns(2);
    gl.setRows(4);
    gl.setHgap(5);
    gl.setVgap(5);
    pan.setLayout(gl);

    labelSumDispo.setHorizontalAlignment(JLabel.CENTER);
    labelSumDispo.setFont(new Font("Tahoma", Font.BOLD, 11));

    champSumDispo = new JIntField(sumDepart, 0, Integer.MAX_VALUE);
    champSumDispo.setEditable(false);

    labelSucc.setHorizontalAlignment(JLabel.CENTER);
    labelSucc.setFont(new Font("Tahoma", Font.BOLD, 11));

    labelSum.setHorizontalAlignment(JLabel.CENTER);
    labelSum.setFont(new Font("Tahoma", Font.BOLD, 11));

    pan.add(labelSumDispo);
    pan.add(champSumDispo);
    pan.add(labelSucc);
    pan.add(listeSucc);
    pan.add(labelSum);
    pan.add(champMontant);
    pan.add(btnTransferer);
    pan.add(btnEffacer);

    this.setContentPane(pan);
    this.setSize(300, 150);
    this.setTitle("Succursale: "+num);
    this.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
    this.setLocationRelativeTo(null);
    this.setResizable(true);
    this.setVisible(true);
}
public JComboBox getListeSucc() {
    return listeSucc;
}
public void setListeSucc(List<Succursale> listeSucc) {
    this.listeSucc.removeAllItems();
    for(int i = 0; i<listeSucc.size();i++){
        System.out.println("l<index est:"+i);

        this.listeSucc.addItem(listeSucc.get(i).getName());
        System.out.println(this.listeSucc.getItemCount());
    }
}

}


text:
Q: Calculating angles for a radial menu I'm working with a copy of a demo page. I've found out that the alignment of the menu items (li) is done using the nth-child pseudo selector and the rotate property. The problems I'm facing with the demo are:

*

*The number of menu items is fixed. On the page where I plan to use this, the number of menu items is dynamic because it changes from one user to the next.

*Its orientation is up to 180 degrees, whereas I want it to be a full 360 degrees.
In order to overcome these problems, I decided to use jQuery to count the number of menu items, then apply the appropriate rotate value to each item.
Upon investigating the CSS, I found that in the case of 7 menu items the rotation angle values are:

*

*-20 degrees for the 1st child

*12 degrees for the 2nd child

*44 degrees for the 3rd child

*76 degrees for the 4th child and so on.

In summary:

-20 degrees for the first child and keep adding 32 degrees for the next 6 children

Now I'm struggling to figure out the math behind it. I wish to calculate these values dynamically based on the number of menu items. What formula should I use to get the appropriate angles for each child?

A: calculate the number of menu items.
so yo want to divide 360d between them.
simply by divide you understand each menu item degree
var each_item_degree = 360 / number_of_items;

you should add from fist child to last child each_item_degree.

it will gives you what you want, but without any margins. for margins between them yo can easily reduse total margins from 360, for example if for 7 item is 32d witch starts from -20 to 12, start next one from 15d. it gives you 3d margin.

good luck .

A: We can work out the formula with a bit of algebra. Let's do it!
Linear sections
Suppose we have a quantity y that we want to divide into n sections of size x that are separated by gaps of size p*x.
If there is a gap after every section except the last one, there are n-1 gaps.
Thus, we have:
n*x + (n-1)*p*x  =  y

(n + (n-1)*p) * x  =  y

x  =  y / (n + (n-1)*p)

For example, if the quantity is 180 and we want to make 7 sections of size x separated by gaps of size 0.1*x, we get:
x  =  360 / (7 + 6*0.1)

   =  23.6842

Now let's consider the total distance from the start of each section to the next.
If a section starts at position t0, the next section starts at position t1 such that:
t1  =  t0 + x + p*x

To continue with the figures above, we get:
t1  =  t0 + 23.6842 + 0.1*23.6842

    =  t0 + 26.0526

Now we know that the section starting points are 26.0526 units apart and each section is 23.6842 units long.
Circular sections
If the quantity that we're subdividing is circular, the calculation is different because the last section and the first section are also separated by a gap. In other words, there are n gaps in the circle.
Now we have:
n*x + n*p*x  =  y

(n + n*p) * x  =  y

x  =  y / (n + n*p)

So if we're dividing 360 degrees into 7 sections of size x with gaps of size 0.1*x, we get:
x  =  360 / (7 + 0.1*7)

   =  46.7532

That's the size of a section. The distance between the starting point t0 of one section and the starting point t1 of the next section is:
t1  =  t0 + x + p*x

    =  t0 + 46.7532 + 0.1*46.7532

    =  51.4285

In summary, the distance from the start of each section to the start of the next section is 51.4285, and the length of each section is 46.7532.


text:
Q: Set column order in sequelize.js I would like to put user_id column before the timestamps, how can i tell this to sequelize.define?
sequelize.define('UserPassport', {
    method: DataType.STRING,
    token:  DataType.STRING,
    social_id: DataType.STRING
  }, {
    classMethods: {
      associate: function(models) {
        UserPassport.belongsTo(models.User);
      }
    },
    tableName:   'user_passports',
    underscored: true
  });

schema of the table:
CREATE TABLE `user_passports` (
      `id` int(11) NOT NULL AUTO_INCREMENT,
      `method` varchar(255) DEFAULT NULL,
      `token` varchar(255) DEFAULT NULL,
      `social_id` varchar(255) DEFAULT NULL,
      `created_at` datetime NOT NULL,
      `updated_at` datetime NOT NULL,
      `user_id` int(11) DEFAULT NULL,
      PRIMARY KEY (`id`),
      KEY `user_id` (`user_id`),
      CONSTRAINT `user_passports_ibfk_1` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`) ON DELETE SET NULL ON UPDATE CASCADE
    ) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;

P.S: is it possible to make a composite key out of method and social_id so they both would compose the PK instead of the id field.

A: All you need to do is just to add it in define stage wherever you want, like so:
var user_passport = sequelize.define('user_passport', {
    method: DataTypes.STRING,
    token: DataTypes.STRING,
    social_id: DataTypes.STRING,
    user_id: DataTypes.INTEGER
}, {
    classMethods: {
        associate: function(models) {
            user_passport.belongsTo(models.User, { foreignKey: 'user_id' });
        }
    },
    tableName: 'user_passports',
    underscored: true
});

and in associate attach a reference to the field:
user_passport.belongsTo(models.settings, { foreignKey: 'user_id' });


text:
Q: How to get a git repository's default branch in Ruby's "rugged" gem? Related to git - how to get default branch?
I'm trying to port a Bash script to Ruby. The script uses git symbolic-ref --short HEAD to get a repo's default branch.
Is there a way to combine rugged's repo.branches.each_name(:local) with some other command to find the default branch?
Or am I thinking too complicated and there is a useful default in rugged that I am missing? The script needs to continue by creating a new branch off the default/latest one, check-it out, commit something standardized, push the new branch, and open a pull request against that base branch.


text:
Q: With Julia Symbolics, can I solve for a variable in an equation? I would like to solve for a in y = √((a^2 + b^2))
What I tried:
julia> using Symbolics

julia> @variables a b
(a, b)

julia> y = √((a^2 + b^2))
sqrt(a^2 + b^2)

julia> eq = y = √((a^2 + b^2))
sqrt(a^2 + b^2)

julia> eq
sqrt(a^2 + b^2)

And then to solve, I tried:
julia> Symbolics.solve_for(eq,[a])
julia> Symbolics.solve_for(eq,a)
julia> Symbolics.solve_for(y,[a])
julia> Symbolics.solve_for(y,a)

which all resulted in the error:
ERROR: type Num has no field rhs

A: There are two problems in your code. The first one is that an equation should have two parts, right hand side (i.e. rhs) and left hand side (i.e. lhs). Your error message clearly points out the problem: sqrt(a^2 + b^2) is a Num type since a and b are variables of Num since they will (supposed to) evaluate to numbers. In Symbolics.jl, the way to declare an equation is to use ~. So the right way to express your equation is
@variables a b y
eq = y ~ √((a^2 + b^2))

However unfortunately Symbolics.jl cannot solve it for you now since solve_for can only resolve system of linear equations, just as the document says

Currently only works if all equations are linear. check if the expr is linear w.r.t vars.

So it will throw AssertionError: islinear(ex, vars) error. However you can try out this function using some simple equation like a+b.
julia> eq = y ~ a+b
y ~ a + b
Symbolics.solve_for([eq],[a])
1-element Vector{Num}:
 y - b

BTW:
You can turn off the linearity check with check=false parameter, but it's almost guaranteed that Symbolics.jl will give you a wrong result. For example, the Symbolics.jl says the result of equation y ~ √((a^2 + b^2)) is a + y*sqrt(a^2 + b^2)*(a^-1) - ((a^-1)*(sqrt(a^2 + b^2)^2)).


text:
Q: How to use QML_IMPORT_PATH with Qt Cmake Project? I need to provide some modules for project.
Now, it looks for them in QT directory(I've installed it in $HOME), but instead of it I want to make it search in /usr/lib/x86_64-linux-gnu/qt5/qml/.
What I have tried:
a) Defining QML_IMPORT_PATH in .bashrc - didn't work out
b) Copying needed module in $HOME/Qt5.5.1/Tools/QtCreator/bin/qml/:
Here we have something different. If I open of the .qml files - it wouldn't underscore import line (which is ok). But, If I run executable with console - the same message module org.bla.bla is not installed.
So, If copying didn't help, maybe I had to just make QtCreator(or smth else) search for modules in appropriate folder, but how?
UPD.
Well, you can define path to your modules with QML2_IMPORT_PATH(not just QML, but QML2). As I mentioned above, I've copied module folder in $HOME/Qt5.5.1/Tools/QtCreator/bin/qml/ which is completely wrong! The right way was to copy it in $QT_HOME/5.5/gcc_64/qml/. It runs now fine, but I can't say the same about "how" it works. Unfortunately, this is not related to the question I've asked. Therefore, I'll not ask others to answer my question, but won't close it as well until find real problem and mention it here, so I can help others.

A: Here is an improvement of @Tom Deblauwe's answer that allows to keep system-specific local settings out of the repository's makefile. It assumes you use QT Creator as your IDE.

*

*In Qt Creator, open the "Projects" sidebar tab and there go to "Build & Run → [your build config's entry] → Build → CMake".

*In the list of CMake configuration settings you find there, set the value of setting QML_IMPORT_PATH according to your system. Separate multiple directories
with ";".

*You can additionally provide some common defaults in the repository's CMakeLists.txt makefile so that users with common setups don't need to set their their QML_IMPORT_PATH. The code below will not overwrite the user's QML_IMPORT_PATH but append to it. You'd add the following to CMakeLists.txt:
# Directories where Qt Creator can find QML files.
# (Not needed for builds, but makes Qt Creator code completion happy.)
list(APPEND QML_IMPORT_PATH "/example/path/to/qml")
list(APPEND QML_IMPORT_PATH "/second/example/path/to/qml")

# Prevent adding duplicate values at each run of CMake.
list(REMOVE_DUPLICATES QML_IMPORT_PATH)

# The variable is cached in ${BUILD_DIR}/CMakeCache.txt. We need FORCE to
# change it there immediately. Also, add a comment to the cache file.
set(QML_IMPORT_PATH ${QML_IMPORT_PATH}
    CACHE STRING "Qt Creator 4.1 extra qml import paths"
    FORCE
)

*After running CMake, QML_IMPORT_PATH is now the user-defined value plus some CMakeLists.txt defined values appended to it. Qt Creator's CMake configuration settings from steps 1-2 will still show the user's value in the table. But when mousing over that value, the full value incl. the appended portion is shown in a popover.

A: With the new and upcoming QtCreator 4.1 you will be able to do that. Just set QML_IMPORT_PATH in your CMake cache. If you have multiple paths, separate them with a ; which is just how a list is done in CMake.
list(APPEND QML_DIRS "dir1")
list(APPEND QML_DIRS "dir2")
set(QML_IMPORT_PATH "${QML_DIRS}" CACHE STRING "Qt Creator 4.1 extra qml import paths")


text:
Q: Data Stream Disconnection due to buffer overflow I am using HttpURLConnection in java to get Stream(JSON) from a Data Provider. BufferedReader is used for reading and processing is implemented in multiThread. It's fine when the JSON stream is up to 200 per sec, if it more stream is disconnected by the provider with this error
Force closing connection to xxx.xxx.xxx.xx because it reached the maximum allowed backup (buffer size is 2343 messages)

The code I am using to retrieve data is.
pool = new ThreadPoolExecutor(150, 200, 0L, TimeUnit.SECONDS, new LinkedBlockingQueue());
connection = getConnection(dataCollectorURL, username, password);
inputStream = connection.getInputStream();

            if(inputStream!=null)
            {
                int responseCode = connection.getResponseCode();
                if (responseCode >= 200 && responseCode <= 299) {
                    long time = Runtime.getRuntime().freeMemory();
                    BufferedReader reader = new BufferedReader(new InputStreamReader(new GZIPInputStream(inputStream, 100*1024),"utf-8"),100*1024);
                    BufferedReader errorReader = null;
                    String line = reader.readLine();
                    while(line != null){

                        jParser = new ObjectMapper().getJsonFactory().createJsonParser(line);
                        try
    {
        pool.execute(new ParseJSONTwitter(jParser.readValueAsTree()));
        if(loopCount==100)
        {
            printThreadStatus();
            loopCount = 0;
        }
        loopCount++;
    }
    catch(IOException e)
    {
        e.printStackTrace();
    }
                        if(reader.ready())
                        {
                            line = reader.readLine();

                        }
                        else
                        {
                            line = null;

                        }

                    }

                    if(!(responseCode>=200 && responseCode<=299) || line==null)
                    {
                        if(inputStream!=null)
                        {
                            inputStream.close();//To free n/w resources
                        }
                        reconnect();

                    }
                } else {
                    handleNonSuccessResponse(connection);
                        if(inputStream!=null)
                            {
                                inputStream.close();//To free n/w resources
                            }
                            reconnect();
                }
            }

Am I doing something wrong? Why does this error occurs?
Anyone aware of this issue???
Thanks.
-vibin


text:
Q: Drupal 7 - How to disable jQuery UI used by Views Accordion I'm using the Views Accordion module. I would like to disable the use of jQuery UI that it uses and use pure CSS instead.
I first cloned the module and did the necessary modifications, but then I read that it is not recommended to edit contributed modules, that it is better to create a new module that modifies their functionality, correct?
In the Views Accordion module there is this line in the views_accordion_style_plugin.inc:
public function pre_render($result) {
     drupal_add_library('system', 'ui.accordion');

What would I put on my module to disable adding that ui.accordion library?
Thanks!

A: That is right, you should never update a contrib module. It is always recommended to create your own module.
Create a new module, with hook_js_alter() implementation, and try to unset jquery ui javascript file if it does exist.
Code sample:
function MODULE_js_alter(&$js) {

    if(isset($js['misc/ui/jquery.ui.accordion.min.js']))
        unset($js['misc/ui/jquery.ui.accordion.min.js']);
}


text:
Q: I want to print a varValue of an object with it's related review objects. This is really frustrating. I would like to print out the name of the game object alongside the comment objects related to them. The reviews/replies are called by reference of the the object. I can tell the compiler knows the reference because it groups reviews and replies by game.
I want it like this:
Reviews for The Witcher 3 --- the part I want, the rest is easy.
Rev1/ User ID: u1;  Name: JD;  "This game is timeless!"
Rep1/ User ID: u2;  Name: Boss;  "Really? You run around in imaginary fields hunting for imaginary creatures...lame."
Rep2/ User ID: u1;  Name: JD;  "Blah, blah, something."
Other games ect...
Reviews group perfect for game type and replies group perfectly under the review. But I can't find a way to show the game the reviews are for. Is there a way?
Any help would be great.
review and reply methods are called like this:
game1.addReviews(review1);
review1.addReply(reply1);
reply1.addReply(reply2);

....
public class Comment {

protected List<Comment> reply = new ArrayList<Comment>();

private User user;
private String usrComment;

public Comment() {

}

public void addReply(Comment r) {

    this.reply.add(r);
}

@Override
public String toString() {
    return   this.user.getUsr() + '"' + this.usrComment + '"';
}

...
public abstract class Content {

protected List<Comment> Review = new ArrayList<Comment>();

private String ID;
private String Application_Name;

// constructor to take ID, name and price of app
public Content(String iD, String application_Name, double price) {
    super();
    ID = iD;
    Application_Name = application_Name;
    Price = price;
}
public void addReviews(Comment a) {

    this.Review.add(a);
}

}

...
public class Game extends Content {

private boolean isMultiPlayer;
private OS o;
private double Price = 0;

public Game(String iD, String application_Name, double price, boolean isMultiPlayer, OS o) {
    super(iD, application_Name, price);
    this.isMultiPlayer = isMultiPlayer;
    this.o = o;
}
}

A: This was silly. The object (game) is the object calling the method and passing another object as an argument. So any method or value related to the calling game object can be accessed within the method called. I was using two advanced loops and recursion, so I may have confused myself a little.


text:
Q: library(tidyverse) gives error message never seen before library(tidyverse)
> Error: package or namespace load failed for 'tidyverse' in loadNamespace(j <- i[[1L]], c(lib.loc, .libPaths()), versionCheck = vI[[j]]):
  namespace 'tibble' 2.1.3 is already loaded, but >= 3.0.0 is required
> In addition: Warning message:
> package 'tidyverse' was built under R version 3.6.3"

Tried a few things from the internet. No luck! Any help will be appreciated.
I am using the latest version of R studio, also updated all my packages recently.


text:
Q: Append Values to CSV and retain the old data I have to append the data in CSV, the problem I am facing is intead of appending I am overwriting the data, not able to retain the old data, example :
finalDf = pd.DataFrame(columns=['sourcez', 'tergetz', 'TMP'])
df = pd.DataFrame()
df["sourcez"] = ["str(source_Path)"]
df["tergetz"] = ["str(target_path)"]
df["TMP"] = ["total_matching_points"]
finalDf = finalDf.append(df)
finalDf.to_csv('Testing.csv', index=False)

Now if I add a new value
finalDf = pd.DataFrame(columns=['sourcez', 'tergetz', 'TMP'])
df = pd.DataFrame()
df["sourcez"] = ["str(source_Path)_New"]
df["tergetz"] = ["str(target_path)_New"]
df["TMP"] = ["total_matching_points_New"]
finalDf = finalDf.append(df)
finalDf.to_csv('Testing.csv', index=False)

It is keeping the latest data in csv instead I want both data to be updated in csv. any idea?
I have tried to create a new csv with pandas dataframe and I want to append the values instead overwriting
I have tried:
finalDf = pd.DataFrame(columns=['sourcez', 'tergetz', 'TMP'])
df = pd.DataFrame()
df["sourcez"] = ["str(source_Path)"]
df["tergetz"] = ["str(target_path)"]
df["TMP"] = ["total_matching_points"]
finalDf = finalDf.append(df)
finalDf.to_csv('Testing.csv', index=False, mode='a+')

But the problem is heading is repeating csv:
sourcez,tergetz,TMP
str(source_Path),str(target_path),total_matching_points
sourcez,tergetz,TMP
str(source_Path)_New,str(target_path)_New,total_matching_points_New
How to remove repeated headings sourcez,tergetz,TMP


text:
Q: laravel 5.3 first page not showing I have install apache2 and laravel 5.3 in my system.I have assign port 8081 to
/var/www/html/laravel

folder. Now i am trying to execute
http://localhost:8081/
so its showing me all folders of laravel instead of execute default page of laravel.So is that correct ?
Is there need to do some changes in configuration.php file for that ?

A: The problem may be about the '.htaccess' file. Please create a .htaccess file in public folder, then fill inside like this:
<IfModule mod_rewrite.c>
<IfModule mod_negotiation.c>
    Options -MultiViews
</IfModule>

RewriteEngine On

# Redirect Trailing Slashes If Not A Folder...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)/$ /$1 [L,R=301]

# Handle Front Controller...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [L]

# Handle Authorization Header
RewriteCond %{HTTP:Authorization} .
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
</IfModule>

This works for me.

A: <?php

namespace App\Providers;

use Illuminate\Foundation\Support\Providers\RouteServiceProvider as ServiceProvider;
use Illuminate\Support\Facades\Route;

class RouteServiceProvider extends ServiceProvider
{
    /**
     * This namespace is applied to your controller routes.
     *
     * In addition, it is set as the URL generator's root namespace.
     *
     * @var string
     */
    protected $namespace = 'App\Http\Controllers';

    /**
     * The path to the "home" route for your application.
     *
     * @var string
     */
    public const HOME = '/'; //************** Make change in this line to default redirection in laravel 7 or in any version*****************strong text**

    /**
     * Define your route model bindings, pattern filters, etc.
     *
     * @return void
     */
    public function boot()
    {
        //

        parent::boot();
    }

    /**
     * Define the routes for the application.
     *
     * @return void
     */
    public function map()
    {
        $this->mapApiRoutes();

        $this->mapWebRoutes();

        //
    }

    /**
     * Define the "web" routes for the application.
     *
     * These routes all receive session state, CSRF protection, etc.
     *
     * @return void
     */
    protected function mapWebRoutes()
    {
        Route::middleware('web')
             ->namespace($this->namespace)
             ->group(base_path('routes/web.php'));
    }

    /**
     * Define the "api" routes for the application.
     *
     * These routes are typically stateless.
     *
     * @return void
     */
    protected function mapApiRoutes()
    {
        Route::prefix('api')
             ->middleware('api')
             ->namespace($this->namespace)
             ->group(base_path('routes/api.php'));
    }
}


text:
Q: Advantage of "forcing" the partition I have a topic theimportanttopic with three partitions.
Is an advantage to "forcing" the partition assignment?
For instance, I have three consumers in one group. I want consumer1 to always and only consume from partition-0, consumer2 to always and only consume from partition-1 and consumer3 to always and only consume from partition-2.
One consumer should not touch any other partition at any point of time except the one that was assigned.
A drawback I can think of is that when one of the consumers goes down, no one is consuming from the partition.
Let's suppose a fancy self-healing architecture is in place, can bring back any of those lost consumer back very efficiently.
Would it be an advantage, knowing there won't be any partition reassignment cost to the healthy consumers? The healthy consumers can focus on their own partition, etc.
Are there any other pros and cons?
https://docs.spring.io/spring-kafka/reference/html/#tip-assign-all-parts
https://docs.spring.io/spring-kafka/reference/html/#manual-assignment
It seems the API allow possibility of forcing the partition, I was wondering if this use case was one of the purposes of this design.

A: How do you know what is the "number" of each consumer? Based on your last questions, you've either used kubernetes, or setting concurrency in Spring Kafka. In either case, pods/threads rebalance across partitions of the same executable application... Therefore, you cannot scale them and assign to specific partitions without extra external locking logic.
In my opinion, all executable consumers should be equally be able to handle any partition.
Plus, as you pointed out, there's downtime if one stops.
But, the use case is to exactly match the producer. You've produced data by some custom partitioner logic, therefore, you need exact consumers to read only a subset of that data.
Also, assignment doesn't use consumer groups, so while there would be no rebalancing, it makes it not possible to monitor lag using tools like Burrow or consumer groups cli. Lag would need gathered directly from the consumer metrics themselves.


text:
Q: What other connections are made in the motor housing related to the Centrifugal switch for single phase inductive motors

simulate this circuit – Schematic created using CircuitLab

The schematic is what I observed and imagined from measurement of the six terminal connections. This is a 120V 2HP electric motor with two external capacitors.
The only way I can get it to come to speed it disconnect the 400uf cap and wait for it to slowly get to speed and hear the centrifugal switch open. It then works as expected under load conditions.
1) U1,U2 goes open at speed
2) Reconnect 400uf cap when at speed no effect
3) Disconnect 47uf when at speed draws 2 more amps going from 5 to 7 amps
4) Try to start with 400uf draws 50 amps will not go to speed for centrifugal sw to open
5) starting without 400uf draws 40 amps, takes 5 to 10 seconds to come to speed.
6) Lines V2,Z1 and U2,V1 control direction of motor, if connected V2,U2 and Z1 V1 would reverse direction.
Something appears to prevent normal startup of an inductive motor.  It was made in China and expects 50hz but was told this should not be the problem running on 60hz.

A: I think the drawing is correct except that the terminal numbers may not be correct. There is nothing else related to the centrifugal switch. There is likely some kind of over-current or over-temperature protective device that would disconnect the motor from power if it opens.
Operation at 60 Hz might have some effect on motor performance, but not likely the problem described. It seems likely that the 400 uF capacitor is shorted.


text:
Q: Floyd's Algorithm to detect cycle in linked list proof I've seen several proofs for Floyd's algorithm in several posts inside and outside stack overflow. All of them proves the second part of the algorithm that is, why the method to find the start of the cycle works. But none of the proofs I've seen addresses the first part that is, why the slow pointer and the fast pointer will meet inside the loop. Why wouldn't the slow and the fast pointer go on infinity and never meet at a particular node? All the proofs I've seen so far either do not address this or tells "it's obvious" that the pointers will meet. I'm sorry but I don't get why the points will never go on an infinite loop, to me this feels like the proof of Fermat's last theorem. Can someone prove why it'll always meet for a loop of any length?

A: . Let's take an example of odd length linked list.
If you take a linked list loop as 1->2->3->4->5 and 5 is connected to 1(so that it forms a loop). Now, let's have a pointer from node 1 and iterating alternatively through list. Now visiting is done in the following order: 1st iteration: 1->3->5 Next starts from 2. 2nd iteration: 2->4 Next starts from 1... so on...
So, we can observe that every node is visited. This is true even if you start iteration from 2nd node.
. 2nd example of even length, 1->2->3->4->5->6 & 6->1 (cycle). Starting node as 1; Slow => 1, Fast => 2
Slow : 1 ; Fast : 2
Slow : 2 ; Fast : 4
Slow : 3 ; Fast : 6
Slow : 4 ; Fast : 2
Slow : 5 ; Fast : 4
Slow : 6 ; Fast : 6  => Met!
So, in case of odd length, fast meets slow as fast touches every point and in case of even, slow and fast meet at a point after some iterations.
I didn't find proof like thing, but just posted my observations.
Any suggestions/corrections are appreciated. :)


text:
Q: How to auto-refresh website and update me when its page source changed? I'm looking forward to knowing when there is a new "free room" available on a booking website.
I think I can make a refresh script, but how can I add an "if" condition over a variable in the page source to update me when it changed? Is it even possible?

A: You can try polling for variable change repeatedly using setInterval, see http://www.w3schools.com/jsref/met_win_setinterval.asp
EDIT:
If you want to download the whole page periodically you can do something like this:
setInterval(function() {
    //this function is called repeatedly
    $.ajax("/path/to/your/page")
     .done(function(data, textStatus, jqXHR) {
         // check for changes and reload the page
      });
}, 1000);

A: Thank you all for helping me. I managed to deliver what I wanted using this easy PHP script that downloads and searches for a string on the page's source:
<?php
for ($i = 0; $i < 10000000000; ++$i) {
    $ch = curl_init("www.webpage.com");
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $text = curl_exec($ch);

    $test = strpos($text, "Sorry, no rooms available.");

    if ($test)
    {
        echo "No rooms left.";
    }
    else
    {
        echo 'ROOM AVAILABLE.\n';
        $exec = "terminal-notifier -message \"Room Available\"";
        shell_exec($exec);
    }
    sleep(1);
}
?>

It uses terminal-notifier to send you a notification on OS X.
https://github.com/julienXX/terminal-notifier
To run it, open Terminal: :php script.php


text:
Q: DriverDistractionException when registering multiple clients to the DriverDistractionAPI I'm developing an App for the DispoPilot.guide and the FleetBoard Store and try to access vehicle data. My App consits of a UI with several activities and some services which should handle the vehicle data.
When I register my activity and my service to the driver distraction API I get a DriverDistractionException for the second client I'm registering.
What is wrong with my code?
I'm using
DriverDistractionClient.INSTANCE.connect(this, this);

in both my activity and my service.

A: It is not allowed to connect the client (your application) multiple times to the API.
You can only have one callback for the API. If notification of multiple listeners is desired, this must be handled separately. This can be done by implementing the IDriverDistractionClientCallback interface which then accepts multiple callbacks.


text:
Q: lerna ERR! ZlibError: zlib: invalid block type while publishing packages in lerna I am trying to publish my packages using lerna publish like this:
lerna publish prerelease --preid daily --yes --force-publish --registry <registry_url>

I have plugged this step in my Jenkins build pipeline as follows:
stage("setup enviornment") {
      steps {
            echo "\n[ ENV SET UP ]\n"
                ... Authentication Steps
            }
        }
stage("install packages") {
      steps {
        echo "\n[ INSTALLING PACKAGES ]\n"
        sh "yarn install"
      }
    }
stage("build packages") {
      steps {
        echo "\n[ BUILDING PACKAGES ]\n"
        sh "yarn build"
      }
    }
stage("Publish packages") {
      steps {
        echo "\n[ PUBLISHING PACKAGES ]\n"
        sh "yarn daily-deploy"
      }
    }

The script daily-deploy contains the lerna command as mentioned above.
However, I get the following error in the last step of publishing packages (private repository):
lerna info auto-confirmed
lerna info execute Skipping releases
lerna info git Pushing tags...
lerna info publish Publishing packages to npm...
lerna notice Skipping all user and access validation due to third-party registry
lerna notice Make sure you're authenticated properly ¯\_(ツ)_/¯
lerna WARN ENOLICENSE Package <package name> is missing a license.
lerna WARN ENOLICENSE One way to fix this is to add a LICENSE.md file to the root of this repository.
lerna WARN ENOLICENSE See https://choosealicense.com for additional guidance.
lerna ERR! ZlibError: zlib: invalid block type
lerna ERR!     at Unzip.ZlibBase.(anonymous function).on.er (/apps/agent/workspace/<project>-prerelease/node_modules/minizlib/index.js:73:52)
lerna ERR!     at Unzip.emit (events.js:203:15)
lerna ERR!     at Zlib.zlibOnError [as onerror] (zlib.js:165:8)
lerna ERR!     at processChunkSync (zlib.js:403:12)
lerna ERR!     at Unzip.ZlibBase._processChunk (zlib.js:378:12)
lerna ERR!     at Unzip.write (/apps/agent/workspace/<project>-prerelease/node_modules/minizlib/index.js:140:30)
lerna ERR!     at Object.write (/apps/agent/workspace/<project>-prerelease/node_modules/tar/lib/parse.js:305:58)
lerna ERR!     at Yallist.pipes.forEach.p (/apps/agent/workspace/<project>-prerelease/node_modules/tar/node_modules/minipass/index.js:374:18)
lerna ERR!     at Yallist.forEach (/apps/agent/workspace/<project>-prerelease/node_modules/tar/node_modules/yallist/yallist.js:156:8)
lerna ERR!     at ReadStream.emit (/apps/agent/workspace/<project>-prerelease/node_modules/tar/node_modules/minipass/index.js:373:20)
lerna ERR!     at ReadStream.emit (/apps/agent/workspace/<project>-prerelease/node_modules/tar/node_modules/fs-minipass/index.js:154:22)
lerna ERR!     at ReadStream.write (/apps/agent/workspace/<project>-prerelease/node_modules/tar/node_modules/minipass/index.js:163:17)
lerna ERR!     at ReadStream.[_handleChunk] (/apps/agent/workspace/<project>-prerelease/node_modules/tar/node_modules/fs-minipass/index.js:131:19)
lerna ERR!     at ReadStream.[_onread] (/apps/agent/workspace/<project>-prerelease/node_modules/tar/node_modules/fs-minipass/index.js:109:32)
lerna ERR!     at fs.read (/apps/agent/workspace/<project>-prerelease/node_modules/tar/node_modules/fs-minipass/index.js:101:22)
lerna ERR! lerna zlib: invalid block type
error Command failed with exit code 1.

I have all private packages except for one.
My lerna.json is as below:
{
  "packages": [
    "packages/*"
  ],
  "version": "independent",
  "command": {
    "publish": {
      "registry": <repository_url>
    }
  },
  "npmClient": "yarn",
  "useWorkspaces": true
}

Can someone help me with this issue?


text:
Q: Creating random matrix with rules in R I need to create a random matrix from the values below which will contain two basic rules:
1) Each column must contains only one value where remaining will be zeros and
2) each row must be occupied by only one value.
# create dummy matrix
B = matrix(
  c(83, 101, 75, 182, 150, 199,
    218,  80,   90, 138,    249,    299,
    113,  171,  146,    226,    40.4,   78,
    314,    116,    186,    33.2,   345,    196,
    327,    189,    199,    109,    359,    281,
    430,    292,    302,    232,    461,    404
  ), ncol=6, nrow=6)
# Transpose
t(B)
# names for cols and rows
colnames(B) <- c("x1",  "x2",   "x3",   "x4",   "x5",   "x6")
rownames(B) <- c("y1",  "y2",  "y3",    "y4",   "y5",   "y6")

Every possible combination of that arrangement is the output
    x1  x2  x3  x4  x5  x6
y1  83  0   0   0   0   0
y2  0   0   90  0   0   0
y3  0   171 0   0   0   0
y4  0   0   0   0   345 0
y5  0   0   0   109 0   0
y6  0   0   0   0   0   404

and e.g.
    x1  x2  x3  x4  x5  x6
y1  0   101 0   0   0   0
y2  218 0   0   0   0   0
y3  0   0   146 0   0   0
y4  0   0   0   0   345 0
y5  0   0   0   109 0   0
y6  0   0   0   0   0   404

and so forth...
Please, is there any elegant solution, how to do that. Any advice or help is very appreciated. Thanks a lot in forward.

A: Create a diagonal matrix and then permute rows or columns. In case of single random permutation sample(n) would suffice, for all of them - allPerms.
n <- 3  # dimension
mat <- diag(1:n)

permute::allPerms(n) -> perms
mat[perms[k, ], ]   # k-th permutation

Downside is that all permutations are generated and saved.


text:
Q: Does GKE use an overlay network? GKE uses the kubenet network plugin for setting up container interfaces and configures routes in the VPC so that containers can reach eachother on different hosts.
Wikipedia defines an overlay as a computer network that is built on top of another network.
Should GKE's network model be considered an overlay network? It is built on top of another network in the sense that it relies on the connectivity between the nodes in the cluster to function properly, but the Pod IPs are natively routable within the VPC as the routes inform the network which node to go to to find a particular Pod.

A: VPC-native and non VPC native GKE clusters uses GCP virtual networking. It is not strictly an overlay network by definition. An overlay network would be one that's isolated to just the GKE cluster.
VPC-native clusters work like this:
Each node VM is given a primary internal address and two alias IP ranges.  One alias IP range is for pods and the other is for services.
The GCP subnet used by the cluster must have at least two secondary IP ranges (one for the pod alias IP range on the node VMs and the other for the services alias IP range on the node VMs).
Non-VPC-native clusters:
GCP creates custom static routes whose destinations match pod IP space and services IP space.  The next hops of these routes are node VMs by name, so there is instance based routing that happens as a "next step" within each VM.
I could see where some might consider this to be an overlay network. I don't believe this is the best definition because the pod and service IPs are addressable from other VMs, outside of GKE cluster, in the network.
For a deeper dive  on GCP's network infrastructure, GCP's network virtualization whitepaper can be found here.


text:
Q: find string inside a gzipped file in a folder My current problem is that I have around 10 folders, which contain gzipped files (around on an average 5 each). This makes it 50 files to open and look at.
Is there a simpler method to find out if a gzipped file inside a folder has a particular pattern or not?
zcat ABC/myzippedfile1.txt.gz | grep "pattern match"
zcat ABC/myzippedfile2.txt.gz | grep "pattern match"

Instead of writing a script, can I do the same in a single line, for all the folders and sub folders?
for f in `ls *.gz`; do echo $f; zcat $f | grep <pattern>; done;

A: use the find command
find . -name "*.gz" -exec zcat "{}" + |grep "test"

or try using the recursive option (-r) of zcat

A: Coming in a bit late on this, had a similar problem and was able to resolve using;
zcat -r /some/dir/here | grep "blah"

As detailed here;
http://manpages.ubuntu.com/manpages/quantal/man1/gzip.1.html
However, this does not show the original file that the result matched from, instead showing "(standard input)" as it's coming in from a pipe. zcat does not seem to support outputting a name either.
In terms of performance, this is what we got;
$ alias dropcache="sync && echo 3 > /proc/sys/vm/drop_caches"

$ find 09/01 | wc -l
4208

$ du -chs 09/01
24M

$ dropcache; time zcat -r 09/01 > /dev/null
real    0m3.561s

$ dropcache; time find 09/01 -iname '*.txt.gz' -exec zcat '{}' \; > /dev/null
0m38.041s

As you can see, using the find|zcat method is significantly slower than using zcat -r when dealing with even a small volume of files. I was also unable to make zcat output the file name (using -v will apparently output the filename, but not on every single line). It would appear that there isn't currently a tool that will provide both speed and name consistency with grep (i.e. the -H option).
If you need to identify the name of the file that the result belongs to, then you'll need to either write your own tool (could be done in 50 lines of Python code) or use the slower method. If you do not need to identify the name, then use zcat -r.
Hope this helps

A: zgrep will look in gzipped files, has a -R recursive option, and a -H show me the filename option:
zgrep -R --include=*.gz -H "pattern match" .

OS specific commands as not all arguments work across the board:
Mac 10.5+: zgrep -R --include=\*.gz -H "pattern match" .
Ubuntu 16+: zgrep -i -H "pattern match" *.gz

A: You don't need zcat here because there is zgrep and zegrep.
If you want to run a command over a directory hierarchy, you use find:
find . -name "*.gz" -exec zgrep ⟨pattern⟩ \{\} \;

And also "ls *.gz" is useless in for and you should just use "*.gz" in the future.

A: find  . -name "*.gz"|xargs zcat | grep "pattern" should do.

A: zgrep "string" ./*/*
You can use above command to search for string in .gz files of dir directory where dir has following sub-directories structure:
/dir
    /childDir1
              /file1.gz
              /file2.gz
    /childDir2
              /file3.gz
              /file4.gz
    /childDir3
              /file5.gz
              /file6.gz

A: how zgrep don't support -R
I think the solution of "Nietzche-jou" could be a better answer, but I would add the option -H to show the file name something like this
find . -name "*.gz" -exec zgrep -H 'PATTERN' \{\} \;

A: You can use this command -
zgrep "foo" $(find . -name "*.gz")


text:
Q: Radicals of co-quasitriangular map Let $B=\mathcal{O}_R\left(GL(n)\right)$ be a localization of the algebra $A(R)$ of functions on the quantum formal group corresponding to the matrix $R$ ["Quantization of Lie groups and Lie algebras", Faddev, Reshetikhin, Takhtajan] at $\mathrm{det}$ (quantum determinant), where $\mathrm{det}$ is a central grouplike element of degree $n$, which is not a zero divisor and $\mathrm{det}\ a=f(a)\mathrm{det}$ for some $f\in\mathrm{Aut}(A(R))$. We assume that $A(R)$ is defined with respect to $n\times n$ matrix coalgebra $C$ with standard coproduct $\Delta\left(t_{\ j}^{i}\right)=t_{\ k}^{i}\otimes t^{k}_{\ j}$, where $\left(t^{i}_{\ j}\right)$ forms basis of $C$ and there exist a bilinear $r:C\otimes C\rightarrow k$ s.th. $r\left(t^{i}_{\ j},t^{k}_{\ l}\right)=R^{i \ k}_{\ j \ l}$, where $R=\left(R^{i \ k}_{\ j \ l}\right)$ is a bi-invertible solution of Yang-Baxter equation on $k^n\otimes k^n$. One can define antipode map $S$ and co-quasitriangular structure $\textbf{r}$ on $B$.
In one article I found a statement that if $\mathrm{det}-1$ belongs to the left and right radicals of $\textbf{r}$ then we can define some additional structures.
My question is : What is a radical of map which gives us a co-quasitriangular structure on $B$ ? I can't find this definition.

A: The co-quasitriangular structure $r$ is a bilinear map over the ground field. Hence one can define right and left radicals as in linear algebra.
Note that the quantum determinant is a sum, e.g. in an example presented in the paper by Faddev-Rheshitikhin-Takhtajan,
$
 \operatorname{det}_q T= \sum_{s∈S_n} (-q)^{l(s)} t^1_{s_1}\ldots t^n_{s_n}
$.
For this reason one needs to extend the map $r$ to $A(R)\otimes A(R)$ first. This can be done using the axioms of a dual $r$-matrix. This way one obtains a dual $r$-matrix on $A(R)\otimes A(R)$ and the left and right radical are defined. The condition then becomes that $r(\operatorname{det}_q-1\otimes a)=0$ for any $a\in A(R)$. If this holds, i.e. $\operatorname{det}-1$ is in the radical, then the map $r$ descents to a dual $r$-matrix on the quotient $A(R)/(\operatorname{det}-1)$ which can be viewed as functions $\mathcal{O}_R(SL_n)$ on quantum $SL_n$.


text:
Q: Why does the change in length depend on the initial length of a rod? When a rod of some length is heated then it undergoes linear expansion (also areal and volumetric) but I don't understand Why does the amount of expansion depend on the initial length of the rod ?
If we have two rods one of half the length of the other, both of same material and at same initial temperature then if both are heated to same final temperature then the one with greater length undergoes greater change in length. This is what confused me.
Shouldn't the energy per unit length be same in both the rods and so each bonds should get the same energy in both the rods and so both should expand the same amount?

A: To address the energy-per-unit-length qualm, let's assume that it is equal in both rods. We can also assume the rods have the same number of bonds-per-length, and each bond receives the same amount of energy.
One rod is longer, so it takes more energy to raise its temperature to the same temperature, because it has more mass.
Now, each bond has been given the same amount of energy and will expand by a tiny amount $\Delta{}x$. But the longer rod has more bonds, and each bond is expanding by a tiny amount. The smaller rod expands by $\frac{L}{b}\Delta{}x$ and the larger rod expands by $\frac{2L}{b}\Delta{}x$ where $b$ is the length for a single bond, so that $L/b$ is the total number of bonds along the rod's length.


text:
Q: How to find singular plural and different wording cases in SOLR I'm new to SOLR, but I want to find out how to perform a singular, plural and different wording search in SOLR. Example what I have in my mind.
e.g. this is my data set in SOLR:
[
 { url: '/my-awesome-url/' },
 { url: '/my-awesome-urls/' },
 { url: '/my-url-awesome/' },
 { url: '/url-awesome-my/' },
 { url: '/hi/' },
 { url: '/foo-bar'}
]

This is my search term my awesome url. Is it possible to write a query that would find:
[
  { url: '/my-awesome-url/' },
  { url: '/my-awesome-urls/' },
  { url: '/my-url-awesome/' },
  { url: '/url-awesome-my/' }
]

If it's possible how to do this? What do I need to know to be able to write this type of query?

A: Yes its possible. You can apply the fieldtype to your field url.
The fieldtype will consist of tokenizers and filters.
Tokenisers : The job of a tokenizer is to break up a stream of text into tokens, where each token is (usually) a sub-sequence of the characters in the text.  Tokenizers read from a character stream (a Reader) and produce a sequence of Token objects (a TokenStream).
Filters : Unlike tokenizers, a filter's input is another TokenStream. The job of a filter is usually easier than that of a tokenizer since in most cases a filter looks at each token in the stream sequentially and decides whether to pass it along, replace it or discard it.
In your case you can apply standard tokenizer.
All the Tokenizers
Filters like lowercase filters, stemmer filter etc.
All the Filters
You can try the below field type for your field.
<fieldType name="textUrl" class="solr.TextField" positionIncrementGap="100">
      <analyzer type="index">
        <tokenizer class="solr.StandardTokenizerFactory"/>
        <filter class="solr.LowerCaseFilterFactory"/>
        <filter class="solr.PorterStemFilterFactory"/>
      </analyzer>
      <analyzer type="query">
        <tokenizer class="solr.StandardTokenizerFactory"/>
        <filter class="solr.LowerCaseFilterFactory"/>
        <filter class="solr.PorterStemFilterFactory"/>
      </analyzer>
    </fieldType>


text:
Q: How to use an .aspx form for a workflow step in SharePoint 2010 I'd like to implement email templates in SharePoint 2010 and found this great video tutorial on how to implement it using SharePoint Designer:
http://www.youtube.com/watch?v=B6ifiMNt_cg
Basically, I need exactly what is shown in that video, so I'm trying to re-do the steps in the video, which is based on SharePoint 2007, into our SharePoint 2010 environment.
The part where I get stuck is the "send email" workflow form. In the video, the author is editing the send email workflow form as an .ASPX. As such, he is able to drag a list (the email templates list) on to it and make a webpart connection.
I noticed though that in SharePoint2010, following these exact steps leads to the creation of an Infopath form for the "send email" workflow step. And on this infopath form, I can't drag the email templates list or make a webpart connection.
So my question is...in SharePoint 2010, can I use an .aspx instead of the default infopath form for a workflow step? I can't use Visual Studio or custom coding, I'm limited to basic configuration and SharePoint designer.

A: You can use either an InfoPath form or an .aspx page as the form for your workflow.
I am not sure what you mean by using an aspx as a workflow step though.
For making web part connections in SharePoint designer, check out this video http://office.microsoft.com/en-us/sharepoint-designer-help/video-create-web-part-connections-using-sharepoint-designer-2010-VA102191896.aspx
I was unable to find a quick tutorial on email templates in SharePoint designer for 2010 and I am only familiar with how to do something like that in code, not the designer.


text:
Q: Select rows from one table where certain field is equal to a field in a row from another table, with Python and SQLite3 I have a small database which is legacy from an almost defunct project. This database has a "Patients" table with individual personal data and an unique "Id" field, and an "Exams" table with some fields for each exam, one of these fields being "Patient_Id".
What I want is, for a given patient (row from "Pacientes" table) the exams (rows) from "Exames" table whose "Patient_Id" matches that of the given patient.
I am very beginner with SQL, so if the question is very naive, I apologize.
My working code is the following, but I am using a for loop while I would much rather have a SQL query (which is the very point of using databases, I think...):
#!/usr/bin/env python
# coding: utf-8

import os, sqlite3

conn = sqlite3.connect('BDdata.db3')
conn.row_factory = sqlite3.Row
c = conn.cursor()

c.execute('SELECT * FROM Exames')
exams = c.fetchall()

c.execute('SELECT * FROM Pacientes')
for row in c:
    Nome = row['nome']
    ID = row['Id']
    for exam in exams:          # I would like to replace this loop
        if exam['Id_Paciente'] == ID:       # with a SQL query meaning
            print exam['File']

============================
An answer to a similar question seems to be what I want, but I have no idea how to do this in Python with sqlite3 module, much less what in this expression is essential and what is incidental, or what is the syntax structure:
Selecting rows from a table by One a field from other table
SELECT i.prof_image
FROM profile_images i
WHERE cat_id = (select max(cat_id) from images_cat)

A: I think the following should do what you want:
...
c = conn.cursor()

c.execute('SELECT * FROM Pacientes')
for row in c.fetchall():
    Nome = row['nome']
    ID = row['Id']
    c.execute('SELECT File FROM Exames WHERE Id_Paciente=?', [ID])
    for exam in c:
        print exam['File']


text:
Q: MemoryError of running Randomforest in scikit-learn I am following the Python example given in For Beginners - Bag of Words. However, the following code segment gives the error message like MemoryError. What might cause this error
forest = forest.fit(train_data_features, train["sentiment"])

Traceback (most recent call last):
File "C:/Users/PycharmProjects/Project3/demo4.py", line 60, in <module>
   forest = forest.fit(train_data_features, train["sentiment"])
File "C:\Users\AppData\Roaming\Python\Python27\site-
   packages\sklearn\ensemble\forest.py", line 195, in fit
X = check_array(X, dtype=DTYPE, accept_sparse="csc")
File "C:\Users\AppData\Roaming\Python\Python27\site-
   packages\sklearn\utils\validation.py", line 341, in check_array
   array = np.array(array, dtype=dtype, order=order, copy=copy)
MemoryError

A: MemoryError, as the name says, means you're running out of free memory.
If you're following the example code from here, then there are a few things that could help you:

*

*delte variables using del when you don't need them anymore
(for example, clean_train_reviews is not needed after line 62)

*After line 42, only train["sentiment"] is needed, the rest of train could be discarded to free memory

*don't read both the training and the test sets at the beginning. The test set is only needed after building the forest, and at that point nothing else related to the train set is needed anymore.

*The whole training part could be wrapped in a function returning the forest, that would take care of all references which are no longer needed after that.

A: In the specified example the bag of words contains 5000 features; this requires significant memory. So, one solution is to reduce the number of features, but doing this may affect the model performance.
Another solution is to switch from 32-bit Python to 64-bit.


text:
Q: visifire Custom Axis Labels Not Showing I need to Export my Chart as an image without showing it first in WPF. So i built the Chart in Code:
    public void CreateHistogram(CalcRepository cr, int i)
    {
        Chart chart = new Chart();

        chart.Width = 300;
        chart.Height = 200;
        chart.ScrollingEnabled = false;
        chart.AnimationEnabled = false;
        chart.TrendLines.Add(new TrendLine{Value = cr.Mean,Orientation = System.Windows.Controls.Orientation.Vertical});
        chart.TrendLines.Add(new TrendLine{Value = cr.ChartTrippleNegativeStdDeviation,Orientation = System.Windows.Controls.Orientation.Vertical,LineStyle = LineStyles.Dashed});chart.TrendLines.Add(new TrendLine{Value = cr.ChartTripplePositiveStdDeviation,Orientation = System.Windows.Controls.Orientation.Vertical,LineStyle = LineStyles.Dashed});
        chart.TrendLines.Add(new TrendLine{Value = cr.UpperSpecificationLimit,Orientation = System.Windows.Controls.Orientation.Vertical});
        chart.TrendLines.Add(new TrendLine{Value = cr.LowerSpecificationLimit,Orientation = System.Windows.Controls.Orientation.Vertical});
        chart.TrendLines[0].SetValue(Canvas.ZIndexProperty, 40);
        chart.TrendLines[1].SetValue(Canvas.ZIndexProperty, 40);
        chart.TrendLines[2].SetValue(Canvas.ZIndexProperty, 40);
        chart.TrendLines[3].SetValue(Canvas.ZIndexProperty, 40);
        chart.TrendLines[4].SetValue(Canvas.ZIndexProperty, 40);

        chart.DataPointWidth = cr.DataPointWidth;
        chart.Visibility = Visibility.Visible;
        Axis x = new Axis();
        x.AxisMaximum = cr.VisUpperBound;
        x.AxisMinimum = cr.VisLowerBound;
        x.AxisType = AxisTypes.Primary;

        CustomAxisLabels cal = new CustomAxisLabels();
        cal.Labels.Add(new CustomAxisLabel {From = cr.Mean, To = cr.Mean, Text = "Mean"});
        cal.Labels.Add(new CustomAxisLabel {From = cr.ChartTrippleNegativeStdDeviation,To = cr.ChartTrippleNegativeStdDeviation,Text = "LCL"});
        cal.Labels.Add(new CustomAxisLabel{From = cr.ChartTripplePositiveStdDeviation,To = cr.ChartTripplePositiveStdDeviation,Text= "UCL"});
        cal.Labels.Add(new CustomAxisLabel {From = cr.UpperSpecificationLimit, To = cr.UpperSpecificationLimit , Text = "USL"});
        cal.Labels.Add(new CustomAxisLabel {From = cr.LowerSpecificationLimit, To = cr.LowerSpecificationLimit, Text = "LSL"});

        cal.FontSize = 10;
        cal.Angle = 0;
        cal.FontColor = new SolidColorBrush(Colors.Black);
        cal.Enabled = true;

        x.CustomAxisLabels.Add(cal);
        chart.AxesX.Add(x);

        var ds = new DataSeries();
        var dpc = new DataPointCollection(cr.HistogramValues);
        ds.DataPoints = dpc;

        chart.Series.Add(ds);

        ds.ZIndex = 1;
        ds.Bevel = false;
        ds.ShadowEnabled = false;
        ds.LightingEnabled = false;
        ds.Color = new SolidColorBrush(Colors.SteelBlue);

        chart.BeginInit();
        chart.EndInit();
        chart.Measure(new Size(300, 200));
        chart.Arrange(new Rect(0, 0, 300, 200));
        chart.UpdateLayout();

        ExportToPng(new Uri("C:\\" + i + ".png"), chart);
    }

everything works fine, except the custom Axis Labels are missing. This is how the Output looks like:

As you can see, there is even space allocated for the CustomAxis Labels but they are not shown. Anyone got an idea?
Hint: AnimationEnabled has to be set false otherwise the series is not rendered yet when the image is taken - took me a long time to figure that out.

A: I found already a solution:
When exceeding the bounds, the values are set to Double.NaN. I found out, that the creation of all Labels fails, if any value in the Collections Double.Nan or Double.Infinity - Seems lika a bug in visifire.
I solved it by adding each Label in its seperate Collection.


text:
Q: Binding device to a driver module I'm trying to understand better the process of binding a device to its driver.
I have an USB tool (In System Programmer for Arduino) whose Id (Product and Vendor) are known. The driver, cdc_acm.ko, doesn't recognize it (of course, it's not in its internal device list!). So... I have loaded the module
sudo modprobe cdc_acm
lsmod | grep cdc
$>cdc_acm

$>dmesg
...
[41244.510906] usbcore: registered new interface driver cdc_acm
[41244.510915] cdc_acm: USB Abstract Control Model driver for USB modems and ISDN adapters

Perfect. Then I insert the device and dmesg output is the following:
...
[41447.794431] usb 2-1.2: new full-speed USB device number 17 using ehci-pci
[41447.887680] usb 2-1.2: New USB device found, idVendor=03eb, idProduct=2ff7
[41447.887690] usb 2-1.2: New USB device strings: Mfr=0, Product=1, SerialNumber=0
[41447.887695] usb 2-1.2: Product: Arduino USB-Serial DFU

That seems to me that usb driver has been dealing with. Let me check accordingly to the folllowing http://lwn.net/Articles/143397/
$>ls -la /sys/bus/usb/drivers/usb/usb2/2-1/2-1.2/2-1.2\:1.0/
total 0
drwxr-xr-x 3 root root    0 gen 20 19:29 .
drwxr-xr-x 5 root root    0 gen 20 12:51 ..
-r--r--r-- 1 root root 4096 gen 20 12:58 bAlternateSetting
-r--r--r-- 1 root root 4096 gen 20 12:51 bInterfaceClass
-r--r--r-- 1 root root 4096 gen 20 12:51 bInterfaceNumber
-r--r--r-- 1 root root 4096 gen 20 12:58 bInterfaceProtocol
-r--r--r-- 1 root root 4096 gen 20 12:58 bInterfaceSubClass
-r--r--r-- 1 root root 4096 gen 20 12:58 bNumEndpoints
-r--r--r-- 1 root root 4096 gen 20 12:58 modalias
drwxr-xr-x 2 root root    0 gen 20 12:58 power
lrwxrwxrwx 1 root root    0 gen 20 12:58 subsystem -> ../../../../../../../bus/usb
-r--r--r-- 1 root root 4096 gen 20 12:58 supports_autosuspend
-rw-r--r-- 1 root root 4096 gen 20 12:51 uevent

module link is not existing, therefore it seems that the device is not linked to usb module driver. Nice to note that the content of modalias file is what I was expecting:
 usb:v03EBp2FF7d0000dc00dsc00dp00icFEisc01ip02in00

Now I try to link the device to the module cdc_acm with the following command:
$>sudo echo -n "2-1.2:1.0" > sudo /sys/bus/usb/drivers/cdc_acm/bind

dmesg output shows nothing specific to the command just issued.
What am I doing wrong here? I would expect at least some debug output, if I issued an offending request I would expect at least a kernel message back... At least having some system feedback would help me in understanding what the problem is...
Anybody can help me? Thanks.
PS. I'm using Ubuntu 14.10 64bit on Intel core i3 ASUS laptop F552C.

A: This is very popular situation, the use of shell redirection with sudo to write to root owned file. You can run it as:
sudo sh -c 'echo -n "2-1.2:1.0" > /sys/bus/usb/drivers/cdc_acm/bind'

Which run shell as root and use redirect inside it. There are many other ways, see When using sudo with redirection, I get 'permission denied'


text:
Q: TensorFlow : Tried to convert 'input' to a tensor and failed. Error: None values not supported I am trying to make my first Convolutional Neural Network using Tensorflow and python(3.6). Here is the relevant part of my code :
def init_weights(shape):
  init_random_dist = tf.truncated_normal(shape , stddev = 0.1)
  return tf.Variable(init_random_dist)
def init_bias(shape):
  init_bias_vals = tf.constant(0.1 , shape = shape)
  return tf.Variable(init_bias_vals)
def conv2d(x,W):
  return tf.nn.conv2d(x , W, strides = [1,1,1,1] , padding = 'SAME')
def max_pool_2by2(x):
  tf.nn.max_pool(x , ksize = [1,2,2,1] , strides = [ 1,2,2,1 ]  , padding ='SAME')
def convolutional_layer(input_x,shape):
  W = init_weights(shape)
  b = init_bias([shape[3]])
  return tf.nn.relu(conv2d(input_x,W)+b)
x = tf.placeholder(tf.float32 , shape = [ None , 784 ])
y_true = tf.placeholder(tf.float32 , shape = [ None , 10 ])
x_image = tf.reshape(x , [-1 , 28 , 28 , 1])
convo_1 = convolutional_layer(x_image , shape = [5,5,1,32])#height-width-inputchannels-no.ofkernels
convo_1_pooling = max_pool_2by2(convo_1)

convo_2 = convolutional_layer(convo_1_pooling,shape = [5,5,32,64])
convo_2_pooling = max_pool_2by2(convo_2)

I am using the MNIST dataset for this network hence the 784 and 28x28. This is the error I am getting :
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
/usr/local/lib/python3.6/dist-packages/tensorflow/python/framework/op_def_library.py in _apply_op_helper(self, op_type_name, name, **keywords)
    509                 as_ref=input_arg.is_ref,
--> 510                 preferred_dtype=default_dtype)
    511           except TypeError as err:

/usr/local/lib/python3.6/dist-packages/tensorflow/python/framework/ops.py in internal_convert_to_tensor(value, dtype, name, as_ref, preferred_dtype, ctx)
   1035     if ret is None:
-> 1036       ret = conversion_func(value, dtype=dtype, name=name, as_ref=as_ref)
   1037

/usr/local/lib/python3.6/dist-packages/tensorflow/python/framework/constant_op.py in _constant_tensor_conversion_function(v, dtype, name, as_ref)
    234   _ = as_ref
--> 235   return constant(v, dtype=dtype, name=name)
    236

/usr/local/lib/python3.6/dist-packages/tensorflow/python/framework/constant_op.py in constant(value, dtype, shape, name, verify_shape)
    213       tensor_util.make_tensor_proto(
--> 214           value, dtype=dtype, shape=shape, verify_shape=verify_shape))
    215   dtype_value = attr_value_pb2.AttrValue(type=tensor_value.tensor.dtype)

/usr/local/lib/python3.6/dist-packages/tensorflow/python/framework/tensor_util.py in make_tensor_proto(values, dtype, shape, verify_shape)
    420     if values is None:
--> 421       raise ValueError("None values not supported.")
    422     # if dtype is provided, forces numpy array to be the type

ValueError: None values not supported.

During handling of the above exception, another exception occurred:

ValueError                                Traceback (most recent call last)
/usr/local/lib/python3.6/dist-packages/tensorflow/python/framework/op_def_library.py in _apply_op_helper(self, op_type_name, name, **keywords)
    523               observed = ops.internal_convert_to_tensor(
--> 524                   values, as_ref=input_arg.is_ref).dtype.name
    525             except ValueError as err:

/usr/local/lib/python3.6/dist-packages/tensorflow/python/framework/ops.py in internal_convert_to_tensor(value, dtype, name, as_ref, preferred_dtype, ctx)
   1035     if ret is None:
-> 1036       ret = conversion_func(value, dtype=dtype, name=name, as_ref=as_ref)
   1037

/usr/local/lib/python3.6/dist-packages/tensorflow/python/framework/constant_op.py in _constant_tensor_conversion_function(v, dtype, name, as_ref)
    234   _ = as_ref
--> 235   return constant(v, dtype=dtype, name=name)
    236

/usr/local/lib/python3.6/dist-packages/tensorflow/python/framework/constant_op.py in constant(value, dtype, shape, name, verify_shape)
    213       tensor_util.make_tensor_proto(
--> 214           value, dtype=dtype, shape=shape, verify_shape=verify_shape))
    215   dtype_value = attr_value_pb2.AttrValue(type=tensor_value.tensor.dtype)

/usr/local/lib/python3.6/dist-packages/tensorflow/python/framework/tensor_util.py in make_tensor_proto(values, dtype, shape, verify_shape)
    420     if values is None:
--> 421       raise ValueError("None values not supported.")
    422     # if dtype is provided, forces numpy array to be the type

ValueError: None values not supported.

During handling of the above exception, another exception occurred:

ValueError                                Traceback (most recent call last)
<ipython-input-17-d2abcb4a99e1> in <module>()
      3 convo_1_pooling = max_pool_2by2(convo_1)
      4
----> 5 convo_2 = convolutional_layer(convo_1_pooling,shape = [5,5,32,64])
      6 convo_2_pooling = max_pool_2by2(convo_2)

<ipython-input-14-aed4eef361c3> in convolutional_layer(input_x, shape)
      2   W = init_weights(shape)
      3   b = init_bias([shape[3]])
----> 4   return tf.nn.relu(conv2d(input_x,W)+b)

<ipython-input-6-52ed03971cc3> in conv2d(x, W)
      1 def conv2d(x,W):
----> 2   return tf.nn.conv2d(x , W, strides = [1,1,1,1] , padding = 'SAME')

/usr/local/lib/python3.6/dist-packages/tensorflow/python/ops/gen_nn_ops.py in conv2d(input, filter, strides, padding, use_cudnn_on_gpu, data_format, dilations, name)
    629         "Conv2D", input=input, filter=filter, strides=strides,
    630         padding=padding, use_cudnn_on_gpu=use_cudnn_on_gpu,
--> 631         data_format=data_format, dilations=dilations, name=name)
    632     _result = _op.outputs[:]
    633     _inputs_flat = _op.inputs

/usr/local/lib/python3.6/dist-packages/tensorflow/python/framework/op_def_library.py in _apply_op_helper(self, op_type_name, name, **keywords)
    526               raise ValueError(
    527                   "Tried to convert '%s' to a tensor and failed. Error: %s" %
--> 528                   (input_name, err))
    529             prefix = ("Input '%s' of '%s' Op has type %s that does not match" %
    530                       (input_name, op_type_name, observed))

ValueError: Tried to convert 'input' to a tensor and failed. Error: None values not supported.

Please ask for any more details that might be required. I am a newbie to TensorFlow.

A: Function max_pool_2by2 does not return any value so convo_1_pooling is None then.


text:
Q: How to split a string by character sets that are different in python I want to split an string I have by characters that are different than the others into a list. for example, if I have string ccaaawq, I want my program to give me ['cc', 'aaa', 'w', 'q']. Since there is no single differentiator between each split, I'm wondering what is the best approach to solving this problem.
thanks in advance for your answers

A: You can use itertools.groupby:
from itertools import groupby

s = "ccaaawq"

out = ["".join(g) for _, g in groupby(s)]
print(out)

Prints:
['cc', 'aaa', 'w', 'q']

A: Here is a regex find all approach:
inp = "ccaaawq"
output = [x[0] for x in re.findall(r'((.)\2*)', inp)]
print(output)  # ['cc', 'aaa', 'w', 'q']

The above works by matching any one character followed by that same character zero or more times.  These matches are then stored in the first capture group, which we extract from the 2D list output.


text:
Q: Matplotlib giving error "OverflowError: In draw_path: Exceeded cell block limit" I'm trying to render an image using matplotlib with 100000000 data points and it produces the error OverflowError: In draw_path: Exceeded cell block limit. Is there a limit in the amount of data points it can draw?

A: The problem is a hardcoded limit in the number of points in the backend Agg.
Try using:
import matplotlib as mpl
mpl.rcParams['agg.path.chunksize'] = 10000

or other large value.
You can find the issue and the solution proposed here: https://github.com/matplotlib/matplotlib/issues/5907

A: Maybe the problem is because matplotlib uses default inline plotting, which means it connects the points. There's some limit to the points for that. But if you remove inline plotting, it might work. Try
import matplotlib.pyplot as plt
plt.plot(x, y, 'ro', linestyle="None")

The 'ro' is for it to show red dots.

A: The problem is a hardcoded limit in the number of points in the backend Agg.
It can be solved by mpl.rcParams['agg.path.chunksize'] = 10000.
You can find the issue and the solution proposed here: https://github.com/matplotlib/matplotlib/issues/5907


text:
Q: OnClickListener not fired on ConstraintLayout On my android app project i have to make a button with a ProgressBar on background and two TextView.
I make a first attempt like this:
    <android.support.constraint.ConstraintLayout
        android:id="@+id/keyboard_touch_1"
        android:layout_width="60dp"
        android:layout_height="85dp"
        android:layout_marginBottom="150dp"
        android:layout_marginStart="10dp"
        android:focusable="true"
        android:clickable="true"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintStart_toStartOf="parent">

        <ProgressBar
            android:id="@+id/keyboard_touch_1_progress_bar"
            style="@android:style/Widget.ProgressBar.Horizontal"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:indeterminate="false"
            android:max="100"
            android:progress="50"
            android:progressDrawable="@drawable/button_progress_bar_default"
            android:clickable="false"
            android:focusable="false" />

        <TextView
            android:id="@+id/keyboard_touch_1_score"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentStart="true"
            android:layout_marginEnd="8dp"
            android:layout_marginTop="8dp"
            android:text="2"
            android:textColor="@color/colorAccent"
            android:textSize="11dp"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintTop_toTopOf="parent"
            tools:text="3"
            android:clickable="false"
            android:focusable="false" />

        <TextView
            android:id="@+id/keyboard_touch_1_letter"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentStart="true"
            android:layout_marginTop="13dp"
            android:text="A"
            android:textColor="@color/colorAccent"
            android:textSize="45dp"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent"
            android:clickable="false"
            android:focusable="false" />

    </android.support.constraint.ConstraintLayout>

It looks good but when i attempt to add an OnClickListener it doesn't work correctly.
keyboard_touch_1.setOnClickListener {
    Toast.makeText(this, "IT WORKS !!!", Toast.LENGTH_SHORT).show()
}

The OnClickListener is not fired and i have no idea of why. It's probably very simple but i doesn't understand why.
Thanks in advance.

A: Remove
android:clickable="false"

From Docs

Defines whether this view reacts to click events

and move keyboard_touch_1.setOnClickListener {...} at the end of onResume because
DataBindingUtil.setContentView  will reset the previously set layout (setContentView) therefore you have a new layout with new views.
Note :  you are using data-binding along with normal initialization setContentView(R.layout.activity_game) technique so the optimal way would be to use
Event Handling via data binding

A: As I cannot comment due to my low rep I will have to post an answer.
Based on the code you have provided via your GitHub link you are actually trying to set the content view twice.
Firstly you are calling setContentView(R.layout.activity_game) within your onCreate() method and then DataBindingUtil.setContentView(this, R.layout.activity_game) within your onResume() method.
Please try deleting setContentView(R.layout.activity_game) and then move your data binding setup code to your onCreate method(). You can then access your constraint layout view via your "binding" object as a property.
For example:
override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        viewModel = GameViewModel()
        val binding: ActivityGameBinding = DataBindingUtil.setContentView(this, R.layout.activity_game)
        binding.viewModel = viewModel

        binding.keyboardTouch1.setOnClickListener {
            Toast.makeText(this, "IT WORKS !!!", Toast.LENGTH_SHORT).show()
        }
    }

    override fun onResume() {
        super.onResume()
        viewModel.startUpdate()
    }

    override fun onPause() {
        super.onPause()
        viewModel.stopUpdate()
    }

A: maybe your layout is include label with id, this id override origin id.


text:
Q: jquery on event not working on phonegap but chrome works fine jquery on event not working for class that is append after document ready on phonegap. but it's working fine on chrome.
my template code is here:

render method:
    var template = $("#newsList").html();
    var str = "";
    for(var i in data[page]){
        str += template.format(data[page][i]['created_at'], data[page][i]['title'], data[page][i]['content'], data[page][i]['id']);
    }
    $("#news-list-wrapper").html(str);

and event code:
    var app = {
        initalize: function(){
            var _this = this;
            $(document).on("click", ".news-list", function(){
                _this.openNews($(this).attr("news_id"));
            });
        }
    }

    $(document).ready(function(){
        document.addEventListener("deviceready",function(){
            app.initialize();
        },false);
    });

my jquery version is 1.9.1 and i tried 2.1.0
and i tried these;
    $(document).on("click", ".news-list", function(){....
    $(".news-list").on("click", function(){....
    $(document).delegate("click", ".news-list", function(){....
    $(".news-list").live("click", function(){....


text:
Q: display table row only when if statement is correct I want to display table row with its content only if the two variables are not empty but it seems the syntax is not correct. Could you please have a look at my code.
<?php
  if (!empty($title1) && !empty($title2)) {

    echo '

    Title 1:
'.$title1;
    if (!empty($more_one)) {
      echo '
See More';
    }
     echo
    '

    Title 2:
'.$title2;
    if (!empty($more_two)) {
      echo '
See More';
    }
     echo
    '

'
}

?>

A: DEMO
<?php
$title1 = "foo"; $title2 = "bar";
if (!empty($title1) && !empty($title2)):
?>

  <?php
   echo 'Title 1:
' .  $title1;
   if (!empty($more_one)) echo '
See More';
  ?>

  <?php
   echo 'Title 2:
'.$title2;
   if (!empty($more_two)) echo '
See More';
  ?>

<?php endif; ?>

A: Replace your code as follows
<?php
  if (!empty($title1) && !empty($title2)) {
    echo '
Title 1:
'.$title1;
    if (!empty($more_one)) {
      echo '
See More';
    }
    echo '	Title 2:
'.$title2;
    if (!empty($more_two)) {
      echo '
See More';
    }
    echo '
';
  }
?>

there was many echos missing in your code..

A: I think it will help you to take care of your conditions
<?php

if (!empty($title1) && !empty($title2)) {
    $html = "";
    $html .='
Title 1:
' . $title1;
    if (!empty($more_one)) {
        $html .= '
See More';
    }

    $html .= '	Title 2:
' . $title2;
    if (!empty($more_two)) {
        $html .= '
See More';
    }

    $html .= '
';

    echo $html;
}
?>

A: Do you mean:
while(!empty($title1) && !empty($title2)){
//Do this
}

replace the result loader for the query inside the while param.

A: <?php
  if ($title1 != '' && $title2 != '') {
    echo '

            Title 1:
'.$title1;
            if ($more_one != '') {
                echo '
See More';
            }
            echo
            '

            Title 2:
'.$title2;
            if ($more_two != '') {
                echo '
See More';
            }
            echo
            '

';
   }
?>

A: on last echo missing ";"
echo '
';


text:
Q: Manipulating arrays in php I have an file uploading site, it has an option of uploading through urls, what I am trying to do is whenever a user uploads through url, I check my database if a file exists that was uploaded through same url it displays the download url directly instead of uploading it again.
The data sent to uploading script is in array form like:
Array (
[0] => http://i41.tinypic.com/3342r93.jpg
[1] => http://i41.tinypic.com/28cfub7.jpg
[2] => http://i41.tinypic.com/12dsa32.jpg
)

and the array used for outputing the results is in form like this:
Array
(
    [0] => Array
        (
            [id] => 43
            [name] => 3342r93.jpg
            [size] => 362750
            [descr] =>
            [password] =>
            [delete_id] => 75CE
            [upload_id] => 75F45CAE1
        )

    [1] => Array
        (
            [id] => 44
            [name] => 28cfub7.jpg
            [size] => 105544
            [descr] =>
            [password] =>
            [delete_id] => D392
            [upload_id] => 6676FD881
        )

    [2] => Array
        (
            [id] => 45
            [name] => 12dsa32.jpg
            [size] => 49000
            [descr] =>
            [password] =>
            [delete_id] => 54C9
            [upload_id] => A58614C01
        )

)

Now I want is that if the link http://i41.tinypic.com/28cfub7.jpg is already upload I just add it to output array but maintain it in a order (if the link added was 2nd in array the output result should also show it in 2nd)
So what function should be used to remove the matched urls from input array and a function to add it output array in the order no.
// edited
Yes unset will do the thing but I want to maintain the order:
For example after unsetting the array looks like this:
 Array (
    [0] => http://i41.tinypic.com/3342r93.jpg
    // [1] was removed
    [2] => http://i41.tinypic.com/12dsa32.jpg
    )

but the output array would be
    Array
    (
        [0] => Array
            (
                [id] => 43
                [name] => 3342r93.jpg
                [size] => 362750
                [descr] =>
                [password] =>
                [delete_id] => 75CE
                [upload_id] => 75F45CAE1
            )

// this will become [1], so how can i add another output[1] and shift other
// items after it to [2], [3] and so on...
        [1] => Array
            (
                [id] => 45
                [name] => 12dsa32.jpg
                [size] => 49000
                [descr] =>
                [password] =>
                [delete_id] => 54C9
                [upload_id] => A58614C01
            )

    )

A: Well, you can add it to the output array by doing something like:
$OutArray[2] = $element;

Where $element is another Array with the id, name, size (etc...) elements.
As for removing from the array:
unset($OutArray[2]);

You may want to read Array (PHP manual).

A: If you have an indexed array, you can remove a value by doing:
unset ($array[2]);

If you want to add an item to an array, use this shorthand of array_push (you don't need to specify an index!):
$array[] = "new object";

All documentation is on php.net/arrays

A: Why don't use an if statement and/or file_exists() to see if the file is there.  If you already have an array with the values then it just won't be uploaded again.


text:
Q: How do I select nodes in Polymer without using ID? I'd like to use the content multiple times, but in different arrangements. Simply copying all content child nodes into each occurrence (as seen here: Polymer Duplicate Element Content) won't do the trick, and I can't use the querySelector for ID, since each content child node is supposed to be copied into multiple elements.
index.html:
...

    <my-list>

This is first.

This is second.

This is third.

    </my-list>

So I'd want something like this for my my-list.html, but I don't know how to select elements that don't have an ID:
<dom-module id="my-list">
    <template>

    </template>
</dom-module>

There's no interaction on the page, so I'm not concerned about data binding.

A: You can use Polymer.dom(node). An example would be
Polymer.dom(this).querySelector('.first');


text:
Q: Replace Python List/Set implementation with custom one I currently write a source-to-source compiler from a language developed by a professor of mine to Python. It goes all well, but some of the language idiosyncrasies drive me mad. The source language has 1-indexed lists and different slicing rules, and Python uses (much saner) 0-indexed-lists.
Is there any way that I can replace the list implementation Python uses? The following gives the idea of what I want.
class MyList(list):
    # My implementation of 1-indexed lists
    pass

x = ["foo", "bar", "baz"]
y = MyList(["foo", "bar", "baz"])

assert type(x) == type(y) # Should work
assert x[1] == "foo" # Should work

I want to use the syntax sugar python gives me with lists, instead of dealing with generating it on my own. I know I would normally never do that in real code, but in addition to my current need, I wonder about a nice and elegant solution. I think about either fiddling the metaclass of list, or changing its functions at runtime. Is there any way that I can do that AND extend still MyList from list, since it uses list methods under its hood?

A: You could wrap a list in a class and implement special container-related method names like __len__ and __getitem__. Here's an idea of what you might implement:
class MyList(object):

  def __init__(self):
    self._data = list()

  def __getitem__(self, index):
    return self._data[index+1]

  def __len__(self):
    return len(self._data)