Q:

Using JavaSounds from tomcat

I'm trying to write a Java EE application that records sound from the input on the server.
My code works fine when debuging, and running on the server as myself (both ubuntu) however when it's running from the web sever I get an exception:
javax.sound.sampled.LineUnavailableException
at org.classpath.icedtea.pulseaudio.PulseAudioMixer.openImpl(PulseAudioMixer.java:714)
at org.classpath.icedtea.pulseaudio.PulseAudioMixer.openLocal(PulseAudioMixer.java:588)
at org.classpath.icedtea.pulseaudio.PulseAudioMixer.openLocal(PulseAudioMixer.java:584)
at org.classpath.icedtea.pulseaudio.PulseAudioMixer.open(PulseAudioMixer.java:579)
at org.classpath.icedtea.pulseaudio.PulseAudioDataLine.open(PulseAudioDataLine.java:95)
at org.classpath.icedtea.pulseaudio.PulseAudioTargetDataLine.open(PulseAudioTargetDataLine.java:111)
at org.classpath.icedtea.pulseaudio.PulseAudioTargetDataLine.open(PulseAudioTargetDataLine.java:130)

I've tried to add the tomcat user to the audio group (which some documentation suggested) but it's still throwing the exception. I think the only difference must be the environment, but I'm at a loss for where the problem might be.

A:

I've managed to get this working now - but thank for the help.
In the end it was a OS level issue, under ubuntu only users in the audio group can access sound resources when not logged in (https://wiki.ubuntu.com/Audio/TheAudioGroup) and to connect to pulse audio it looks like you need X11 auth of some kind. After those changes it require a restart so tomcat could grab the sound device before anything else did.


Q:

Google chrome has the wrong docky icon

I'm using fedora 20 with xfce.
The launcher icon on docky is the xfce panel icon instead of the google chrome icon, I've made sure the correct icon is inside /usr/share/applications but it's still the panel icon.

A:

I had a similar issue, I was getting the google keep icon instead of chrome. It seems to be a common issue with Docky, see http://wiki.go-docky.com/index.php?title=How_to_Customize_Window_Matching
I simply followed their instructions, but to simplify:

run: xprop | grep WM_CLASS | awk '{print $4}'
This will give you a '+' shaped pointer. Use it to click on your Chrome window. It will output the name, I got 'Google-chrome'
Open /usr/share/applications/google-chrome.desktop for editing and add StartupWMClass=Google-chrome or whatever you got in step 2 without quotes
stop Docky and run: rm ~/.cache/docky/docky.desktop.*.cache
Restart and the icon should be correct.


Q:

Boost spirit: Invalidate parser from member function

this article (boost spirit semantic action parameters) explains how to invalidate a match from a plain function with the signature
void f(int attribute, const boost::fusion::unused_type& it, bool& mFlag)

I would like to invalidate a match from a member function of the grammar:
#include <boost/spirit/home/qi.hpp>
#include <boost/spirit/home/phoenix.hpp>

#include <iostream>
#include <string>

namespace qi  = boost::spirit::qi;
namespace phoenix = boost::phoenix;

class moduleAccessManager
{
public:
    bool getModule(const std::string name)
    {
        if(name == "cat" || name == "dog")
            return true;
        else
            return false;
    }
};

void globalIsModule(std::string moduleName, const boost::spirit::unused_type&, bool& mFlag)
{
        moduleAccessManager acm; /* Dirty workaround for this example */
        if(acm.getModule(moduleName))
            std::cout << "[isModule] Info: Found module with name >"  << moduleName << "<" << std::endl;
        else
        {
            std::cout << "[isModule] Error: No module with name >" << moduleName << "<" << std::endl;
            mFlag = false; // No valid module name
        }
}

template <typename Iterator, typename Skipper>
class moduleCommandParser : public qi::grammar<Iterator, Skipper>
{
private:
    moduleAccessManager* m_acm;

    qi::rule<Iterator, Skipper> start, module;

public:
    std::string m_moduleName;

    moduleCommandParser(moduleAccessManager* acm)
        : moduleCommandParser::base_type(start)
        , m_acm(acm)
        , m_moduleName("<empty>")
    {
        module  =   qi::as_string[qi::lexeme[+(~qi::char_(' '))]]
            [&globalIsModule] // This works fine
//          [phoenix::bind(&moduleCommandParser::isModule, this)] // Compile error
            ;
        start    =  module >> qi::as_string[+(~qi::char_('\n'))];
    };

    void isModule(std::string moduleName, const boost::spirit::unused_type&, bool& mFlag)
    {
        // Check if a module with moduleName exists
        if(m_acm->getModule(moduleName))
            std::cout << "[isModule] Info: Found module with name >"  << moduleName << "<" << std::endl;
        else
        {
            std::cout << "[isModule] Error: No module with name >" << moduleName << "<" << std::endl;
            mFlag = false; // No valid module name
        }
    };

};

int main()
{
    moduleAccessManager acm;
    moduleCommandParser<std::string::const_iterator, qi::space_type> commandGrammar(&acm);

    std::string str;
    std::string::const_iterator first;
    std::string::const_iterator last;

    str = "cat run";
    first = str.begin();
    last = str.end();
    qi::phrase_parse(first, last, commandGrammar, qi::space);

    str = "bird fly";
    first = str.begin();
    last = str.end();
    qi::phrase_parse(first, last, commandGrammar, qi::space);
}

Code on Coliru: http://coliru.stacked-crooked.com/a/4319b38a6d36c362
The important part is these two lines:
            [&globalIsModule] // This works fine
//          [phoenix::bind(&moduleCommandParser::isModule, this)] // Compile error

Using the global function works fine, but that's not an option for me because I need access to the m_acm object which is specific to the parser.
How can I bind a member function to a semantic action and at the same time be able to invalidate the match from that member function (using the 3 argument function signature mentioned above)?

A:

There are two ways:

you can assign to qi::_val using Phoenix actors
you can assign to the third parameter (bool&) inside a "raw" semantic action function

An example is here:

Constraining the existing Boost.Spirit real_parser (with a policy) (using _val)

The anatomy of a semantic action function (with the third argument):

boost spirit semantic action parameters

In your case you have a member function with roughly the "raw semantic action function" signature. Of course, you'll have to bind for the this parameter (because it's a non-static member function).
Note that in this particular case, phoenix::bind is not the right bind to use, as Phoenix Actors will be considered to be "cooked" (not raw) semantic actions, and they will get executed in the Spirit context.
You could either

use boost::bind (or even std::bind) to bind into a function that preserves the arity (!) of the member function:
[boost::bind(&moduleCommandParser::isModule, this, ::_1, ::_2, ::_3)]

This works: Live On Coliru
instead use a "cooked" semantic action, directly assigning to the _pass context placeholder:
[qi::_pass = phoenix::bind(&moduleAccessManager::getModule, m_acm, qi::_1)]

This works too: Live On Coliru

The latter example, for future reference:
#define BOOST_SPIRIT_USE_PHOENIX_V3
#include <boost/spirit/include/qi.hpp>
#include <boost/spirit/include/phoenix.hpp>

#include <iostream>
#include <string>

namespace qi      = boost::spirit::qi;
namespace phoenix = boost::phoenix;

class moduleAccessManager {
public:
    bool getModule(const std::string name) {
        return name == "cat" || name == "dog";
    }
};

void globalIsModule(std::string moduleName, const boost::spirit::unused_type&, bool& mFlag)
{
        moduleAccessManager acm; /* Dirty workaround for this example */
        if(acm.getModule(moduleName))
            std::cout << "[isModule] Info: Found module with name >"  << moduleName << "<" << std::endl;
        else
        {
            std::cout << "[isModule] Error: No module with name >" << moduleName << "<" << std::endl;
            mFlag = false; // No valid module name
        }
}

template <typename Iterator, typename Skipper>
class moduleCommandParser : public qi::grammar<Iterator, Skipper>
{
private:
    moduleAccessManager* m_acm;

    qi::rule<Iterator, Skipper> start, module;

public:
    std::string m_moduleName;

    moduleCommandParser(moduleAccessManager* acm)
        : moduleCommandParser::base_type(start)
        , m_acm(acm)
        , m_moduleName("<empty>")
    {
        using namespace phoenix::arg_names;
        module  =   qi::as_string[qi::lexeme[+(~qi::char_(' '))]]
                        [qi::_pass = phoenix::bind(&moduleAccessManager::getModule, m_acm, qi::_1)]
                    ;
        start   =  module >> qi::as_string[+(~qi::char_('\n'))];
    };

};

int main()
{
    moduleAccessManager acm;
    moduleCommandParser<std::string::const_iterator, qi::space_type> commandGrammar(&acm);

    std::string str;
    std::string::const_iterator first;
    std::string::const_iterator last;

    str = "cat run";
    first = str.begin();
    last = str.end();
    std::cout << str << std::boolalpha
              << qi::phrase_parse(first, last, commandGrammar, qi::space)
              << "\n";

    str = "bird fly";
    first = str.begin();
    last = str.end();
    std::cout << str << std::boolalpha
              << qi::phrase_parse(first, last, commandGrammar, qi::space)
              << "\n";
}


Q:

Normal cone of the complement of an ellipsoid

On page 68, exercise 2.38 in Boyd & Vanderberghe's book, Convex Optimization, a normal cone of a boundary point $x$ of a set $C$ is defined as
$$\mathcal N_C(x) := \left\{ g \mid g^T x \ge g^T y, \quad \forall y\in C \right\}$$
My questions are:

Do we need the convexity of the set $C$ in the normal cone definition above or not?

If $C$ does indeed need to be convex (and for some unknown reasons the authors did not mention it in the definition), what is the definition of a normal cone at a boundary point of a non-convex set $C$?

Assuming that the given definition does not ask for the convexity of the set $C$, what is the normal cone of a boundary point of $C= \{ x \mid x^T A x \ge 1 \}$ in which  $A$ is a positive definite matrix?

My attempts show that the normal cone for this scenario is actually the zero set, which is a bit fishy to me because it is independent of $A$! But why $\mathcal N_C(x)=\{0\}$ for $x$ with $x^TAx=1$ and $C=\{ x \, | \, x^TAx\ge 1\}$:
if $y\in C$, then $-y\in C$. Thus, we can say that $\mathcal N_C(x):=\{g\, | \, g^Tx\ge |g^Ty|, \ \ \forall y\in C\}$. Further, if $y\in C$, then $\lambda y\in C$ for $\lambda \ge 1$. Thus, for a nonzero $g$ to be inside $\mathcal N_C (x)$, we must have $g^Tx\ge \lambda |g^Tx| $ for all $\lambda \ge 1$. Since a boundary point $x$  of $C$ is not zero, we must have $\pm 1= g^Tx/|g^Tx|\ge \lambda$ for any $\lambda \ge 1.$ This is impossible so that $\mathcal N_{C}(x)=\{0\}$.
Please confirm or let me know where my mistake is! Thank you so much in advance.

A:

The book Convex Optimization by Rockafellar requires convexity of $C$ in the definition:

A vector $x^*$ is said to be normal to a convex set $C$ at a point $a$, where $a \in C$, if $x^*$ does not make an acute angle with any line segment in $C$ with $a$ as endpoint, i.e. if $\langle x-a, x^*\rangle \leq 0$ for every $x\in C$. For instance, if $C$ is a half-space $\left\{x | \langle x,b\rangle \leq \beta \right\}$ and $a$ satisfies $\langle a,b\rangle = \beta$, then $b$ is normal to $C$ at $a$. In general, the set of all vectors $x^*$ normal to $C$ at $a$ is called the normal cone to $C$ at $a$. The reader can verify easily that this cone is always convex.

With this definition, Rockafellar states the following theorem (27.4):

Let $h$ be a proper convex function, and let $C$ be a non-empty convex set. In order that $x$ be a point where the infimum of $h$ relative to $C$ is attained, it is sufficient that there exist a vector $x^* \in \partial h(x)$ such that
$-x^*$ is normal to $C$ at $x$. This condition is necessary, as well as sufficient, if $\text{ri} (\text{dom} \; h)$ intersects $\text{ri} \; C$, or if $C$ is polyhedral and $\text{ri} (\text{dom} \; h)$ merely intersects $C$.

Here, $\partial h(x)$ is the subgradient of $h$ at $x$, ri is the relative interior, and dom is the subset of the domain where the objective value is finite. In other words, the normal cone can be used to characterize the minimum of a convex function over a convex set.
You could argue that it is not surprising that a book titled Convex Optimization requires a set to be convex, and that you could extend the definition of a normal cone to nonconvex sets $C$. However, a definition by itself is useless and only comes to life if it is useful somewhere. As far as I know, the normal cone for a nonconvex set is not used in any meaningful theorem.


Q:

python- sqlite3.OperationalError: near ",": syntax error"

This isn't my code; I got it from https://www.youtube.com/channel/UC4KX0hatvRrOVy_D0nPlusg. The author didn't have the source code so I just had to type it up from the video. His worked fine but I kept getting this error:
File "D:\ProgramDevelopment\Python\Project\Python_GUI_IDEL\PythonDatabaseYoutube.py", line 45, in run_query
query_result= cursor.execute(query,parameters)
sqlite3.OperationalError: near ",": syntax error"

Link in github: https://github.com/ahmed-aya/Python_database/blob/master/Python_Database
from tkinter import *
from tkinter import ttk
import sqlite3

class Product(object):

  def __init__(self,wind):
    self.wind=wind
    self.wind.title('IT products')

    frame = LabelFrame (self.wind,text= 'Add new record')
    frame.grid (row=0,column=1)

    Label(frame,text='Name:').grid(row=1,column=1)
    self.name =Entry(frame)
    self.name.grid(row=1,column=2)

    Label(frame,text='Price:').grid(row=2,column=1)
    self.price =Entry(frame)
    self.price.grid(row=2,column=2)

    ttk.Button(frame,text='Add record',command=self.adding).grid(row=3,column=2)
    self.message=Label(text='',fg='red')
    self.message.grid(row=3,column=0)

    self.tree=ttk.Treeview(height=10,column=2)
    self.tree.grid(row=4,column=0,columnspan=2)
    self.tree.heading('#0',text='Name',anchor=W)
    self.tree.heading(2,text='Price',anchor=W)

    ttk.Button(text='Delete record',command=self.deleting).grid(row=5,column=0)
    ttk.Button(text='Edit record',command=self.editing).grid(row=5,column=1)

    self.viewing_records()

  def run_query (self, query, parameters=()):
    with sqlite3.connect('database.db') as conn:
        cursor = conn.cursor()
        query_result= cursor.execute(query,parameters)
        conn.commit()
    return query_result

  def viewing_records(self):
    records = self.tree.get_children()
    for element in records:
        self.tree.delete(element)
    query ='SELECT * FROM product ORDER BY name DESC'
    db_rows = self.run_query (query)
    for row in db_rows:
        self.tree.insert('',0,text=row[1], values = row[2])

  def validation (self):
    return len (self.name.get()) !=0 and len (self.price.get()) !=0

  def adding (self):
    if self.validation():
        query ='INSERT INTO product  VALUES (NULL,?,?)'
        parameters =(self.name.get(),self.price.get())
        self.run_query(query,parameters)
        self.message ['text'] = 'Record {} added'.format (self.name.get())
        self.name.delete(0,END)
        self.price.delete(0,END)
    else:
        self.message['text']='name field or price is empty'
    self.viewing_records()

  def deleting (self):
    self.message['text']=''
    try:
        self.tree.item (self.tree.selection())['text']
    except IndexError as e:
        self.message['text']='Please, select recoard'
        return

    self.message['text']=''
    name=self.tree.item (self.tree.selection())['text']
    query='DELETE FROM product WHERE name=?'
    self.run_query(query,(name,))
    self.message['text']='Record {} deleted.'.format(name)
    self.viewing_records()

  def editing(self):
    self.message['text']=""
    try:
        self.tree.item (self.tree.selection())['values'][0]
    except IndexError as e:
        self.message['text']='Please select record'
        return
    name = self.tree.item (self.tree.selection())['text']
    old_price = self.tree.item (self.tree.selection())['values'][0]

    self.edit_wind= Toplevel()
    self.edit_wind.title('Edit Window')

    Label (self.edit_wind,text='Old name: ').grid(row=0,column=1)
    Entry (self.edit_wind,textvariable=StringVar(self.edit_wind,value=name),state='readonly').grid(row=0,column=2)
    Label (self.edit_wind,text='New name: ').grid(row=1,column=1)
    new_name = Entry(self.edit_wind)
    new_name.grid(row=1,column=2)

    Label (self.edit_wind,text='Old price: ').grid(row=2,column=1)
    Entry (self.edit_wind,textvariable = DoubleVar(self.edit_wind,value=old_price),state='readonly').grid(row=2,column=2)
    Label (self.edit_wind,text='New price: ').grid(row=3,column=1)
    new_price=Entry(self.edit_wind)
    new_price.grid(row=3,column=2)

    Button(self.edit_wind,text='save changes', command=lambda:self.edit_records(new_name.get(),name,new_price.get(),old_price)).grid(row=4,column=2,sticky=W)
    self.edit_wind.mainloop()

  def edit_records(self, new_name,name,new_price,old_price):
    query = 'UPDATE product SET name=?,price,=? WHERE name=? AND price =?'
    parameters = (new_name,new_price,name,old_price)
    self.run_query (query,parameters)
    self.edit_wind.destroy()
    self.message['text']='Record {} changed.'.format(name)
    self.viewing_records()

if __name__== '__main__':
    wind=Tk()
    application = Product(wind)
    wind.mainloop()

A:

As your error says, you have a typo.
query = 'UPDATE product SET name=?,price,=? WHERE name=? AND price =?'
                                        ^ extra comma here


Q:

Deformation Numbers of Genus $g$ Curves

I want to compute $h^1(C, \mathcal{T}_C)$, where $C$ is a genus $g$ smooth projective curve.
This is where I have gotten so far: I know that, because $C$ is a curve, $\Omega_C$ is the Serre dualising sheaf. So, $h^1(\mathcal{T}_C) = h^0(\Omega^{\otimes 2}_C)$. Riemann-Roch then gives $$h^0(\Omega^{\otimes2}_C) - h^1(\Omega^{\otimes2}_C) = 2(\text{deg }\Omega_C) -g+1 = 3g-3.$$
What I do not know how to do is to compute the term $h^1(\Omega^{\otimes2}_C) =h^0(\mathcal{T}_C).$ I tried using a normal exact sequence for the map $|\omega_C| : C \to \mathbb{P}^{g-1}$, but the $\mathcal{T}_{C/\mathbb{P}^{g-1}}$ term confused me.

A:

The best thing to do is to compute directly $h^1(T_C)$. By Riemann-Roch we have $$h^0(T_C)-h^1(T_C)=  \deg(T_C)-g+1=3-3g.$$
On the other hand, by a well-known result by Hurwitz, we know that if $g \geq 2$ then $C$ has only finitely many automorphisms. This, in turn, implies $h^0(T_C)=0$, because the dimension of $H^0(T_C)$ is precisely the dimension of $\mathrm{Aut}(C)$, so the result follows.

A:

In addition to Francesco's answer, can I suggest a slightly different approach?

If $g = 0$, then $C = \mathbb P^1$, and $T_C = \mathcal O_{\mathbb P^1}(2)$, hence $h^1(T_C) = 0$.
If $g = 1$, then $C$ is an elliptic curve, so $T_C = \mathcal O_C$. The dualising sheaf in this case is also $\mathcal O_C$, so $h^1(T_C) = h^1(\mathcal O_C) = h^0(\mathcal O_C) = 1$.
If $g \geq 2$, then ${\rm deg \ }T_C = - {\rm deg \ }\Omega_C = 2 - 2g < 0$. A line bundle with a negative degree has no global sections (Hartshorne IV.1, Lemma 1.2), so $h^0(T_C) = 0$. Therefore, by Riemann-Roch, which states that $ h^0(T_C) - h^1(T_C) = {\rm deg}(T_C) - g + 1, $ we learn that $ h^1(T_C) = 3g - 3.$


Q:

Import: module not found by compiler, works with Visual Code, DefinitelyTyped

I'm new to Typescript and I hope I'm missing something simple here. I've installed type definitions for a javascript library and get an error thrown by the compiler but can't seem to figure out what's going on. My editor is Visual Studio Code and I'm developing a react typescript project on a Mac. Here's the play by play.
I installed type definitions for 'keen-tracking' like so,
npm install @types/keen-tracking@2.0.0

Next, I added a few lines to 'src/vendor.ts' that looks like the following,
import KeenTracking from 'keen-tracking';

const keenTrackingCredentials = {
    projectId: 'xxx',
    writeKey: 'yyy'
  };

export const keenClient = new KeenTracking(keenTrackingCredentials);

Lastly, I import the keenClient in a component like so,
import {keenClient} from '../model/vendor';

const MyComponent :React.SFC<MemberProps> = props => {
    return <div>
        <Cover {...props} actionLabel="Label" action={function():void{ keenClient.recordEvent('pledge', {member: props.member.email} ) }} />
    </div>

I run my project with npm start and when I save the file, the compiler throws the following error
Module not found: Can't resolve 'keen-tracking' in '~/projectDir/src/model'

Visual Studio Code recognizes the link to the keen-tracking type definitions which looks like the following. I recognize that the typescript version is 2.0 and when I type tsc --version at a command prompt I see that version 3.2.2 is running, though I'm not positive that's the same version that Visual Studio Code is using.
// Type definitions for keen-tracking 2.0
// Project: https://github.com/keen/keen-tracking.js#readme
// Definitions by: Rui Ferreira <https://github.com/rui-ferreira>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.2

export default class KeenTracking {
    constructor(options: { projectId: string; writeKey: string; requestType?: string });

    recordEvent(
        collectionName: string,
        event: object
    ): Promise<{ created: boolean }>;

    recordEvents(events: {
        [collectionName: string]: object[];
    }): Promise<{
        [collectionName: string]: boolean[];
    }>;
}

I'd appreciate any pointers on where I can look next to get this resolved, my current thinking is that the definition is incorrect or maybe I need to debug the generated js files, though I haven't figured out how to do that just yet. Thank you!

A:

You installed types but not the module so install the module using below command and restart the app
   npm install keen-tracking --save

And also the way you installed types may not work
Try this too without version
  npm install --save @types/keen-tracking


Q:

Can the quick-save button be made to overwrite old save games?

Far cry 2 automatically assigns a 'Quick Save' option to the key F5, which is great, because I find the Far Cry 2 Save menu very clunky.
However, it auto-saves to a new file, or slot, when I'd prefer it just overwrote the most recent. Normally, if I want another save for whatever reason I'll go into the save menu manually.
Is there any way to tweak Far Cry 2 to Quicksave over the top of an older save file?

A:

I am not aware of any way to change the quicksave function to what you want.
In the end, I just used the quicksave function whenever I felt it necessary and then before quitting the game, I would just delete all but the most recent save game.
Clunky, yes, but it was the only way I could play without needing to fiddle with the menu each time I wanted to save, while also avoiding the problem of hundreds of savegames littering my hard drive.


Q:

Find a bijective function between all stricly increasing sequences and all increasing sequences.

$$A = \{f \in \mathbb{N}^\mathbb{N}: \forall n \in \mathbb{N} \quad f_n \leq f_{n+1}\}$$$$B = \{f \in \mathbb{N}^\mathbb{N}: \forall n \in \mathbb{N} \quad f_n < f_{n+1}\}$$Find a bijective function $\Psi:A \rightarrow B$ or $\Psi:B \rightarrow A$.
It's easy to spot that $B \subseteq A$ and because of that it's easy to spot that there is an inective function $g: B \rightarrow A$ so $|B| \leq |A|$. But because of the $\subseteq$ I struggle to find the bijective function.

A:

Hint: Consider
$$(f_n)\in A\mapsto (f_n+n-1)\in B.
$$


Q:

Overflow method not working in html page.

I am working on an assignment for school which is designing an app with HTML. I am having trouble with the contents of the apps bleeding over at the bottom when you scroll down. I tried various options of the overflow method and nothing seems to work. I included the entire css and html. Thanks to anyone who takes the time to help me out!
<!DOCTYPE html>

    <meta charset="utf-8">
    <title></title>
    <link rel="stylesheet" href="CSS/reset.css">
    <link rel="stylesheet" href="CSS/style.css">
    <link href=https://fonts.googleapis.com/css?family='Roboto' rel='stylesheet'>

      Washington at State Station

Line

Destination

Arrival

124

Eastbound

Navy Pier

5 Min

Freq. 10 min

124

Southbound

Navy Pier

10 Min

Freq. 10 min

J14

Southbound

103rd/Stony Island

15 Min

Freq. 15 min

151

Northbound

Devon/Clark

16 Min

Freq. 16 min

60

Eastbound

Randolph/Harbor Dr

18 Min

Freq. 20 min

6X

Reroute

Jackson Park Express

30 Min

Freq. N/A

4

Out of Service

Cottage Grove

Resumes 12:10 am

20

Out of Service

Madison

Resumes 12:10 am

157

Out of Service

Streeterville/Taylor

Resumes 6:00 am

CSS

*, *:before, *:after {
  box-sizing: border-box;
}

body {
  background-color: #6E6C6C;
  font-family: 'Roboto';
  font-size: 16px;
  color: #ffffff;
  margin-top: 75px;
}

#table-wrapper {
  position: relative;
}

#table-scroll {
   height: 647px;
  overflow: auto;
}

h1 {
  font-size: 18px;
  font-weight:600;
  line-height: 1.3em;
  color:#02356A;
}

h3 {
  font-size: 14px;
  font-weight: 400;
  line-height: 1.3em;
  color:#02356A;
}

.container {
  margin: 0 auto;
  width: 360px;
  height: 667px;
}

nav {
  margin: 0 auto;
  position: fixed;
  width: 360px;
  height: 111px;
  background-color: #164F9C;
}

.bus-list {
  padding-top: 158px;
  width: 100%;
  padding-bottom: 50px;
}

.info {
  text-align: left;
  padding: 16px;
  width: 100%;
  background-color: #e5edf2;
  border-bottom: thin #000000 solid;
}

.info:hover {
    background-color: #81aef1;
}

.content {
    width: 90%;
    display:inline-block;
}

.icon {
    width: 4px;
    padding-left: 24px;
    }

.title {
    font-size: 20px;
    color: #ffffff;
    width: 180px;
    padding-left: 32px;
    vertical-align: middle;
    line-height: 1.3em;
}

.ham-menu {
    width: 24px;
}

.search-icon {
    padding-left: 24px;
    width: 24px;
}

.app-bar {
    padding: 16px;
}

.route-bar {
    background-color:#02356A;
    height: 48px;
    width: 360px;
    text-align: left;
    padding: 16px;
}

.lines {
    text-align: left;
    width: 100px;
}

.dest {
    width: 37%;
}

.times {
    width: 27%;
    text-align: right;
}

.bottom-bar {
    background-color: #000000;
    margin-top: 425px;
}

.alert {
    background-image: url(file:///C:/Users/Steve/bloc/frontend/images/alerts.png);
    background-repeat: no-repeat;
    background-size: 42px 38px;
    background-position: right;
    width: 27%;
}
.footer {
    position: fixed;
    background-color: #000000;
    width: 360px;
    bottom: 37px;
    height: 48px;
    background-image:url(file:///C:/Users/Steve/bloc/frontend/images/bottom-bar.png);
    background-size: cover;
}

A:

You have a bottom: 37px; in your CSS in the footer. Set this to 0px and you won't see the element under it anymore.


Q:

Building of your Domain Objects?

I'm in the process of trying to learn Domain Driven design so i'm sure this will be the first of many questions (i can already think of at least a couple more but i don't want to fragment my questions). I'm using Dino Esposito's "Architecting Microsoft .NET Solutions for the Enterprise" which, in some cases, is very abstract.
First of all, i always assumed your business objects would have some type of connectivity (passed in through the constructor) whether it be a repository or DBConnection or whatever. Looks like i'm wrong.
Do you just construct your domain object by a combination passing in ALL the data and maybe some add/remove functions for the underlying collections (Order-->OrderDetails)? So in your DataMapper you would construct the buisness objects from the tuples in your DB and then return them to an application layer through a repository where you would use them? Then both your application layer & DL would need a reference to your Business objects. This would of course force you to build in your own lazy loading mechanism if your not using an ORM or maybe even if your using an ORM because you would be disconnected at this point. You wouldn't want to load ALL the underlying data in all circumstances of course.

A:

According to domain driven design - domain objects are persistence ignorant. That means - they shouldn't contain infrastructure code that connects to database. However - repository abstractions are considered as part of domain model. Therefore - it's 'allowed' to use those, but I personally like to avoid that.
If You are talking about modeling of domain objects - then no, mostly it's not a good thing to model them as dumb data bags. That leads to anemic model.
If You are talking about reconstructing domain objects when they are retrieved from persistence mechanisms, then Yes - basically that's just rebuilding domain object from scratch. But tricky part here is - this rebuilding and other persistence related issues should not invade into Your domain. You should not have public add/remove functions without any validations just to make Your persistence to work. In reality - it's hard to keep model completely clean (in fact, it's already messed up with programming language You are using and there does not exist pure medium that could hold it, apart from reality You are modeling itself) and there will always be some implicit dependencies (e.g. - everything must be marked virtual when using NHibernate ORM).
But You aren't focusing on what You should in case You want to understand domain driven design. Core of domain driven design is ubiquitousness in language and explicitly modeled business. It's about way You think. Start with reading 'blue book'. Twice. And check out this sample application by Szymon Pobiega until You understand reason behind those lines of code.
EDIT: Oh...  forgot about ddd yahoo group which is quite nice source of info too.

One thing that confuses me in your post is about you shouldn't "Model" them as dumb property bags but in "reconstructing" then its ok.

Take a look at this (oversimplified and bad one) example. From client side, unless You are cheating, You won't be able to create a new Person that has name.Length>50.
public class Person{
  public Person(string name){
      if (name.Length>50) throw new ArgumentException
        ("Person name length should not exceed 50 characters");
      Name=name;
    }
    public string Name {get;private set;}
}

But when we reconstruct object from persistence mechanisms - cheating is exactly what we do. We bypass validation, we set data directly, we bypass object behavior because data is what represents state. E.g. using reflection:
typeof(Partner).GetProperty("Name").SetValue(partner,nameFromDB);

It sounds like its a very complex topic and probably a lot of people who think the are using domain-driven design..aren't

Domain driven design at start is truly confusing. And worst thing what could happen (and usually happens) is when developer starts to believe out of nowhere that he is doing it right (been there myself. might be I'm still there):

And... is the Domain-Driven Design used in .NET pop culture really Domain-Driven Design in fact

That leads to lot of confusion and falsehood. Some try to explain why. Some just hate it.


Q:

How did this violate "Nice?"

My answer was deleted on this question with a comment that I needed to follow the "Nice" policy.  I don't get how this wasn't nice; I was specifically addressing the interchange of childish "making up rules" invocations by the participants in the dispute that prompted the original question.  How is calling childish action childish a failure of "being nice?"

A:

You only read half of the closing comment. The user asked how to do this <thing> in work, but your answer was essentially to get another job. Here is the comment I left in that regard:

These types of "just don't have the problem" solutions don't answer the question asked…

This is a problem on Lifehacks where folks ask (for example) how to get a spaghetti stain out of their shirt, and folks suggest not spilling food on themselves in the first place.
And the answer itself was written in a way to pander to the crowd through name-calling and snark. Here is the answer I removed:

I'd suggest looking for a different job that employs adults, rather than grade school children.

That is not the tone we wish to set in the context of an answer on the site. I thought I should mention our broad "Be Nice" policy to clarify the issue.


Q:

Did Bail Organa and/or Princess Leia know where to find Obi-Wan on Tatooine?

Since we know that they were headed to Tatooine at the beginning of A New Hope (confirmed by Bail Organa's conversation with Mon Mothma in Rogue One), did they know where he resided on Tatooine? The only way I could think of that Organa would know would be if Obi-Wan told him in Revenge of the Sith (didn't happen) or he knew where Owen and Beru Lars lived. If not, has it been established how they would have found him?

A:

Bail was in the room when Yoda and Obi-Wan discussed splitting up the twins. He also dropped Obi-Wan off at Tatooine before delivering Padmé's body to her family on Naboo. He certainly knew that Obi-Wan would be in the near-vicinity of the Lars homestead and it's possible that he's been in contact with him more recently.

“Cliegg Lars still lives on Tatooine, I think-and Anakin’s stepbrother
  … Owen, that’s it, and his wife, Beru, still work the moisture farm
  outside Mos Eisley …”
“As close to kinfolk as the boy can come,” Yoda said approvingly. “But
  Tatooine, not like Alderaan it is-deep in the Outer Rim, a wild and
  dangerous planet.”
“Anakin survived it,” Obi-Wan said. “Luke can, too. And I can-well, I
  could take him there, and watch over him. Protect him from the worst
  of the planet’s dangers, until he can learn to protect himself.”


Q:

Sorting numeric strings

I'm using DatagridView in c# to read a csv file.
The data is not sorting properly when clicking the headers at the top of the grid.
For example, it should be sorted as 1,2,3,4,5,etc
However, the result is 1,10,2,20,etc.
I think I need to convert it from a string to an int, but I don't know how to do that.
Here's my current code:
try
{
    if (openFileDialog1.ShowDialog() == DialogResult.OK)
    {
        string csvPath = openFileDialog1.FileName;
        string rowValue;
       // int rowValue = int.Parse(??);
        string[] cellValue;
        dataGridView1.Rows.Clear();
        //dataGridView1.Columns.Clear();
        if (System.IO.File.Exists(csvPath))
        {
            System.IO.StreamReader fileReader = new StreamReader(csvPath);
            rowValue = fileReader.ReadLine();
            cellValue = rowValue.Split(',');

            for (int i = 0; i <= cellValue.Count() - 1; i++)
            {
                DataGridViewTextBoxColumn column = new DataGridViewTextBoxColumn();
                column.Name = cellValue[i];    //column name , value
                column.HeaderText = cellValue[i];
                dataGridView1.Columns.Add(column);
               // dataGridView1.Columns[].CellType = typeof(Int64);
            }
            while (fileReader.Peek() != -1)
            {
                rowValue = fileReader.ReadLine();
                cellValue =  rowValue.Split(',');
                dataGridView1.Rows.Add(cellValue);
            }
            fileReader.Dispose();
            fileReader.Close();
        }
        else

A:

Try to register a comparer into the DataGridView like this:
private void CustomSortCompare(object sender, DataGridViewSortCompareEventArgs e)
{
    if(e.Column.Name != "CollumnName") return;

    var a = int.Parse(e.CellValue1.ToString());
    var b = int.Parse(e.CellValue2.ToString());

    // If the cell value is already an integer, just cast it instead of parsing
    e.SortResult = a.CompareTo(b);
    e.Handled = true;
}

and the register the sorter in the DataGridView
dataGridView1.SortCompare += CustomSortCompare;

See the documentation DataGridView.SortCompare Event


Q:

Use Promise.all instead of async/await if a forEach

I am making a discord bot using discord.js which gets data from an API and add or delete the message associated with the data.
In the snippet below I have written the logic to delete the messages if the corresponding data is no longer available at API.
gameEmbeds is a map which contains key as the identifier for the data from API and val as the identifier for the message in the discord channel.
  gameEmbeds.forEach(async (val, key, map) => {
  if (map !== undefined && newGames.get(key) === undefined) {
    const message = await channel.fetchMessage(val);
    message.delete()
      .catch((e) => {
        console.error(`${new Date()} `, e);
      });
  }

I have to make iterator function async because every entry to be processed one by one to make the changes in the UI look smoother which violates the async nature of JS.
I think I can make sure this happens with Promise.all which will also make this code a bit faster, however, I don't know how to implement it in my code without breaking stuff. I am new to node.js. Please help.
EDIT: Thanks CF256, I removed redundant .then()

A:

I will create a new array for holding all the small promises, and once the forEach loop is complete, I will then call the Promise.all on the small promises keeper

const allDeleteJobs = [];
gameEmbeds.forEach(async (val, key, map) => {
  if (map !== undefined && newGames.get(key) === undefined) {
    const message = await channel.fetchMessage(val);
    // Push the new delete job to the array registry
    allDeleteJobs.push(message.delete());
  }
});
(async () => {
  if(allDeleteJobs.length >= 1){
    await Promise.all(allDeleteJobs);
    // Delete all the messages or do other stuff
  }
})()
.catch(error => console.error(error));


Q:

How to set id of a socket in WebSocket?

I'm using: https://github.com/websockets/ws as websockets.
In socket.io you could give an id to your sockets like:
io.emit('id','myText');

io.on('id',function(data){
    //read data
});

In websocket on the server you can read sockets by id.
ws.on('id', function (data) {

};

You can read sockets by id on the client too.
ws.addEventListener('id', function (data) {

};

But I couldn't find how to send a socket with a specific id, I've also checked the code base. Am I missing something or is this impossible? Or are there some hacks that could achieve this?
//I want this:
ws.send('id','myText');

A:

I'll format my comments into an answer since it appears to have explained things for you:
There is no handler for your own message names like this in webSocket:
ws.on('id', function(data) { ... });

Instead, you listen for data with this:
ws.on('message', function(data) { ... });

If you want to send a particular message name, you send that inside the data that is sent. For example, data could be an object that you had data.messageName set to whatever you want for each message.
It appears like you're trying to use a socket.io API with a webSocket. That simply doesn't work. socket.io adds a layer on top of webSocket to add things like message names. If you want to use that type of layer with a plain webSocket, you have to implement it yourself on top of a webSocket (or just use socket.io at both ends).


Q:

How to execute tcl script from php?

I need to execute a TCL script from PHP. At the moment I am using the following code
<?php
echo passthru("tclsh83 Testcases/source.tcl ");
?>

This is working. But this creates a shell for each call . How do I open a shell and communicate to and fro from the TCL script . Any pointers will be appreciated .
Regards,
Mithun

A:

If you have lots of data to send to the tcl script, you could open read and write pipes with proc_open().  Then, in the tcl script, use gets stdin varname to read a line from stdin.


Q:

R function to allocated a fixed resource based on a unit value

I am trying to create a function in R to allocate a fixed amount of units based on the value those units provide.  I set up the below sample dataframe.
fruit <- c("apple","orange","bannana","cherry")
units_of_mass <- c(9, 11, 16, 7)
health_pts <- c(5, 3, 6, 1)
diet_plan <- data.frame(fruit, units_of_mass, health_pts)
total_units_desired <- 32

So what I would like to do is to allocate the total units desired based on the health points assigned to each fruit, starting with the highest health points.
I tried using dplyr but got stuck
fruit_detail <- diet_plan %>%

arrange(fruit, health_pts) %>%

mutate(
  cum_units = cumsum(units_of_mass) - units_of_mass,
  can_allocate = total_units_desired - cum_units,
  allocated = ifelse(can_allocate <= 0, 0, ifelse(can_allocate >=
  cum_units, cum_units))
 )

The simple way to do this would be to arrange by health points and subtract units until you run out of total_units_desired, which would look something like the below:
## iterate on allocations
diet_plan <- setDT(diet_plan)

max <- max(diet_plan$health_pts)

allocation_1 <- subset(diet_plan, health_pts == max)
allocation_1[, units_allocated := ifelse(total_units_desired >
               units_of_mass, units_of_mass, total_units_desired)]

remaining_units <- ifelse(total_units_desired - allocation_1$units_allocated
                   > 0, total_units_desired - allocation_1$units_allocated,
                   0)

diet_plan <- subset(diet_plan, health_pts < max)
max <- max(diet_plan$health_pts)

allocation_2 <- subset(diet_plan, health_pts == max)
allocation_2[, units_allocated := ifelse(remaining_units > units_of_mass,
                                  units_of_mass, remaining_units)]

remaining_units <- ifelse(remaining_units - allocation_2$units_allocated >
                   0, remaining_units - allocation_2$units_allocated, 0)

diet_plan <- subset(diet_plan, health_pts < max)
max <- max(diet_plan$health_pts)

allocation_3 <- subset(diet_plan, health_pts == max)
allocation_3[, units_allocated := ifelse(remaining_units > units_of_mass,
                                  units_of_mass, remaining_units)]

remaining_units <- ifelse(remaining_units - allocation_3$units_allocated >
                   0, remaining_units - allocation_3$units_allocated, 0)

diet_plan <- subset(diet_plan, health_pts < max)
max <- max(diet_plan$health_pts)

allocation_4 <- subset(diet_plan, health_pts == max)
allocation_4[, units_allocated := ifelse(remaining_units > units_of_mass,
units_of_mass, remaining_units)]

result <- rbind(allocation_1, allocation_2, allocation_3, allocation_4)

 fruit units_of_mass health_pts units_allocated
bannana        16          6              16
apple           9          5               9
orange         11          3               7
cherry          7          1               0

A:

The way you presented your problem, we can just sort by health_pts, then find the cumulative sum of units_of_mass, which is the total units_allocated if we take that item and all items above it. Then we can just filter the items where taking them wouldn't put us over the limit of total_units_desired.
The remaining rows, then, can have the maximum amount of units allocated:
diet_plan_sum %>%
    arrange(desc(health_pts)) %>%                # Sort by health_pts
    mutate(cum_sum = cumsum(units_of_mass)) %>%  # Calculate total cumulative units
    filter(cum_sum < total_units_desired) %>%    # Drop items over allocation limit
    mutate(units_allocated = units_of_mass) %>%  # For remaining rows, allocate max
    select(-cum_sum)                             # Drop cum_sum variable

    fruit units_of_mass health_pts units_allocated
1 bannana            16          6              16
2   apple             9          5               9

If you want to allocate the remaining units, we can then make a few changes to the above:
First, we find the first row where we go over the threshold: this is the only row with partial values. We can then set its units_allocated value to total - the proceeding row's value, which is the remainder.
For every other row, we check if the cumulative sum is greater than the threshold: if so, set units_allocated to 0, if not, set units_allocated to the units_of_mass:
diet_plan_sum %>%
    arrange(desc(health_pts)) %>%
    mutate(cum_sum = cumsum(units_of_mass),
           # Find the first row where we go over the threshold, set it to remainder
           units_allocated = if_else(cum_sum > total_units_desired & lag(cum_sum) < total_units_desired,
                                     total_units_desired - lag(cum_sum),
                                     if_else(cum_sum > total_units_desired,
                                             0,
                                             units_of_mass))) %>%
    select(-cum_sum) # Drop cum_sum variable

    fruit units_of_mass health_pts units_allocated
1 bannana            16          6              16
2   apple             9          5               9
3  orange            11          3               7
4  cherry             7          1               0


Q:

Convert array values to object keys

I do a get which returns me a json object like so:
        "data": [
[
"2016 Pass/Fail Rates by Test Centre",
"",
"",
"",
"",
"",
"",
"",
"",
""
],
[
"",
"Passes",
"",
"No ID",
"",
"Fails",
"",
"Fail Dangerous",
"",
"Total"
],
[
"Sometown",
"8,725",
"53.40%",
"140",
"0.90%",
"7,417",
"45.40%",
"48",
"0.30%",
"16,330"
],
[
"Some Other Town",
"12,778",
"44.80%",
"193",
"0.70%",
"15,422",
"54.10%",
"103",
"0.40%",
"28,496"
],
[... many more identically formatted arrays ...]

and I would like to end up with:
[{"Location":"Sometown", "Passes":8,725, "Pass%":53.40%, "No ID":140, "NoID%":0.90%, "Fails":7,417, "Fail%":45.40%, "Fail Dangerous":48, "FailDangerous%":0.30%, "Total":16,330}, {"Location":"Some Other Town", "Passes":8,725, etc etc...

So I want to ignore the first array inside the "data" array, use the values of the second array as keys (and replace the empty strings with something more useful) and the values in all remaining arrays as values in the resulting object.
So it is quite the multipart problem, though I suspect a fairly simple one.  What is the simplest way to do that - and if different, what is the leanest way to do it in terms of processing/page load?
Thanks in advance,

A:

You can iterate over your array while adding your index and value into an object...
You can find an example on how you can iterate objects and arrays here and an example here
Generally, to add an item to object
var array = [{"Location":"Sometown"}, {"Location2":"Sometown2"},    {"Location3":"Sometown3"}],
object = {};
array.forEach(function(element, index) {
    object[index] = element;
});
console.log(object);

A:

You could take the second array as keys for the wanted objects and iterate only the part after the keys. Then iterate the keys and build a new object for the values of the array. Return the object for mapping for a new array.

var data = { data: [["2016 Pass/Fail Rates by Test Centre", "", "", "", "", "", "", "", "", ""], ["Location", "Passes", "Passes%", "No ID", "No ID%", "Fails", "Fails%", "Fail Dangerous", "Fail Dangerous%", "Total"], ["Sometown", "8,725", "53.40%", "140", "0.90%", "7,417", "45.40%", "48", "0.30%", "16,330"], ["Some Other Town", "12,778", "44.80%", "193", "0.70%", "15,422", "54.10%", "103", "0.40%", "28,496"]] },
    keys = data.data[1],
    result = data.data.slice(2).map(function (a) {
        var temp = {};
        keys.forEach(function (k, i) {
            temp[k] = a[i];
        })
        return temp;
    });

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }


Q:

jQuery: replacing HTML with dynamic HTML instead of appending

So far, I've got this code:
$("
", {
    "id": "myId",
    "class": "myClass",
    "html": "Hello world!"
}).appendTo("#myContainer");

This appends

Hello world!

to #myContainer, as one would expect.
But instead of appending, I would like to have it replace the contents.
I'm imagining something like this:
$("#myContainer").html("
", {
    "id": "myId",
    "class": "myClass",
    "html": "Hello world!"
});

A:

Actually, this is really easy to do, you just have to wrap the dynamic HTML in $() (or jquery(), if you prefer) again:
$("#myContainer").html($("
", {
    "id": "myId",
    "class": "myClass",
    "html": "Hello world!"
}));

Even though this works perfectly fine, I'm wondering if there's a more elegant/performant way of doing this.


Q:

How to solve Scanner Permissions issues

My computer previously ran Ubuntu 10.4.  After upgrading to 13.4, my Epson scanner no longer can be found by the system.  Following documentation, I find the following:
$ sane-find-scanner

  # sane-find-scanner will now attempt to detect your scanner. If the
  # result is different from what you expected, first make sure your
  # scanner is powered up and properly connected to your computer.

  # No SCSI scanners found. If you expected something different, make sure that
  # you have loaded a kernel SCSI driver for your SCSI adapter.

could not open USB device 0x046d/0x082b at 001:007: Access denied (insufficient permissions)
...
  # No USB scanners found. If you expected something different, make sure that
  # you have loaded a kernel driver for your USB host controller and have setup
  # the USB system correctly. See man sane-usb for details.
...

If I instead run sudo sane-find-scanner, I get
$ sudo sane-find-scanner

  # sane-find-scanner will now attempt to detect your scanner. If the
  # result is different from what you expected, first make sure your
  # scanner is powered up and properly connected to your computer.

  # No SCSI scanners found. If you expected something different, make sure that
  # you have loaded a kernel SCSI driver for your SCSI adapter.

found USB scanner (vendor=0x04b8 [EPSON], product=0x0131 [EPSON Scanner]) at libusb:001:009
could not fetch string descriptor: Pipe error
could not fetch string descriptor: Pipe error
  # Your USB scanner was (probably) detected. It may or may not be supported by
  # SANE. Try scanimage -L and read the backend's manpage.

So what do I do?  scanimage -L does nothing for me and I don't know what the "backend's manpage" might be.  It's seems likely that this is a permissions issue since the scanner can be found as root, but I don't know how to solve it.  Can someone help?
Update:
I had also tried simple-scan and xsane.  Neither of them could find the scanner.  That was what led me to try sane-find-scanner.

A:

My scanner(Epson Perfection V-300 Photo is NOT supported). So how did it ever work with Ubuntu 10.04? "Perfection V300 Photo    USB 0x04b8/0x0131 Unsupported   supported by the epkowa backend plus non-free interpreter".  Thanks to Marc for giving me a place to look, the first step there got me this information, which brought back the memories of what I had to do to get this to work with Ubuntu 10.04.  I downloaded the drivers and everything just worked.
I would say that the error message in sane-find-scanner is less helpful than it easily might be.
Instead of just
  # Your USB scanner was (probably) detected. It may or may not be supported by
  # SANE. Try scanimage -L and read the backend's manpage.

they could have easily included a link to http://www.sane-project.org/sane-mfgs.html and saved me hours of wasted time investigating.


Q:

Alternative solutions for Hibernate.Envers

i'm planning a historization for my java webapp (spring, hibernate).
By googling I found Hibernate.Envers, which seems to be the perfect solution for me.
Are there any comparable solutions?
Thanks a lot!
Jean

A:

The only alternative I know is the Hibernate Audit Library but

It is more focused on auditing than historization.
I have no idea of the maturity

I would just go for Envers if using Hibernate.


Q:

Split a string based on each time a Deterministic Finite Automata reaches a final state?

I have a problem which has an solution that can be solved by iteration, but I'm wondering if there's a more elegant solution using regular expressions and split()
I have a string (which excel is putting on the clipboard), which is, in essence, comma delimited. The caveat is that when the cell values contain a comma, the whole cell is surrounded with quotation marks (presumably to escape the commas within that string). An example string is as follows:
123,12,"12,345",834,54,"1,111","98,273","1,923,002",23,"1,243"

Now, I want to elegantly split this string into individual cells, but the catch is I cannot use a normal split expression with comma as a delimiter, because it will divide cells that contain a comma in their value. Another way of looking at this problem, is that I can ONLY split on a comma if there is an EVEN number of quotation marks preceding the comma.
This is easy to solve with a loop, but I'm wondering if there's a regular expression.split function capable of capturing this logic. In an attempt to solve this problem, I constructed the Deterministic Finite Automata (DFA) for the logic.

The question now is reduced to the following: is there a way to split this string such that a new array element (corresponding to /s) is produced each time the final state (state 4 here) is reached in a DFA?

A:

Using regex (unescaped): (?:(?:"[^"]*")|(?:[^,]*))
Use that and call Regex.Matches() which is .NET, or its analog in other platforms.
You could further expand the above to this: ^(?:(?:"(?<Value>[^"]*)")|(?<Value>[^,]*))(?:,(?:(?:"(?<Value>[^"]*)")|(?<Value>[^,]*)))*$
This will parse the whole string in 1 shot, but you need named groups and multi-capture per group for this to work (.NET supports it).


Q:

How to make filter and word replacement method for android studio

Welcome,. I am making an application to recognize the voice and convert it to text and then compare and correct it, so far everything from converting voice to text and comparing it works perfectly, but there are some words that I want to change or change their wording ... I tried to put it under an if statement As in the place of the code, and it was working well in terms of application, but it affects performance significantly So I was asking if I could make something like a filter so that it contains a large group of words and at the same time maintains a good performance for the application.
An example of what i did :
If(inputText.getText.toString.contains("A Specific Word ")){
String before ;
String after ;
before = inputText.getText.toString;
after = before.replaceAll("A Specific Word", "ASW" );
inputText.setText(after);
}
But this Causes performance problems.

A:

I think you can simply enhance it by usingthis code:
try{
    String sentence = inputText.getText().toString();
    inputText.setText(sentence.replaceall("Hello", "Hi"));    // Replace with Your words
}catch(Exception e){
    System.out.println("Couldn't find Hello");
}

Using try-catch statements it will not check if the word is in there but if it is not there, then also it will continue and will safely pass over the statement.
What is different?
That we are not finding the required word in the sentence which will save time will longer sentences.


Q:

Numpy Problems with Arrays of poly1d Objects

I'd like to first start this out with the fact that it is possible, in numpy, to create an array of poly1d objects:
random_poly = np.frompyfunc(lambda i, j: np.poly1d(np.random.randint(1, 4, 3)), 2, 1)
def random_poly_array(shape):
    return np.fromfunction(random_poly, shape)

a1 = random_poly_array((3,3))

This works just fine, and we can even multiply matrices made from this form using np.dot:
a2 = random_poly_array((3,3))
a1_x_a2 = np.dot(a1, a2)

However, most other methods fail to work. For example, you can't take a list of certain poly1d objects and convert it into an array:
np.array([np.poly1d([1,2,3]), np.poly1d([1,2,3])])

As that will raise ValueError: cannot copy sequence with size 2 to array axis with dimension 3. To add to the confusion,
np.array([np.poly1d([1,2]), np.poly1d([1,2])])

will not raise an error, but instead create a 2x2 array of just 2's. Adding dtype=object has no affect, and numpy will still try to convert the poly1d objects to arrays.

The reason why this is problematic is that one cannot take an array of dimension d and convert it to an array of poly1d objects of dimension d-1. I would have expected
arr = np.arange(1, 10).reshape(3,3)
np.apply_along_axis(np.poly1d, 0, arr)

To return an array of poly1d objects, but instead it returns an unalterated array. Even worse, if arr=np.arange(9).reshape(3,3), it will throw an error, as the first poly1d object created will have a length of 2 instead of 3 due to the zero coefficient. Thus, my question is this: is there a feasible method to create poly1d arrays in numpy? If not, why not?

A:

Using the concept of None forcing numpy to not broadcast an object into an array, something brought to my attention by Paul Panzer, I created a function which will transform the last axis into a poly1d object:
def array_to_poly(arr):
    return np.apply_along_axis(lambda poly: [None, np.poly1d(poly)], -1, arr)[..., 1]

However, if we're okay with abusing more than one system in a single function, we can make it apply over arbitrary axes:
def array_to_poly(arr, axis=-1):
    temp_arr = np.apply_along_axis(lambda poly: [None, np.poly1d(poly)], axis, arr)
    n = temp_arr.ndim
    s = [slice(None) if i != axis%n else 1 for i in range(n)]
    return temp_arr[s]

Testing it with arr = np.arange(1, 25).reshape(2,3,4), we obtain:
In [ ]: array_to_poly(arr, 0)
Out[ ]:
array([[poly1d([ 1, 13]), poly1d([ 2, 14]), poly1d([ 3, 15]),
        poly1d([ 4, 16])],
       [poly1d([ 5, 17]), poly1d([ 6, 18]), poly1d([ 7, 19]),
        poly1d([ 8, 20])],
       [poly1d([ 9, 21]), poly1d([10, 22]), poly1d([11, 23]),
        poly1d([12, 24])]], dtype=object)

In [ ]: array_to_poly(arr, 1)
Out[ ]:
array([[poly1d([1, 5, 9]), poly1d([ 2,  6, 10]), poly1d([ 3,  7, 11]),
        poly1d([ 4,  8, 12])],
       [poly1d([13, 17, 21]), poly1d([14, 18, 22]), poly1d([15, 19, 23]),
        poly1d([16, 20, 24])]], dtype=object)

In [ ]: array_to_poly(arr, 2)
Out[ ]:
array([[poly1d([1, 2, 3, 4]), poly1d([5, 6, 7, 8]),
        poly1d([ 9, 10, 11, 12])],
       [poly1d([13, 14, 15, 16]), poly1d([17, 18, 19, 20]),
        poly1d([21, 22, 23, 24])]], dtype=object)

as expected.


Q:

boost rational_cast with rounding?

How can I do a rational_cast<int64_t> with rounding?
Currently I'm doing a hack like this:
boost::rational<int64_t> pts = ..., time_base = ...;
int64_t rounded = std::llround(boost::rational_cast<long double>(pts / time_base));

But I'd like to be able to do it "properly" without involving floating point.

A:

Rounding is inherently lossy.
The quickest hack that comes to mind is simply using the built-in behaviour (which is floor-ing or trunc-ing the result) and offset by a half:
Live On Coliru
#include <iostream>
#include <fstream>
#include <boost/rational.hpp>

int main() {
    using R = boost::rational<int64_t>;
    for (auto den : {5,6}) {
        std::cout << "---------\n";
        for (auto num : {1,2,3,4,5,6}) {
            R pq(num, den);
            std::cout << num << "/" << den << " = " << pq << ": "
                      << boost::rational_cast<int64_t>(pq + R(1,2)) << "\n";
        }
    }
}

Prints
---------
1/5 = 1/5: 0
2/5 = 2/5: 0
3/5 = 3/5: 1
4/5 = 4/5: 1
5/5 = 1/1: 1
6/5 = 6/5: 1
---------
1/6 = 1/6: 0
2/6 = 1/3: 0
3/6 = 1/2: 1
4/6 = 2/3: 1
5/6 = 5/6: 1
6/6 = 1/1: 1


Q:

Why does my iPhone select a random song when I connect my headphones?

Like many other people, I listen to music on my iPhone (6S, iOS 10.0.2) on my way to work. Since the update to iOS 10, I have noticed the following annoying behavior:
When I plug my headphones into my phone, the "Music" app selects a random song from my collection and wants to play that. It doesn't start playing it, but shows the song in the lock screen, waiting for me to press the Play button. I find this really annoying because I would expect to still be at the song that I was listening to last.
Is there a way to change this behavior to my expected behavior (the song I last listened to is selected when I insert my headphones)? From what I remember, that was the default behavior in iOS 9.

A:

This bug was introduced in iOS 10, and the same thing happens when you ask Siri to “play music,” or even if you pull up the Control Center’s playback controls.
If you Pause, then Resume only a short while later, the app remembers where you were. But leave it be for an hour or two, and it will forget. At that point it will try to shuffle your entire library when you start music playback.
If you open the Music app, it will suddenly remember which song or playlist you were playing last, and you can Play from there.
Until Apple fixes it, I’m afraid that’s the only workaround.
Edit: I haven’t encountered this issue since iOS 10.1.1.


Q:

How to configure Eclipse to compile using Oracle javac 1.7.0_09?

I am trying to compile following piece of code:
public class DuplicateMainExample {
    public static void main(String[] args) {
        System.out.print("A1");
    }

    public static void main(String... args) {
        System.out.print("A2");
    }
}

In Eclipse it's working fine, but with warnings on the both methods - "Duplicate method main(String[]) in type DuplicateMainExample"
Using javac (java version "1.7.0_09") I have an compilation error:
>javac DuplicateMainExample.java
DuplicateMainExample.java:8: error: cannot declare both main(String...) and main
(String[]) in DuplicateMainExample
        public static void main(String... args) {
                           ^
1 error

How to compile in Eclipse using javac?

A:

Simply because you have declared the same method with exactly the same signature twice ... Only one main method for class should be declared .
Eclipse have embedded its own compiler and in the case of two main methods it gets the last one, the eclipse compiler and the javac compiler are two different compilers ...
Take a look at this older post for more information ...
If you want to compile with javac you could try using the ant javac adapter from within eclipse ... However i think that ECJ is even better than javac(my opinion) ...

A:

Eclipse will never use javac. Its ability to do dynamic highlighting is intimately connected with its own compiler, which has special abilities to operate incrementally.
If you want an IDE that uses javac, you might investigate intellij.


Q:

What would it look like inside an Alcubierre field?

For the purpose of this questions, let's assume my crew has solved all those nasty problems of survivability inside the field, not unleashing a devastating blast of particles at their destination, and energy requirements.
What would the solar system look like to someone inside the ship while the Drive was active? If they for some reason decided to look at the Sun through a window, what would they see travelling away from it? Would they even be able to see anything at all?

A:

According to wikipedia (which is more than sufficient for a layman-level discussion, hard-science or otherwise):

The Alcubierre drive [...] is a speculative idea [...] by which a spacecraft could achieve apparent faster-than-light travel [...].
Rather than exceeding the speed of light within a local reference frame, a spacecraft would traverse distances by contracting space in front of it and expanding space behind it, resulting in effective faster-than-light travel.

When I was getting my degree in physics (almost two decades ago), I wrote a paper on the visual effects of near-luminous travel.  While this isn't the same thing, there are two similar circumstances that immediately leap out at me - both dealing with changes in angles: shape and color.
First, the shape of things changes.  The more the space ahead of you contracts (and the space behind you expands), the 'smaller' things ahead of you look and the 'bigger' the things behind you appear.  Angles of objects slightly off-center ahead contract until - at some limit - they appear directly ahead; the more contraction of space, the tighter the new angle.  For instance, if you are heading straight for a very large object (a galaxy, for instance, so we don't run into it right away), and it forms a rough circle directly ahead, the more the space contracts, the smaller that circle will be as the center remains unchanged by the edges contract in.  A similar, but reversed, effect happens to objects behind you: they expand the 'cone' from you to them.  A circular galaxy directly behind you will expand as the center remains unchanged by the edges all widen.  At extremes, things directly behind you will seem to be 'swallowing' you as the angles pass 90°...
Second, the color of things changes, too.  The very wavelength of light undergoes the same contraction (ahead) and expansion (behind).  Wavelength of light affects, among other things, color - so things ahead of you will tend to "blueshift" and things behind you will tend to "redshift."  At smaller 'levels' of contraction and expansion, this would just make things look weird... but the electromagnetic spectrum is more than just the visual spectrum.  At extremes, things behind you will shift beyond red into the infrared then micro- and radio waves, and things ahead of you will shift beyond blue into the ultraviolet then into ionizing radiation.  Hopefully, your culture that has invented a working FTL drive understands that they'll need radiation shielding...
For near-luminous travel, these two effects don't start becoming really interesting until you hit something like 0.99999c, though they'll be visible to the naked eye long before that.  The question then, becomes, how much "contracting" and "expanding" of space you're doing in your drive.  (I'd provide equations, but I'd have to dig them out of a box in the basement - and while they don't require anything too nasty math-wise, they do involve four-dimensional vector matrices, which gives mathphobes nightmares.  I haven't touched this stuff in close to two decades, so I'd rather not try to wrap my head around the actual physics - just the high-level layman descriptions.)


Q:

How can I connect Mathematica to Clojure?

I'm using Clojure and I'd really love to be able to use some of Mathematica's functions inside it. Can anyone help with mathlinking it?

A:

To call Mathematica from Clojure, you will want to use Clojure's Java interop to access the Wolfram JLink classes to script Mathematica access.
Start by launching Clojure with a classpath that includes the JLink.jar, for example with this batch file:
@echo off
set MATHEMATICA=C:/M/9.0
set JLINKJAR=%MATHEMATICA%/SystemFiles/Links/JLink/JLink.jar
java -cp C:/Apps/clojure-1.4.0/clojure-1.4.0.jar;%JLINKJAR% clojure.main

Once inside Clojure, use the Java interop syntax to access JLink classes as described in the tutorial Writing Java Programs that Use Mathematica. Typically this starts by launching a kernel with the MathLinkFactory to obtain a KernelLink:
user=> (def kl (com.wolfram.jlink.MathLinkFactory/createKernelLink "-linkmode launch -linkname 'c:/M/9.0/math.exe -mathlink'"))
#'user/kl

Then discard the initial input packet from the kernel:
user=> (.discardAnswer kl)
nil

We can now perform evaluations of Mathematica code:
user=> (.evaluate kl "1+1")
nil
user=> (.waitForAnswer kl)
3
user=> (.getInteger kl)
2

When retrieving results from an evaluation, you need to know what type to expect, or you need to retrieve the result as a string and parse it.
Here's one way to evaluate a Mathematica expression that returns a list of integers and get the vector in Clojure:
user=> (.evaluate kl "RandomInteger[{0,99},20]")
nil
user=> (.waitForAnswer kl)
3
user=> (def res (vec (.getIntArray1 kl)))
#'user/res
user=> res
[91 12 98 20 71 43 59 64 98 64 20 93 32 84 41 90 38 27 51 76]

There's also a presentation by Seth Chandler on connecting Mathematica to Clojure: J/Link without Java

A:

I did not try it yet, but Clojuratica may be what you need. The project seems to no longer be maintained though (although I may be wrong). No idea how much of a problem this is, given changes in the Clojure since the time Clojuratica was released.
Of course, Seth's talk was also great and is a great resource as well, as Joel mentioned.


Q:

How do I toggle a cell class in a shiny DT datatable?

Using Shiny and DT, I want to trigger an event for specific cells in a  datatable. Suppose I want the first column to turn red on hover. When I create the table I add a callback that registers a hover event on the td elements in the first column.
library(shiny)
library(DT)

ui <- fluidPage(
  tags$head(tags$style(HTML(".red { background-color: red; }"))),
  DT::dataTableOutput("iris")
)

server <- function(input, output) {
  output$iris <- DT::renderDataTable(DT::datatable(iris, callback = JS("
table.column(0).nodes().to$().hover(function(){$(this).toggleClass('red');});
")))
}

shinyApp(ui = ui, server = server)

From the javascript console if I run the identical code it works :
table=$('#DataTables_Table_0').DataTable()
table.column(0).nodes().to$().hover(function(){$(this).toggleClass('red');});

Why doesn't this work in the datatable callback? What is the right way to do this?

A:

Usually when you see this sort of behaviour, it suggests a timing issue. The callback is being called back before the table is fully rendered, the the columns you want to operate on don't exist just quite yet.
Remove the callback option and use options = list( drawCallback = JS(...) ) instead.
DT::datatable(
  iris,
  options = list(
    drawCallback = JS('function() {this.api().table().column(0).nodes().to$().hover(function(){$(this).toggleClass("red")}) }')
  )
)


Q:

Numbering Items in Scrapy

So I have an items.py with the following:
class ScrapyItem(scrapy.Item):
    source = scrapy.Field()
    link = scrapy.Field()

and the json output is:
[{"source": "Some source", "link":"www.somelink.com"},
 {"source": "Some source again", "link":"www.somelink.org"}]

is there a way change the output to:
[{"source1": "Some source", "link1":"www.somelink.com"},
 {"source2": "Some source again", "link2":"www.somelink.org"}]

From the docs, I saw you can manipulate the item values, can you do the same to the items themselves?
EDIT
Here's the new code I'm using for the output with an article_id item_field
article_id = [1]
def parse_common(self, response):
    feed = feedparser.parse(response.body)
    for entry_n, entry in enumerate(feed.entries, start=article_id[-1]):
        try:
            item = NewsbyteItem()
            item['source'] = response.url
            item['title'] = lxml.html.fromstring(entry.title).text
            item['link'] = entry.link
            item['description'] = entry.description
            item['article_id'] = '%d' % entry_n
            article_id.append(entry_n)
            request = Request(
                entry.link,
                callback=getattr(self, response.meta['method']),
                dont_filter=response.meta.get('dont_filter', False)
            )

            request.meta['item'] = item
            request.meta['entry'] = entry

            yield request
        except Exception as e:
            print '%s: %s' % (type(e), e)
            print entry

The problem is the entry_n restarts whenever it changes to another url. That's why the list was used.

A:

I don't recommend you to identify different items changing the key of your item's values. You can do instead a dictionary with naming the responses doing something like:
output = [{"source": "Some source", "link":"www.somelink.com"}, {"source": "Some source again", "link":"www.somelink.org"}]
output_dict = {}
for counter, item in enumerate(output):
    output_dict['item' + str(counter + 1)] = item
print output_dict

A:

From the discussion

The purpose of the identifier is if an item has some data missing or includes data that isn't needed, I can find that dictionary right away and refactor the code accordingly.

With that purpose in mind, I'd suggest to generate UUIDs. Same effect, less hassle:
# item definition
class ScrapyItem(scrapy.Item):
    source = scrapy.Field()
    link = scrapy.Field()
    uuid = scrapy.Field()
# processing
def parse_common(self, response):
    ...
    item['uuid'] = uuid.uuid4()
    ...


Q:

How do i use AWS-lambda to create csv file from json data?

Problem:
I have a json data filtered out from security groups with respect to my requirements which i want to save into .csv file.
My Research effort:
I have done it in pycharm where i am storing it to my local drive using the following code :
def store_details_in_csv(jsondata):
    file_path = os.path.dirname(__file__) + "/security.csv"
    with open(file_path, "a") as export:
        names = ['Account Number', 'Account Name', 'Region', 'SG', 'Inbound port', 'Inbound IP', 'Assessment']
        writer = csv.DictWriter(export, fieldnames=names)
        writer.writeheader()
        for security_group in jsondata['SecurityGroups']:
            groupId = security_group["GroupId"]
            for inboundEntry in security_group["InboundDetails"]:
                inboundPort = inboundEntry['port']
                inboundIP = inboundEntry['source']
                assessment = inboundEntry['assessment']
                writer.writerow({'Account Number': ACCOUNT_NUMBER, 'Account Name': ACCOUNT_NAME, 'Region': REGION,
                                 'SG': groupId, 'Inbound port': inboundPort,
                                 'Inbound IP': inboundIP, 'Assessment': assessment})

NOW,
How do i use AWS-lambda to create csv file from json data ?

A:

Here, I attach the lambda code for saving csv into S3 without temp files.
import boto3
import csv
import io

s3 = boto3.client('s3')
ec2 = boto3.client('ec2')

def lambda_handler(event, context):
    csvio = io.StringIO()
    writer = csv.writer(csvio)
    writer.writerow(['id', 'name'])

    paginator = ec2.get_paginator('describe_security_groups').paginate()

    for page in paginator:
        for item in page['SecurityGroups']:
            identity = item['GroupId']
            name = item['GroupName']

            writer.writerow([identity, name])

    s3.put_object(Body=csvio.getvalue(), ContentType='text/csv', Bucket='<bucket>', Key='<filename.csv>')
    csvio.close()

You can modify this for your usa case.


Q:

AvS_FastSimpleImport > How to import multiple product rows and images

Sorry for the probably simple question, but I am new to both Magento and Fast Simple Import.
The plugin works great for single products with single properties and single images. But I ofcoarse want more colors, more images, etc. etc. What is the best way to do this? I searched the trough the docs and Google, but couldn't find a working example (or answer).
This is what I have right now:
$data[] = array(
    // Main product
    'sku' => $randomString,
    '_type' => 'simple',
    '_attribute_set' => 'Default',
    '_product_websites' => 'base',
    '_category' => array(1, 3),

    // Product per row
    'name' => "Wikitest",
    'price' => 0.99,
    'special_price' => 0.90,
    'cost' => 0.50,
    'description' => 'Default',
    'short_description' => 'Default',
    'meta_title' => 'Default',
    'meta_description' => 'Default',
    'meta_keyword' => 'Default',
    'weight' => 11,
    'status' => 1,
    'visibility' => 4,
    'tax_class_id' => 2,
    'qty' => 0,
    'is_in_stock' => 0,
    'enable_googlecheckout' => '1',
    'gift_message_available' => '0',
    'url_key' => strtolower($randomString),

// Images

    // Image 1
    array('_media_image' => 'http://upload.wikimedia.org/wikipedia/meta/6/6d/Wikipedia_wordmark_1x.png',
    '_media_target_filename' => 'wikipedia.jpg',
    'image' => 'wikipedia.jpg',
    'small_image' => 'wikipedia.jpg',
    'thumbnail' => 'wikipedia.jpg')

    // Image 2
    '_media_image' => 'http://upload.wikimedia.org/wikipedia/meta/6/6d/Wikipedia_wordmark_1x.png',
    '_media_target_filename' => 'wikipedia2.jpg',
    'image' => 'wikipedia2.jpg',
    'small_image' => 'wikipedia2.jpg',
    'thumbnail' => 'wikipedia2.jpg',

);

What happens in above example is that I only upload / attach one image to the product. Also, when i add extra colors qty etc it will create multiple products or crash on duplicate SKU.
Second question, I am importing from an XML and CSV feed. Is there some best practise to turn an XML / CSV into an array? I can write something myself, but I guess something is already available. If not, tips are welcome as well.
Thanks all!

A:

Option 1: Use AvS_FastSimpleImport directly;
http://avstudnitz.github.io/AvS_FastSimpleImport/options.html
Set the option 'Support Nested Arrays for Import' to Yes and use the nested arrays. Example:
$data = array(
    array(
        'sku' => '1234567',
        '_type' => 'simple',
        '_attribute_set' => 'Default',
        '_product_websites' => array('de', 'en', 'fr'),
        'name' => 'Default',
        'price' => 0.99,
        'description' => 'Default',
        'short_description' => 'Default',
        'colors' => array('green', 'silver')
        'weight' => 0,
        'status' => 1,
        'visibility' => 4,
        'tax_class_id' => 2,
        'qty' => 76,
    ),
);

Option 2:
To transform files to a different format, I personally use https://github.com/ho-nl/Ho_Import, others use https://github.com/AOEmedia/Aoe_Import. Where Ho_Import offers download options etc, Aoe_Import is multi threaded and has better logic for parsing XML.


Q:

Php Variable in loop is not returning the values I want in html

I want to echo 4 lines of code. The variable $x shall be 1,2,3,4 and the variable $y shall be 3,4,5,6.
The $x variable in my loop works fine, the $y however doesn't work like I want it (so it echoes 3,4,5,6 later in HTML)
So my question is: Why is the $y variable not returning 3,4,5,6 in my final HTML code.
for ($x=0; $x<=3;$x++) {
$y=3;
if (${"interferer" .$x} == true) {
  echo "
Interferer $x
";
}
else {
  echo "";

}
$y++;
}

A:

you're setting $y=3; every time, it will never increment.
Try moving $y=3; outside the for loop.


Q:

How do I convert response.body from Vapor to String in Swift 3?

I'm using Vapor to try to get an XML file from another server, the problem is I don't know how to convert the response body to a swift String.
let bikesResponse = try drop.client.get("http://www.c-bike.com.tw/xml/stationlistopendata.aspx")

let bodyBytes = bikesResponse.body
let string = String(bytes) // <-- WHAT DO I DO HERE?

Thanks

A:

Ah, ok I figured it out eventually.
let bikesResponse = try drop.client.get("http://www.c-bike.com.tw/xml/stationlistopendata.aspx")

if let bodyBytes = bikesResponse.body.bytes {

    let string = String(bytes: bodyBytes, encoding: String.Encoding.utf8) {

}


Q:

System dir call to network drive prunes file path

Apologies in advance for not being able to provide a completely reproducible example, not everyone is going to have a network drive to experiment with.
I have a processing function that I'm using to perform data reduction and our data is stored on a network drive. while debugging this morning I discovered something strange (to me) and I'm curious to know why Windows (Win7, 64 bit) behaves this way. My Google-fu has been defeated.
As an example, say I have this file structure on \\mynetworkshare
\\mynetworkshare\testdata\a
\\mynetworkshare\testdata\b
\\mynetworkshare\testdata\c
\\mynetworkshare\testdata\c\day1
\\mynetworkshare\testdata\c\day2

With somedatafile_n.abc in each of the day folders.
My function parses through the user specified folder, c in this case, and looks for all of the data files that match the filter:
searchpath = '\\mynetworkshare\testdata\c'
oldpath = cd(searchpath); % cd to data directory for simpler dir call
[~, filenames] = system('dir /S /B somedatafile_*.abc');
filelist = regexp(filenames, '(.:\\[\w\-\\. ]+\.\w+)', 'match'); % Split filenames
cd(oldpath);

This returns a cell array of filenames:
Z:\day1\somedatafile_1.abc
Z:\day1\somedatafile_2.abc
Z:\day2\somedatafile_1.abc

However, these are not valid paths to use with low level I/O:
Error using textscan
Invalid file identifier. Use fopen to generate a valid file identifier.

It should be noted that this functions correctly if I mount the network drive and use that path instead:
searchpath = 'H:\testdata\c'
oldpath = cd(searchpath); % cd to data directory for simpler dir call
[~, filenames] = system('dir /S /B somedatafile_*.abc');
filelist = regexp(filenames, '(.:\\[\w\-\\. ]+\.\w+)', 'match'); % Split filenames
cd(oldpath);

Which returns:
H:\testdata\c\day1\somedatafile_1.abc
H:\testdata\c\day1\somedatafile_2.abc
H:\testdata\c\day2\somedatafile_1.abc

A:

From https://www.mathworks.com/help/matlab/ref/system.html
DOS does not support UNC path names. Therefore, if the current folder uses a UNC path name, then running system with a DOS command that relies on the current folder fails. To work around this limitation, change the folder to a mapped drive before calling system.
system('net use Z: \\mynetworkshare\testdata\c')
cd('Z:\')
fileID = fopen('day1\somedatafile_1.abc');
C = textscan(fileID,'%s %s %f32 %d8 %u %f %f %s %f');
fclose(fileID);


Q:

Checking if a string contains a dot

Today I was trying to detect if a string contains a dot, but my code isn't working
 String s = "test.test";
 if(s.contains("\\.")) {
     System.out.printLn("string contains dot");
 }

A:

contains() method of String class does not take regular expression as a parameter, it takes normal text.
String s = "test.test";

if(s.contains("."))
{
    System.out.println("string contains dot");
}

A:

String#contains receives a plain CharacterSequence e.g. a String, not a regex. Remove the \\ from there.
String s = "test.test";
if (s.contains(".")) {
    System.out.println("string contains dot");
}

A:

You only need
s.contains (".");


Q:

PowerApps - Change Border Color of Form

I've added a form to a PowerApp by clicking "Insert" >
"Form" > "Edit" and I would like to add "Hover border color" so when the user hovers, they see a border. However, when I click the button to do so, it just shows me this in the formula bar:

What am I supposed to do with this? (read: "how am I supposed to modify this to change the border color?") I looked for some documentation online, but can't find anything about syntax or the actual language that is used here. I'm not looking to spend x number of hours going through a walkthrough just to change a border color so I'm hoping someone already knows how to do this.

A:

how am I supposed to modify this to change the border color?

Properties of controls in PowerApps can have either constant values, or expressions that reference other properties. For example, your control's hover border color is referencing the border color (I'm assuming of the same control), so if you look at the BorderColor property you'll find some expression that defines the color.
For the specific case of colors, the "constant" values you can use are either from the Color enumeration, or a color name from CSS, or a custom color using the RGBA function.
For example, if you want to set your hover border color to blue, you can use Color.Blue or RGBA(255, 0, 0, 1).


Q:

Assert Current fallback trait collection contains one or more unspecified traits:

Once our app is run on iOS13 then the log is full of wried assertions. Anybody some tips how to remove it?
2019-09-19 08:05:43.528382+0200 Ts-2-cz-test[56066:20590106] [Assert] Current fallback trait collection contains one or more unspecified traits: {(
    "_UITraitNameDisplayScale",
    "_UITraitNameDisplayCornerRadius",
    "_UITraitNameSemanticContext",
    "_UITraitNameUserInterfaceLevel",
    "_UITraitNamePresentationSemanticContext",
    "_UITraitNameVibrancy",
    "_UITraitNameDisplayGamut",
    "_UITraitNameDebugHighlight",
    "_UITraitNamePreferredContentSizeCategory",
    "_UITraitNameTouchLevel",
    "_UITraitNameAccessibilityContrast",
    "_UITraitNameLegibilityWeight"
)}; traitCollection: <UITraitCollection: 0x7fb4ce32ad20; HorizontalSizeClass = Compact>; currentFallbackEnvironment: <UIView: 0x7fb46c421d80; frame = (0 0; 1024 1366); autoresize = W+H; layer = <CALayer: 0x7fb46c421ef0>>

A:

I had the same issue here because I was overriding the traitCollection property (which is not recommended by Apple but I didn't find any other solution in my case) and the new traitCollection I returned has many unspecified traits (as the error message said).
So now I return a new traitCollection object but I initialize it by adding super.traitCollection. So in my view controller I have something like:
public override var traitCollection: UITraitCollection {
    var newTraitCollection: [UITraitCollection] = [super.traitCollection]
    // I need to force size class on iPad
    if UIDevice.current.userInterfaceIdiom == .pad {
        newTraitCollection += [UITraitCollection(verticalSizeClass: .regular), UITraitCollection(horizontalSizeClass: .compact)]
    }
    return UITraitCollection(traitsFrom: newTraitCollection)
}


Q:

await method causing incompatibleClassChangeError: implementing class

I'm using play-1.2.5. For async I'm using await() method in my controller. but that await() causing IncompatibleClassChangeError during my application startup. I really don't understand the reason.
when I comment await() line, that error gone away.
here is my Contoller action:
public static void loadScheduledConfigs() {
    Future<JsonObject> future = Startup.THREAD_POOL.submit(new MyCallable());
    JsonObject object = null;
    /*
    I also tried this
        Future<JsonObject> future =  new FutureTask<JsonObject>( new MyCallable());
        JsonObject object =  await(future);
    */
    try{
        object = future.get();
    }catch(Exception e) {
        log.error(e.getMessage(), e);
    }
    renderJSON(object);
}

Exception:
Oops: IncompatibleClassChangeError
An unexpected error occured caused by exception IncompatibleClassChangeError: Implementing class

play.exceptions.UnexpectedException: Unexpected Error
    at play.Invoker$Invocation.onException(Invoker.java:244) ~[play-1.2.5rc4.jar:na]
    at play.Invoker$Invocation.run(Invoker.java:286) ~[play-1.2.5rc4.jar:na]
    at Invocation.HTTP Request(Play!) ~[na:na]
Caused by: java.lang.IncompatibleClassChangeError: Implementing class
    at java.lang.ClassLoader.defineClass1(Native Method) ~[na:1.7.0_07]
    at java.lang.ClassLoader.defineClass(ClassLoader.java:791) ~[na:1.7.0_07]
    at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:142) ~[na:1.7.0_07]
    at java.net.URLClassLoader.defineClass(URLClassLoader.java:449) ~[na:1.7.0_07]
    at java.net.URLClassLoader.access$100(URLClassLoader.java:71) ~[na:1.7.0_07]
    at java.net.URLClassLoader$1.run(URLClassLoader.java:361) ~[na:1.7.0_07]
    at java.net.URLClassLoader$1.run(URLClassLoader.java:355) ~[na:1.7.0_07]
    at java.security.AccessController.doPrivileged(Native Method) ~[na:1.7.0_07]
    at java.net.URLClassLoader.findClass(URLClassLoader.java:354) ~[na:1.7.0_07]
    at java.lang.ClassLoader.loadClass(ClassLoader.java:423) ~[na:1.7.0_07]
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308) ~[na:1.7.0_07]
    at java.lang.ClassLoader.loadClass(ClassLoader.java:356) ~[na:1.7.0_07]
    at java.lang.ClassLoader.defineClass1(Native Method) ~[na:1.7.0_07]
    at java.lang.ClassLoader.defineClass(ClassLoader.java:791) ~[na:1.7.0_07]
    at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:142) ~[na:1.7.0_07]
    at java.net.URLClassLoader.defineClass(URLClassLoader.java:449) ~[na:1.7.0_07]
    at java.net.URLClassLoader.access$100(URLClassLoader.java:71) ~[na:1.7.0_07]
    at java.net.URLClassLoader$1.run(URLClassLoader.java:361) ~[na:1.7.0_07]
    at java.net.URLClassLoader$1.run(URLClassLoader.java:355) ~[na:1.7.0_07]
    at java.security.AccessController.doPrivileged(Native Method) ~[na:1.7.0_07]
    at java.net.URLClassLoader.findClass(URLClassLoader.java:354) ~[na:1.7.0_07]
    at java.lang.ClassLoader.loadClass(ClassLoader.java:423) ~[na:1.7.0_07]
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308) ~[na:1.7.0_07]
    at java.lang.ClassLoader.loadClass(ClassLoader.java:356) ~[na:1.7.0_07]
    at play.classloading.enhancers.ContinuationEnhancer.enhanceThisClass(ContinuationEnhancer.java:74) ~[play-1.2.5rc4.jar:na]
    at play.CorePlugin.enhance(CorePlugin.java:297) ~[play-1.2.5rc4.jar:na]
    at play.plugins.PluginCollection.enhance(PluginCollection.java:551) ~[play-1.2.5rc4.jar:na]
    at play.classloading.ApplicationClasses$ApplicationClass.enhance(ApplicationClasses.java:235) ~[play-1.2.5rc4.jar:na]
    at play.classloading.ApplicationClassloader.loadApplicationClass(ApplicationClassloader.java:167) ~[play-1.2.5rc4.jar:na]
    at play.classloading.ApplicationClassloader.getAllClasses(ApplicationClassloader.java:431) ~[play-1.2.5rc4.jar:na]
    at play.Play.start(Play.java:516) ~[play-1.2.5rc4.jar:na]
    at play.Play.detectChanges(Play.java:642) ~[play-1.2.5rc4.jar:na]
    at play.Invoker$Invocation.init(Invoker.java:198) ~[play-1.2.5rc4.jar:na]
    ... 1 common frames omitted

I don't know either problem is in the way I code, or some dependencies comflict causing this issue. (I checked my lib folder and classpath/dependencies of my project, I did not find any conflicting library)

A:

I got the solution. it's asm.jar who was creating issue. I'm using kryo for serialization. kryo and play both has asm.jar as a dependency. So i have two different version of asm.jar in my class path. one that comes with kryo and other one that comes with play framework. that was causing issue.
I removed one asm.jar and that exception gone away.


Q:

Recursively searching up a node tree

Scenario: I have an unordered list of list items's. In each list item is a span and in each span is an img tag. So my html structure looks like this.

The img tags are just tiny square colour swatches, and the spans are styled into circles so what you have is basically a colour picker of three coloured dots for the user to click on.
When a user clicks on the li, I'm using javascript to grab the data-previews so that I can use that information to change a picture. This works perfectly if the user clicks slightly outside the circle. However, if they click inside the circle, they end up click on the img tag. But the data I need is two parent nodes up in the li tag!
So I wrote a recursive function to address this.
function findUpTag(el, tag) {
  console.log(el.tagName, tag);
    if (el.tagName === tag) {
      console.log("success!", el);
      return el;
    } else {
      findUpTag(el.parentNode, tag);
    }
}

I use it like so findUpTag(el, "LI");
I know my recursive search is working because I always get the console.log("success") output when the current element === "LI".
However, my return value when I click on the image tag is always undefined! Even when my method finds the LI!
What am I doing wrong?

A:

It's because you're not returning the result of the recursive call. You also need to handle the case of el.parentNode being null:
function findUpTag(el, tag) {
  console.log(el.tagName, tag);
    if (el.tagName === tag) {
      console.log("success!", el);
      return el;
    } else {
      return el.parentNode ? findUpTag(el.parentNode, tag) : null; // <====
    }
}

FWIW, while you can use recursion for this, there's no need to; there's only one path up the tree. So it could just be a simple loop:
function findUpTag(el, tag) {
  while (el) {
    if (el.tagName === tag) {
      console.log("success!", el);
      return el;
    }
    el = el.parentNode;
  }
  return null;
}


Q:

RecyclerView does not display items - Android

I'm trying to use a RecyclerView to have a variable number of players in a game. The number of players is set by an extra passed with the intent on loading this activity. The objective is to have "Player #X : EditText" for every player to insert his name, to catch those names and send them onto a new activity.
The problem I am facing is that the RecyclerView does not seem to work. When loading the activity, there are no textviews or edit zones, juste a white screen. The bottom Button is working fine though. I can see the "zone" created for the RecyclerView by pulling up and down, it shows the blue "end of page" markers.
Here is the code, if you could help me figure out what happened :
Activity (java)
package com.olirwin.spartacus.deutsch;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import java.util.ArrayList;

public class players extends AppCompatActivity {

ArrayList<String> playerNames;
Button send;
PlayerAdapter Adapter;
RecyclerView playerList;
String[] names;

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

    playerNames = new ArrayList<String>();

    final ArrayList<Player> players = new ArrayList<Player>();
    send = findViewById(R.id.b_send);

    Bundle extra = new Bundle();
    final int numPlayers = extra.getInt("num");

    for (int i = 0; i < numPlayers; i++)
    {
        playerNames.add("Joueur " + (i+1) + " : ");
    }
    playerList = findViewById(R.id.player_list);
    playerList.setLayoutManager(new LinearLayoutManager(this));
    Adapter = new PlayerAdapter();
    playerList.setAdapter(Adapter);
    names = new String[numPlayers];

    Adapter.notifyDataSetChanged();

    send.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            for (int i = 0; i < numPlayers; i++) {
                players.add(new Player(names[i]));
            }

            Intent intent = new Intent(view.getContext(), Score.class);
            intent.putExtra("players", players);
            view.getContext().startActivity(intent);
        }
    });

}

private class PlayerAdapter extends
RecyclerView.Adapter<PlayerAdapter.PlayerHolder> {

    @Override
    public PlayerHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View v =
LayoutInflater.from(players.this).inflate(R.layout.list_cell, parent,
false);
        return new PlayerHolder(v);
    }

    @Override
    public void onBindViewHolder(PlayerHolder holder, final int position) {
        holder.bind(playerNames.get(position));

        holder.mPlayerName.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int
start, int before,
                                          int count) {
                names[position] = charSequence.toString();
            }

            @Override
            public void onTextChanged(CharSequence charSequence, int start,
int before,
                                      int count){

            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });

    }

    @Override
    public int getItemCount() {
        return playerNames.size();
    }

    public class PlayerHolder extends RecyclerView.ViewHolder {

        TextView mPlayerLabel;
        EditText mPlayerName;

        public PlayerHolder(View itemView) {
            super(itemView);
            mPlayerLabel = itemView.findViewById(R.id.player_label);
            mPlayerName = itemView.findViewById(R.id.player_name);
        }

        public void bind(String playerName) {
            mPlayerLabel.setText(playerName);
            mPlayerName.setHint("Nom de " + playerName);
        }

        public String getData(){
            return mPlayerName.getText().toString();
        }

    }
}
}

Layout
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.olirwin.spartacus.deutsch.players">

<android.support.v7.widget.RecyclerView
    android:id="@+id/player_list"
    android:layout_width="0dp"
    android:layout_height="476dp"
    android:layout_marginBottom="8dp"
    android:layout_marginEnd="8dp"
    android:layout_marginStart="8dp"
    android:layout_marginTop="8dp"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintHorizontal_bias="0.0"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    app:layout_constraintVertical_bias="0.0" />

<Button
    android:id="@+id/b_send"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center_horizontal"
    android:layout_marginBottom="8dp"
    android:layout_marginEnd="8dp"

    android:layout_marginStart="8dp"
    android:layout_marginTop="8dp"
    android:text="Valider"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toBottomOf="@+id/player_list" />

</android.support.constraint.ConstraintLayout>

A:

The problem is in your custom adapter constructor you are not even passing data in list to populate!
try to learn debugging it will make your life more easier.!
 Adapter = new PlayerAdapter(playerNames,context);

private class PlayerAdapter extends
RecyclerView.Adapter<PlayerAdapter.PlayerHolder> {

ArrayList<String> playerNames;

Context context;

   public PlayerAdapter (ArrayList<String> arrayList, Context context) {
            playerNames= arrayList;
            context = context;
        }

    @Override
    public PlayerHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View v =
LayoutInflater.from(players.this).inflate(R.layout.list_cell, parent,
false);
        return new PlayerHolder(v);
    }

}


Q:

.NET Label Appearance TextAlign: MiddleRight problem

I'm having trouble right aligning a label.
I set the TextAlign to MiddleRight, yet when I change the text of the label the label autogrows right.
Is TextAlign the correct parameter for setting the desigered behavior?
Is there a way to fix the problem other than using a TableLayoutPanel?

A:

If the AutoSize property is set to true, then the text alignment will be meaningless (since text alignment determines where within the control boundaries that the text is drawn, but if the control is always the exact size of the text then it's always going to be in the same place, regardless of alignment).
It sounds like what you need to do is disable AutoSize and set the label to the desired size and the desired text alignment.