text:
Q: Matching a color in SVG with feColorMatrix I created a drop shadow in SVG using SourceAlpha for the shadow, so its plain black. Using feColorMatrix I reduced the opacity a bit, but still it wasn't looking as I wanted - I want the color of the shadow to match a specific color value. So I took a more in depth look at feColorMatrix.
Now I don't use SourceAlpha as source for the shadow, but SourceGraphic. As my vector image is plain white aka rgba(255, 255, 255, 1), I can calculate the color of the shadow like that:
<feColorMatrix in="the-shadow" result="color-out" type="matrix"
                values="0.0157 0      0      0 0
                        0      0.3059 0      0 0
                        0      0      0.7765 0 0
                        0      0      0      1 0  "/>

The outcome should be a dark blue shadow aka rgba(4, 78, 198, 1).
Actually this is working and I believe the calculations are all correct, but when creating a shadow with CSS3 using the same color, there is a noticeable difference: The SVG filter seems to render the color a bit too light. Is there any way to fix that?

A: feColorMatrix like most filters operates in the linearRGB colour space. If you want an sRGB colour, Try setting color-interpolation-filters="sRGB" as an attribute on the feColorMatrix.

    <svg width="100%" xmlns:xlink="http://www.w3.org/1999/xlink"

    viewBox="0 0 640 480" height="100%"
    xmlns="http://www.w3.org/2000/svg">

    <filter id="cm">

    <feColorMatrix in="SourceGraphic" type="matrix"
                    values="0.0157 0      0      0 0
                            0      0.3059 0      0 0
                            0      0      0.7765 0 0
                            0      0      0      1 0  "/>

    </filter>

    <filter id="cmRGB">

    <feColorMatrix color-interpolation-filters="sRGB" in="SourceGraphic" type="matrix"
                    values="0.0157 0      0      0 0
                            0      0.3059 0      0 0
                            0      0      0.7765 0 0
                            0      0      0      1 0  "/>

    </filter>

    <rect width="100%" height="50%" fill="white" filter="url(#cm)"/>

    <rect y="50%" width="100%" height="100%" fill="white" filter="url(#cmRGB)"/>

    </svg>

It sure looks different to me on Firefox.

A: Whilst my answer repeats the same idea, what I have to add is too much for a comment.
I don't know for sure, what is linearRGB in the standard, but I expect it to be, erm, linear. I.e. white color transformed with (darken-twice)
R | ½ 0 0 0 0
G | 0 ½ 0 0 0
B | 0 0 ½ 0 0
A | 0 0 0 1 0

should result in the same color as rgb(50%, 50%, 50%), shouldn't it?
As well as black color transformed with (ligthen-twice)
R | ½ 0 0 0 ½
G | 0 ½ 0 0 ½
B | 0 0 ½ 0 ½
A | 0 0 0 1 0

expected to be the same 50% gray.
But what I actually see as a result is much lighter than expected, color picker shows #BCBCBC instead of #808080. On the other hand, color-interpolation-filters="sRGB" makes the result correct (checked a macbook and a win10 ASUS notebook with default settings).
https://jsfiddle.net/7wvy57fq/2/


text:
Q: Parsing html to retrieve data with no Tag I have this html as show below; I would like to use JSOUP to retrieve TEXT 1 and TEXT 2.

    <title>TITLE</title>

Subheading 1

              TEXT 1

 Subheading 2

              TEXT 2

I really do not know how to call it because it doesn't have tags or id. Please help.

A: I have never used JSOUP but from a brief look at the documentation (JSOUP Documentation), you should be able to use standard javascript methods to navigate so doing something like
Document doc = Jsoup.connect("http://example.com/").get();
Elements headings = doc.getElementsByTag("h3");
for (Element heading : headings) {
   Element text=heading.nextElementSibling();
   String value=text.text();
}

Then value should have what you want. Note this is not tested and is just based on the documentation.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Aligning table to bottom of page in a multi-column environment This is a follow-up question to Aligning table to bottom of page. I have a two-column document consisting of text and tables. Sometimes the tables appear at the bottom of a column.
\documentclass[10pt]{book}
\usepackage[showframe]{geometry}
\usepackage{blindtext}
\usepackage{multicol}
\begin{document}
\begin{multicols*}{2}
\noindent\blindtext\par
\blindtext
\par\mbox{}\par
\begin{tabular}{|c|c|c|}\hline
    A & B & C \\\hline
    D & E & F \\\hline
    G & H & I \\\hline
    J & K & L \\\hline
    M & N & O \\\hline
    Q & R & S \\\hline
    T & U & V \\\hline
    W & X & Y \\\hline
    Z &   &   \\\hline
    A & B & C \\\hline
\end{tabular}
\columnbreak
\par
\blindtext\par
\blindtext\par
\end{multicols*}
\end{document}

This is the result:
As you can see, the content of the last row of the table (A, B and C) aligns with the page frame. Is there a way to align the bottom line of the table with the page frame, i.e. lift the table up just a little bit? As far as I know, I cannot use the table environment inside a multi-column environment ; if I could, the problem would be solved.

A: As suggested by user campa in a comment to my question, adding [b] does the trick. I didn't realize you could add that to tabular as well. I though it's only available if you wrap tabular inside a table environment.


text:
Q: Dynamics of counter-rotating flywheels I've wondered about this for ages.  If we create a pair of flywheels that rotate in the opposite direction with the same angular momentum, but are co-located and have the same mass and inertial moment (one can imagine various ways to accomplish this, at least approximately) -- it is clear to me that there cannot be any precession forces, but, if we try to rotate the entire assembly around an axis perpendicular to the axis of flywheel rotation, will the force needed to produce this secondary rotation be the same as if the flywheels were stationary, or will it require a proportionally greater force to rotate in this way, as it does with a single flywheel?

A: two concentric and counterrotating flywheels preclude all precession forces regardless of which plane the axis is rotated in. this is assuming the connection between the two flywheels is sufficiently strong--it make break from tension/compression due to each flywheel experiencing its own forces.
refer to the diagram i just drew up.

the black rectangles are the two flywheels, the connecting line is the physical connection and also the axle which both flywheels are concentric. the red arrows show the direction of angular momentum (along x axis), while the red circles indicate the direction of rotation (around x axis).
the blue arrows indicate the precession forces experienced by both flywheels when the whole system is rotated in the direction indicated by the curved blue arrow. this is what causes tension/compression in the connecting bar, but otherwise zero torque on the system as a whole.
the green arrows indicate the same forces if the system was rotated the other way (counter to the blue curved arrow).
the situation is similar for rotation of the system in any other plane.

A: I think that in case of two flywheels the angular momenta point in opposite directions and thus cancel each other. Therefore no nett torque will be required to change the angular momentum of the pair which is not the case if there is only one flywheel.


text:
Q: Javascript: How to find difference for two number arrays I need to create a new array made up of unique elements from two separate arrays.
I have converted both arrays into a single array and then converted this into an object to check the frequency of the elements. If the value of an object property is 1 (making it a unique property), I want to return it to an array (minus the value). Is there a straightforward way to achieve this?
Edits: Moved result outside for loop. Expected output should be [4]
function diffArray(arr1, arr2) {
  var finalArr = [];
  var countObj = {};
  var newArr = [...arr1, ...arr2];
  for (var i = 0; i < newArr.length; i++) {
    if (!countObj[newArr[i]]) countObj[newArr[i]] = 0;
    ++countObj[newArr[i]];
  }
  for (var key in countObj) {
    if (countObj[key] === 1) {
      finalArr.push(key);
    }
  } return finalArr;
}

diffArray([1, 2, 3, 5], [1, 2, 3, 4, 5]);

A: If I understand correctly, you're wanting to find the difference between arr1 and arr2, and returns that difference (if any) as a new array of items (that are distinct in either array).
There are a number of ways this can be achieved. One approach is as follows:

function diffArray(arr1, arr2) {

  const result = [];
  const combination = [...arr1, ...arr2];

  /* Obtain set of unique values from each array */
  const set1 = new Set(arr1);
  const set2 = new Set(arr2);

  for(const item of combination) {

    /* Iterate combined array, adding values to result that aren't
    present in both arrays (ie exist in one or the other, "difference") */
    if(!(set1.has(item) && set2.has(item))) {
      result.push(item);
    }
  }
  return result;
}

console.log(diffArray([1, 2, 3, 5], [1, 2, 3, 4, 5]), " should be [4]");
console.log(diffArray([1, 2, 3, 5, 8], [1, 2, 3, 5]), " should be [8]");
console.log(diffArray([1, 2, 3, 5, 8], [1, 2, 3, 5, 9]), " should be [8, 9]");
console.log(diffArray([1, 2], [1, 2]), " should be []");


text:
Q: ColdFusion 10 error with Stored Procedures In a .CFC file, within a CFfunction and with CFargument tags.
    <cfscript>
        var sp=new storedproc();
        sp.setDatasource(variables.datasource);
        sp.setProcedure("storedProcedure_INSERT");
        sp.addParam(cfsqltype="cf_sql_integer",type="in",value=arguments.one);
        sp.addParam(cfsqltype="cf_sql_integer",type="in",value=arguments.two);
        sp.addParam(cfsqltype="cf_sql_integer",type="in",value=arguments.three);
        sp.addParam(cfsqltype="cf_sql_integer",type="in",value=arguments.four);
        sp.addProcResult(name="results",resultset=1);
        //writeDump(sp);break;  //This dump is reached
        var spObj=sp.execute(); //blows up here; this is never reached
        writeDump(spObj);break; //This is never reached, either.
        var spResults=spObj.getProcResultSets().results;

A shiny nickle to anyone who can tell me why the sp.execute() is blowing up with message
"Cannot find results key in structure.

The specified key, results, does not exist in the structure."

I've used this psuedo-code many, may times in the past, and never had it do this.  I'm connected to a MSSQL Server 2012 DB, everything's cricket in CF Admin, and other SPs are working properly.  The stack trace doesn't even include any of MY code at all o_O

The error occurred in C:/ColdFusion10/cfusion/CustomTags/com/adobe/coldfusion/base.cfc: line 491
  Called from C:/ColdFusion10/cfusion/CustomTags/com/adobe/coldfusion/storedproc.cfc: line 142
  Called from //hq-devfs/development$/websites/myProject/cfc/mySOAPWSDLs.cfc: line 123

And SO is blowing up if I try and paste anymore of that.  Google has...not been helpful ._.

A: Short answer: The error means you are trying to retrieve a resultset from the stored procedure, when it does not actually return one. A simple solution is to add a SELECT to the end of your procedure, so it returns a resultset containing the data you need. Then your original code will work:
   SELECT @@ROWCOUNT AS NumOfRowsAffected;

Longer answer:
The method you are using, addProcResult(), is the equivalent of <cfprocresult>. It is intended to capture a resultset returned from a stored procedure. (Due to CF's poor choice of attribute names, a lot of people think "resultset" means the storedproc "result" structure, but they are two totally different things). A "resultset" is a query object", in CF parlance.
While all four (4) of the primary sql statements return some result, not all of them return a "query object"

*

*Only SELECT statements generate a "query object"

*INSERT/UPDATE/DELETE statements simply return the number of rows affected. They do not generate a  "query object".

Since your stored procedure performs an INSERT, it does not generate a "query object". Hence the error when you try and grab the non-existent query here:
  sp.addProcResult(name="results",resultset=1);

The simple solution is to add a SELECT statement to the end of your stored procedure, so that it does return a query object. Then your code will work as expected.

As an aside, I suspect you were actually trying to grab the "result" structure, but used the wrong method.  The equivalent of <cfstoredproc result=".."> is getPrefix(). Though that would not work here anyway. According to the docs, it does not contain the number of rows affected. Probably because stored procedures can execute multiple statements, each one potentially returning a row count, so there is not just a single value to return.


text:
Q: Spring Cloud Data Flow Design I have an existing process that I am trying to convert into SCDF implementation. The current process is,
HTTP Receiver (receive HTTP POST data) -> RabbitMQ -> MQ Receiver Service -> Process/Transform -> DB Sink
How can I achieve such flow, if possible? (1st issue)
So far, I figured that SCDF supports producer -> process -> consumer flow only.
I also tried to create multiple flows (HTTP Source -> RabbitMQ Sink & RabbitMQ Source -> Process -> DB) but deployment of RabbitMQ (as source and sink) does not work on Cloud Foundry (2nd issue). Aperently, I can deploy a stream with either Rabbit source or sink but not both togather (even as different stream).
Appreciate your help.

A: What you have described is the fundamental streaming pipeline using named destinations and it is expected to work including Cloud Foundry environment.
You can check out this sample for more information.
If you still see the issue, please share the exact error/exception while you try deploy the streams.


text:
Q: how do i use a class object as a model for a page in ionic framework I have a class object for a settings page eg.
export class SystemSettingsObject{

Settings1: number,
Settings2: boolean

}

How do I use that as a model for my settings page?
In my settings.ts file(.ts file for the view) I have this:
model : SystemSettingsObject

constructor(private systemsettings: SystemSettingsProvider){
 this.model = systemsettings.GetSystemSettings(); // this returns the systemSettingsobject, populated with data
}

If I had to use this model in a page would it just be a matter of saying, [(NgModel)] = "model.Settings1" on an input field?
I also keep getting errors saying cannot initialize Settings1 as null
So I'm not too sure how to fix this, any advice.
Thanks


text:
Q: How can we prove, by Bézout's theorem, that $L$ has finitely many singularities? Bézout's theorem
Bézout's theorem for curves states that, in general, two algebraic curves of degrees $m$ and $n$ intersect in m·n points and cannot meet in more than $m·n$ points unless they have a component in common (i.e., the equations defining them have a common factor)
Question
Let $L = \left\{ {x + iy:x,y \in \mathbb{R},f(x,y) = \sqrt {{x^2} + {y^2}} p(x,y) + q(x,y) = 0} \right\}$ and $p,q$ are two polynomials.
then $L$ is algebraic curve.
Let $(x,y)$ be singularity point,
By implict function theorem, we know that $\frac{{\partial {f_{}}}}{{\partial {x_{}}}}(x,y) = 0$ and $\frac{{\partial {f_{}}}}{{\partial {y_{}}}}(x,y) = 0$.
How can we prove, by Bézout's theorem, that $L$ has finitely many singularities?($x,y\in \mathbb{R}$)

A: First $f$ is not a polynomial so $f=0$ is not an algebraic curve. Without lose of generality, assume $p$ and $q$ are coprime to each other. (The general case is easy if you understand this coprime case). Show that $f=f_x=f_y$ has only finite many solutions.
\begin{equation}
\sqrt(x^2+y^2)p+q=0,\\
\frac{x}{\sqrt (x^2+y^2)}\,p+\sqrt(x^2+y^2)p_x+q_x=0\\
\frac{y}{\sqrt (x^2+y^2)}\,p+\sqrt(x^2+y^2)p_y+q_y=0
\end{equation}
whose solutions is a subset of the solutions of the following algebraic equations
\begin{equation}
(x^2+y^2)p^2=q^2,\\
(x ~p+(x^2+y^2)p_x)^2=(x^2+y^2)q_x^2\\
(y~ p+(x^2+y^2)p_y)^2=(x^2+y^2)q_y^2\\
\end{equation}
Use Bezout's theorem to show that the second set of algebraic equations only have finite solutions, then the solutions of the first non-algebraic equations would be a subset of a finite set, so it also has only finite solutions.
The basic idea is as above, but you need to take care of irreducibilities of equations to make the arguments sound, which I omit since it is not essential for the proof.


text:
Q: Java List Object instead of an Array I hava a Java map like this:
Map<String, Object> data = new HashMap<String, Object>();

And I am performing following operation on it:
data.put("case_ids", new int[] { 31527 });

Where case_ids is one of the attribute of 3rd party API. However, that API throws incorrect API request error and suggests me to use List object instead of an Array for:
data.put("case_ids", new int[] { 31527 });
Not an expert of List, any suggestions? Like data.put("case_ids", new List[] { 31527 }); ?
EDITED: Extending my current question (to avoid repost or similar question). What if I have huge set of values for above put operation and want to create a list of known values. I do not feel that it is a correct way to mention the list of values separated by commas like 31527, 31528, 31529, 31530, 31531,..etc. I would rather store this somewhere and just call that as a input here - data.put("case_ids", new int[] { input });. Also, is that possible to do without a file? Just want to avoid dependency on file.

A: Probably the simplest way how to create a list from known values is
Arrays.asList(31527)

That would make your call
data.put("case_ids", Arrays.asList(31527));

supposing the API accepts a List as the value. Without the API documentation or the error message, we cannot tell what it really accepts.
There are other ways how to create List, such as new ArrayList<>(), etc., just check out the javadoc and concrete classes which implement the List interface.

Update: If you don't want an external file, I suppose you're fine with having the numbers in the source code. The simplest option is to have them somewhere as a static field
public static final int[] VALUES = {1, 2, 3, /*...*/};

which you can turn into a List (in Java 8) with Arrays.stream(VALUES).boxed().collect(Collectors.toList()) (see here).
I  recommend using Guava library instead where you can create a safer immutable list directly with
public static final List<Integer> VALUES = ImmutableList.of(1, 2, 3)

If you don't like having all values in the code like this, then you can read them from a resource file, but that would be for another question.

A: You could use the following format
data.put("case_ids", Arrays.asList(new Integer[] { 31527 }));
If you have an array of integers the one you have mentioned the comments then you can use
int [] cases = { 10,20,30};
data.put("case_ids", Arrays.asList(cases));

A: List<Integer> mList = new ArrayList<Integer>;
mList.add(31527);
data.put("case_ids", mList);

A: List is an interface. Use a concrete class like data.put("case_ids", new ArraList<Integer>{ 31527 });


text:
Q: jQuery issue with $(this).toggleClass and Multiple btns and elements I am having trouble figuring this out. I have come up with jQuery that I can use multiple buttons to open a corresponding div using css transitions. I don't want to use text but the + and - to illustrate that the item is open and closed.
I want the + to change to - when you click on other + items. I also want the + on the current item to toggleClass or change from + to - and back to +
I am hoping that a fresh set of eyes with more JS skill can set me straight.
So here is my code...

div 1

div 2

div 3

div 1

div 2

div 3

I can get everything to work except I cant get the button to toggle the + and - if I click the same button twice. I also cannot get the existing active to close when clicking on another button out side of the container div.
Total Newb question I know but, if someone could help I would greatly appreciate it... many hours on this!
Thanks!

A: Replace the code of $("a").click();
with following i testesed its working fine
$('a').click(function() {

    ($("a").not($(this))).removeClass("btn-pnl-viz");
    $(this).toggleClass("btn-pnl-viz");

});

Reply if any problem with the code
Thanks


text:
Q: Eclipse - JPA EclipseLink Generating tables from entities Hi i'm trying to generate db tables from entities in eclipse. but it does not show schema generation dialog as shown in this link. when i click "Generate table from  entities" it does nothing.
persistence.xml
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.1" xmlns="http://xmlns.jcp.org/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">
<persistence-unit name="TestEclipsLink" transaction-type="RESOURCE_LOCAL">
    <properties>
        <property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/test"/>
        <property name="javax.persistence.jdbc.user" value="root"/>
        <property name="javax.persistence.jdbc.password" value="1234"/>
        <property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver"/>
    </properties>
</persistence-unit>
</persistence>

Entity class
package db.enitity;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.TableGenerator;

@Entity
@TableGenerator(name="person")
public class Person {

@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private int id;
private String name;

public int getId() {
    return id;
}
public void setId(int id) {
    this.id = id;
}
public String getName() {
    return name;
}
public void setName(String name) {
    this.name = name;
}

}


text:
Q: Plot roots of function in complex plane with manipulate I'm trying to analyze the roots of this function
$$f(y;a_1,a_2,b_1,b_2,c_1,c_2) = \frac{a_1}{1 + b_1 e^{-c_1 y}} - \frac{a_2}{1 + b_2 e^{-c_2 y}}$$
For example, I fix (in manipulate), $a_1, a_2, b_1, b_2, c_1$ and vary $c_2$ (in parametric plot maybe?) and I would like a plot of the location of the zeros.
I tried this:
Manipulate[
 soln = Solve[a1/(1 + b1 Exp[-c1 y]) - a2/(1 + b2 Exp[-c2 y]) == 0, y];
 ParametricPlot[Evaluate[y /. soln], {c2, 0, 1}], {a1, 0.01, 2}, {a2,
  0.01, 2}, {b1, 0.01, 2}, {b2, 0.01, 2}, {c1, 0.01, 2}]

But I get that warning that some solutions will not be found. Thanks for your help.

A: I think you are looking for something like that (working with MMA version 8.0):
f[y_, a1_, a2_, b1_, b2_, c1_, c2_] =
                  a1/(1 + b1 Exp[-c1 y]) - a2/(1 + b2 Exp[-c2 y])

I correct my former answer and now work with Reduce.
For all parameters Reduce yields an equation together with a condition (...!=0).
Manipulate[
    Reduce[f[y, a1, a2, b1, b2, c1, c2] == 0] // Quiet, {a1, 0.01,
    2}, {a2, 0.1, 2}, {b1, 0.01, 2}, {b2, 0.01, 2}, {c1, 1, 2}]

(*     E^(1.247 y) ==
       0.000361533 (18326. E^(c2 y) + 11875. E^(1.247 y + c2 y)) &&
       6.06035*10^18 + 3.91644*10^19 E^(c2 y) + 3.53485*10^19 E^(2 c2 y) +
       2.11188*10^19 E^(1.247 y + c2 y) +
       2.29054*10^19 E^(1.247 y + 2 c2 y) != 0    *)

Ploting the equation and Not[condition] shows y solutions depending an c2 as the red curve, where it is not crossed by the blue condion curve.
Manipulate[red = Reduce[f[y, a1, a2, b1, b2, c1, c2] == 0] // Quiet;
  ContourPlot[
   Evaluate[{red[[1]], ! red[[2]]} /. {y -> yy, c2 -> cc2}], {yy, -20,
   20}, {cc2, .01, 2}, MaxRecursion -> 4,
   ContourStyle -> {Red, Blue}], {a1, .01, 2}, {a2, 0.01, 2}, {b1,
   0.01, 2}, {b2, 0.01, 2}, {c1, 0.01, 2}]


text:
Q: Why is WordPress redirecting to homepage after GET form submit? <form method="get" action="example.com/?category=1">
    <input type="submit">
</form>

action parameter may be any page etc. but it always redirect to homepage. If I change method to POST - then all fine. What is the problem here?

A: Your permalink structure appears to be incorrect try changing your code to.  Modified, try creating a search form like this and see if you still get the homepage, if so then there will be something wrong with your theme templates.
<form method="get" action="/">
    <input type="text" name="s">
    <input type="submit">
</form>

A: Try the following (untested):

*

*Change your permalink structure in your settings to Post Name.

*Try this action if used on a page: action="<?php the_permalink(); ?>"

*Or even try to remove the action altogether.


text:
Q: Creating a table using mysql python with variable values I'm trying to create a table in MySQL using python-flask. The table name is the 'id' parameter, which I pull from my server. I want this id to be the name of the table that I'm creating, but when I try to do so, I get the following error:
'mysql.connector.errors.ProgrammingError: 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '46490210 (user varchar(50), message varchar(150))' at line 1'
Here's the python-sql code for reference.
#the file name is chat_db.py

def createTable(id):
    cursor = db.cursor()
    cursor.execute("CREATE TABLE IF NOT EXISTS %s (user varchar(50), message varchar(150))",(id,))
    db.commit()

Here's the Flask code (without the decorators):
import chat_db as roomdb
import random

def rand_id():
    return random.randint(10000000,99999999)

def roomTable():
    roomdb.createTable(rand_id())

roomTable()

Please help out! :)

A: Onlym Number aren't alowwed in mysql, so you need a Letter before the number
In my example i used the Letter A, but it can  be of course any Text you like.
But i don't see why you want to do such a thing in a loop.
def createTable(id):
    cursor = cnx.cursor()
    cursor.execute("CREATE TABLE IF NOT EXISTS A%s (user varchar(50), message varchar(150))",(id,))
    cnx.commit()


text:
Q: How the camel recipientList forward the messages from("direct:A")
    .process(//processing here)
            .recipientList(//expression that return two recipients [direct:B, direct:C] )

from("direct:B")
    .process(//processing here)...

from("direct:C")
    .process(//processing here)...

.from("direct:A") behaves like a java method i.e the thread that calls it will continue to process().
So what will happen in above case  ?
Let say Thread t1 calls from("direct:A") then
t1 will continue to process()
and then t1 will enter into recipientList()
Now from here on-wards will t1 call from("direct:B") and then call from("direct:C") synchronously
or
direct:b and direct:c will be called in two new thread asynchronously.

A: Read the recipient list documentation for a lot more detail. By default it processes messages synchronously. You can use the parallel processing feature of the recipient list to run this concurrently. You can also define your own thread pools.
Go read the documentation it is in there.


text:
Q: Using DefaultRequestHeaders sends requests twice? I have a WebAPI that sends BASIC authorization information as following.
var client = new HttlpClient();
client.BaseAddress = new Uri(GlobalConstants.LdapUri);
var contentType = new MediaTypeWithQualityHeaderValue("application/json");

client.DefaultRequestHeaders.Accept.Add(contentType);
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(Encoding.ASCII.GetBytes(string.Format("{0}:{1}", userName, password))));
Task<HttpResponseMessage> results = client.GetAsync(GlobalConstants.FortressAPIUriDev);
var response = await results;

I've built this API using MVC Core 1.x and the receiving API is built using MVC5.
The problem is that this GetAsync sends two requests at the same time, and I have no clue how to resolve this. I've done some Googling myself to see if I can find a fix for this but so far no luck. Did anyone experience this problem and know how to resolve it?
Thank you very much in advance.

A: Long story short, found a solution as follows:
using (var client = new HttpClient())
{
    var requestMessage = new HttpRequestMessage(HttpMethod.Get, GlobalConstants.LdapUri + GlobalConstants.FortressAPIUriDev);
    requestMessage.Headers.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(Encoding.ASCII.GetBytes(string.Format("{0}:{1}", userName, password))));
    var response = await client.SendAsync(requestMessage);
}

After replacing with this code, it is sending one request at a time.
Found a hint at :
Adding headers when using httpClient.GetAsync


text:
Q: How should I read environment variables at AWS EC2 instance in Reactjs App I want to fetch some credentials from environment variables in my Reactjs app, which would be different for different environment i.e. Dev/staging/prod.
I am doing this in webpack.config.js
`
function getDotenvFilePath(){
    if(process.env.NODE_ENV === 'local'){
        console.log('u r in local ');
        return './.env.local';
    }else if(process.env.NODE_ENV === 'dev'){
        console.log('u r in development ');
        return './.env.development';
    }else if(process.env.NODE_ENV === 'int'){
        console.log('u r in int ');
        return './.env.int';
    }
}`

different files for different environments which I will trigger from maven like this npm run-script build:int is that a right approach?
Thanx

A: small example to read a specific .env file based on the NODE_ENV variable
I am assuming you have dotenv-webpack plugin setup
module.exports = {
  ...
  plugins: [
    new Dotenv({
      path: (process.env.NODE_ENV === 'development' ? './.env.development' ? './.env.production'),
      safe: true,
      systemvars: true,
      silent: true
    })
  ]
  ...
};


text:
Q: ISSUE: Border-Image stretched on safari and not chrome I'm building a holding website for a client and I've added a border image into my code and it doesnt work on safari. However, it works completely fine on Chrome. I've checked the current posts similar to this issue however I've still not managed to figure out the issue. Any Thoughts?
Thanks!
issue Screengrab attached here
// what it should look like screengrab
#wrapper{
                border-style:solid;
                border: 15px solid;
                width: 100%;
                height: 100%;
                box-sizing: border-box;
                margin: 0;
                -moz-border-image: url(border-brown.png) 33.33% round;
                border-image: url(border-brown.png) 33.33% repeat;
                border-image-repeat: round;
                transition: 0.5s;
                overflow: hidden;
                -webkit-backface-visibility:hidden;
                }


text:
Q: Does PlayStation 2 slimline have USB 2.0 ports? I know the classic (fat) PlayStation 2 has two USB 1.1 ports.
Has Sony upgraded slimlines' USB ports (in particular SCPH-90004) to 2.0?

A: Wikipedia has a page indicating that the Slimline had two USB 1.1 ports, like all other models of the PS2.
An additional Wikipedia source about the technical specifications for the PS2 can be found here, which also states they are USB 1.1:

USB 1.1 ports with an OHCI-compatible controller

A: Yes, the PS2 slimeline has USB 2.0 port which can be used for different purposes such as playing a game from a USB drive, listening to audio from a game, communication in an online game and so on


text:
Q: Using an RPC like Protocol Buffers as a backend to Django, instead of MySQL or SQLite The clever folks behind the app-engine-patch project have essentially enabled all the fun stuff of Django, including the admin, but without using Django's ORM.
From their website:

The most important change is that you have to use Google's Model class because the development model is too different from Django (at least with Django's current API).

This is essentially what I want to do, but use Google's Protocol buffers as the data transport layer through RPC.
Using the Person message in their addressbook.proto example, I essentially want to do this:
from django.contrib import admin
from myrpc.models import Person

class PersonAdmin(admin.ModelAdmin):
  list_display = ['id', 'name', 'email']

admin.site.register(Person, PersonAdmin)

A: app-engine-patch is no longer maintained and last time I tried it it was so buggy that I was better off reimplementing the middleware that I wanted. I also don't remember them to ever support Django's Admin.
Django's Admin is not compatible with Google App Engine's API for database access. It's actually totally different.
Then there's Django-norel which attempted to make Django's ORM compatible with GAE and you might have some luck with it, but again it is unmaintained.
So on GAE, don't use a patch because Django 1.2 is already included in the list of available APIs. See this section in their documentation: Third Party Libraries, Django
And you won't be able to use Django's Admin. Take your mind off it.


text:
Q: Fatal error: Uncaught Error: Cannot use object of type mysqli_result as array Нужно достать значение id
Мой код:
$mysqli = mysqli_connect("localhost", "Rysik5318", "password", "test");
$logged_user = $mysqli->query("SELECT * FROM `users` WHERE `login` = '".$_SESSION['logged_user']."' ");
echo $logged_user['id'];

Ошибка -
Fatal error: Uncaught Error: Cannot use object of type mysqli_result as array in D:\OpenServer\domains\edrenbaton\index.php:19 Stack trace: #0 {main} thrown in D:\OpenServer\domains\edrenbaton\index.php on line 19

A: query не извлекает данных, а лишь исполняет запрос. Он возвращает объект mysqli_result, у которого можно применять методы для извлечения данных

Но суть в том, что возвращается объект, а вы обращаетесь к нему как к массиву. Что неверно.
Для того, чтобы оперировать данными, как минимум надо пройти путь до mysqli_result и всяких fetch_*


text:
Q: How to have a database with a custom file extension which automatically opens with and only with my java program when file is double clicked I'm creating a management software which saves all data using a database management system. I will like to know how to get my database have a custom file format like doc for Ms Word, psd for Adobe Photoshop, ai for Adobe Illustrator and when the file is double clicked it automatically opens my java program and loads its data into it.
Can you recommend a DBMS or what do ever which can enable me to achieve this in java?
I'm currently working with sqlite and java swing and to thinking to dive into H2 and JavaFx for future programs

A: Thank you guys! I tried H2 and file association and it worked for me.


text:
Q: How to package tensorflow-gpu model to run on most of the machines? Tensorflow GPU version, nvidia driver version, cudnn version has special compatibility matrix. This compatibility matrix creates problem in packaging and ditributing tensorflow model which can run by others without any hassle when I pass them.Container based technologies(e.g. docker) would also have problem as it won't know nvidia driver version. I am wondering if anyone knows the best way to package tensorflow model which can automatically configure according to underlying nvidia driver on the linux system. How can I achieve this?

A: The easiest way is to use tensorflow image with docker
https://hub.docker.com/r/tensorflow/tensorflow/
and for GPU you can use the nvidia tools with preinstalled existing image or add it up with the  docker file..


text:
Q: How to call a customhelper in CodeCeptjs? How to call a method defined in customhelper?
MycustomHelper
const { Helper } = codeceptjs;
const chai = require('chai');
const chaiAsPromised = require('chai-as-promised');
chai.use(chaiAsPromised);
const expect = chai.expect;

class MyHelper extends Helper {

  async JavaScriptclick(LocatorVale)  {
    await browser.waitForAngularEnabled(true);
    browser.executeScript("arguments[0].click();", element(by.xpath(LocatorVale)));

  }

}

module.exports = MyHelper;

Code.js
helpers: {
    MyHelper: {
      require: './myhelper_helper.js',
    },

Stepfile.js
Scenario('Add a new user group', (I, MyHelper) => {
   MyHelper.JavaScriptclick('.badged-button.mat-raised-button.mat-primar')
});

If I execute the above code, I get the below error
   Add a new user group:
     Object of type MyHelper is not defined in container

Please help me to resolve this issue. I need to click on a button, but I.click is not able to locate the button. So I had to use javascriptclick in this case. However I.executescript is also not working. Hence I need to use native protractor commands as it works only this way.

A: There are no need to call helper by it's name.
All methods are added in actor (I) object
As said in documentation:

Methods of Helper class will be available in tests in I object. This abstracts test scenarios from the implementation and allows easily switching between backends.

https://codecept.io/helpers/#extending-codeceptjs-with-custom-helopers
So, in test:
Scenario('Add a new user group', (I) => {
   I.JavaScriptclick('.badged-button.mat-raised-button.mat-primar')
});


text:
Q: sed isn't working when it's piped from another sed command I'm trying to prepare my output for a grep expression, but when I try to modify the data to get it in the format I want I'm having issues getting it the way I want.
I'm using the following command to get a list of IP addresses that I need.
PRIV_IP=$(aws ec2 describe-instances  \
     --region "${REGION}" \
     --output text \
     --query 'Reservations[].Instances[].[PrivateIpAddress]' \
     --filters Name=tag:TagA,Values="${TagAData}" \
               Name=tag:TagB,Values="HOME" \
               Name=tag:TagC,Values="MAIN" | sed 's/\./-/g' | sed 's/ /\\|/g')

This is the output of the command; it ignores the last sed statement.
echo $PRIV_IP
1-2-3-4 5-6-7-8 9-10-11-12

If I perform the sed manually it works as intended.
echo $PRIV_IP | sed 's/ /\\|/g'
1-2-3-4\|5-6-7-8\|9-10-11-12

Can someone provide some input on what I'm doing incorrectly?

A: It could be that your real command prints TABs but in your test they got converted to space already, e.g.
$ echo -e "A\tB"
A       B
$ echo -e "A\tB" | sed -e 's/ /X/g'
A       B
$ a=$(echo -e "A\tB"); echo $a
A B
$ echo $a | sed -e 's/ /X/g')
AXB

Solution: replace all white space as suggested by the comments, i.e.
$ echo -e "A\tB" | sed -e 's/[[:space:]]/X/g'
AXB


text:
Q: How to store all values from 100 to "User Input" in an array When I'm done with this program it is suppose to display all palindromes and all prime palindromes that are greater than 100 and less than the number input by the user.  As I'm going along in this assignment, I'm getting confused on how to store those values into the array that I have created "char[] charUser"
public static void main(String[] args)
{
    Scanner promptUser = new Scanner(System.in);
    System.out.print("Enter an Integer greater than 100: ");
    Integer userInt = new Integer(promptUser.nextInt());
    String userString = userInt.toString();
    char[] charUser = userString.toCharArray();

    if (userInt <= 100)
    {
        System.out.print("That integer is not greater than 100,"
                        + " restart program and try again!");
    }

    char[] resultArray = reverseArray(charUser);
    for(int i = 0; i < resultArray.length; i++)
        {
            System.out.print(resultArray[i]);
        }
}

/**Takes the integer provided by the user and turns it into a string
 * then takes that string and puts it into a char[], then there is a for loop
 * to reverse that array.
 * @param charUser array used to store the reversed string.
 * @revArray char array used to store data from charChange array.
 * @return returns charChange now with the reversed string.
 */
public static char[] reverseArray(char[] charUser)
{
    char[] revArray = new char[charUser.length];

    for(int i = 0; i < revArray.length; i++)
    {
        revArray[i] = charUser[charUser.length - 1 - i];
    }

    return revArray;
}

/** Takes the original array charUser before being reversed and
 * compares it with the reversed array resultArray to determine if they
 * are equal.
 * @param charUser original array created from the user input.
 * @param resultArray the reversed array of charUser.
 * @return returns the answer to boolean isPalindrome, whether or not the
 * two arrays are equal.
 */
public static boolean arraysAreEqual(char[] charUser, char[] resultArray)
{
   char[] isPal1 = new char[charUser.length];
   char[] isPal2 = new char[resultArray.length];
   boolean isPalindrome = false;

   if(isPal1[isPal1.length] == isPal2[isPal2.length])
   {
       isPalindrome = true;
   }

   return isPalindrome;
}

public static boolean isPrime(int userInt)
{
    int intUser = userInt;
    boolean checkPrime = true;

    for(int i = 2; i < Math.sqrt(intUser); i++)
    {
        if(intUser % i == 0)
        return false;
    }

    return checkPrime;
}

/*public void printArray(char[] resultArray)
{

}*/

}

A: If you want to use an array, you need to know exactly the length of the array (how many elements you want that array to contain) using this line:
int[] palindrome = new int[x]; //x being the length of the array

However if you need to add your new found palindromes to an array in a dynamic fashion (on the fly) you need to use the Arraylist class.
An Arraylist would be initialized like this:
Arraylist<Integer> palindromes = new Arraylist<Integer>();

ANd then elements can be added whenever you find a new plalindrome with the add method of the Arraylist class:
palindromes.add(x); //x being the number to add to the list

You should take a look at Oracle's documentation here for more info on Arraylist and it's many methods
Hope this helps
EDIT
To answer your question you need to rethink this method completely:
public static boolean arraysAreEqual(char[] charUser, char[]      resultArray)
{
   char[] isPal1 = new char[charUser.length];
   char[] isPal2 = new char[resultArray.length];
   boolean isPalindrome = false;

   if(isPal1[isPal1.length] == isPal2[isPal2.length])
   {
       isPalindrome = true;
   }

   return isPalindrome;
}

*

*If you want to create a new char array (as a copy of the one passed as a parameter) you can't do it the way you did it. Altought you wouldn't even need to create a new array, you could just used the one passed as a parameter.

*Next point if you want to compare the char array with it's opposite array, you need to loop and check elements by elements. If you convert them to int you can just check easily if they are equal:
if (number == oppositeNumber){
    //it is a palindrome
    //Therefor return true
}
return false; (if it isn't a palindrome return false)

How to cast char array to int
If you want to convert your char array to an int you need to do these simple steps:

*

*Cast char array to String

*Cast String to int

Like this examples shows:
char[] nums = {'1','2','2','1'};
String str = String.valueOf(nums);
int number = Integer.parseInt(str);
System.out.println(number);


text:
Q: What are the device-width css viewport sizes of the iPhone6 and iPhone 6 Plus The iPhone 6 and iPhone 6 Plus were just announced. But as usual, phone specs never give the meta viewport device-width sizes in CSS Pixels or DPR at width=device-width,initial-scale=1.
Predictions have been made, speculating on 375/414px viewport width, but that still remains unclear...
NB: Please don't speculate or post answers with the known overall device resolution or specs, it's not what I am looking for. I want the default responsive portrait and landscape viewport-width in pixels.

A: According to CSSpixels
iPhone 6: 1334x750, viewport 667x375
iPhone 6+: 2208x1242 *, viewport 736x414 *
*Virtual resolution is subsampled to fit 1920×1080 screen.

A: Below is the ios Device Sizes with detailed information

References

A: (css) device-width of iPhone 6 is 375px, of iPhone 6 Plus is 414px. Note that iPhone 6 Plus report window.devicePixelRatio = 3 (while not truly at 3 DPR)
Update 1: just to clarify, I believe this is NOT a prediction, but actually tested. See more detailed and reputable reference. If in doubt, you can wait for device to be out.
Update 2: for users with Display Zoom enabled on iPhone 6, css viewport in Mobile Safari fallback to 320px (like iPhone 5); for iPhone 6 Plus, it fallback to 375px (like iPhone 6).

A: Device-width is indeed 375x667, but that does not mean the viewport is that size. Here is an empirical sample. Note that the numbers are rounded to the 10s.


text:
Q: Puppeteer-cluster with cheerio in express router API returns empty response I'm writing an API with express, puppeteer-cluster and cheerio that returns all anchor elements containing one or more words that can be added as query parameters. I want to use puppeteer in order to get elements that are javascript generated too. But for some reason it's not working, I get an empty array as an output printed on the browser.
I'm still trying to understand this library but has been 2 days and I made no progress. Any help is deeply appreciated.
Update: I added async to all my functions and they run now, but the result is still empty :(
Update 2: I started logging everything, every step and found that data.name is being passed to the cheerio function as a Promise. '-' I think that is the problem, but don't know how to fix it yet.
Update 3: One of the issues was that the page content (html code) was not being handled properly to the cheerio function. In the browser, however, the response is empty and the console shows an error:

Error handling response: TypeError: Cannot read properties of
undefined (reading 'innerText').

So, I think the response is not json formatted. Is res.json() not the right way to do it?
My code:
app.js
const PORT = process.env.PORT || 8000;
var path = require("path");
const express = require("express");

// Routes
const indexRouter = require("./routes/index");
const allNews = require("./routes/news");
const clusterRouter = require("./routes/cluster");

const app = express();
app.use(cors());
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(express.static(path.join(__dirname, "public")));

app.use("/", indexRouter);
app.use("/news", allNews);
app.use("/cluster", clusterRouter);

app.listen(PORT, () => console.log(`server running on PORT ${PORT}`));

cluster.js
const express = require("express");
const { Cluster } = require("puppeteer-cluster");
const puppeteer = require("puppeteer-extra");
const cheerio = require("cheerio");
const StealthPlugin = require("puppeteer-extra-plugin-stealth");

var router = express.Router();
const newspapers = [
  {
    "name": "CNN",
    "address": "https://edition.cnn.com/specials/world/cnn-climate",
    "base": "https://edition.cnn.com"
  },
  {
    "name": "The Guardian",
    "address": "https://www.theguardian.com/environment/climate-crisis",
    "base": "https://www.theguardian.com"
  }]

const app = express();
puppeteer.use(StealthPlugin());

const result = [];

router.get("/", async (req, res) => {
  (async () => {
    // Query String
    const query = checkForQuery(req);
    const wordsToSearch = query ? verifyQuery(query) : "";

    console.log("Running tests.."); // This is printed on console

    //Functions
    function checkForQuery(request) {
      if (request.originalUrl.indexOf("?") !== -1) {
        console.log(request.query);
        return request.query;
      } else {
        return false;
      }
    }

    // // Validates query and remove invalid values
    function verifyQuery(queryString) {
      const queryParams = {
        only: queryString.only ? queryString.only : "",
        also: queryString.also ? queryString.also : "",
      };
      // Creates new list containing valid terms for search
      var newList = {
        only: [],
        also: [],
      };

      for (const [key, value] of Object.entries(queryParams)) {
        const tempId = key.toString();
        const tempVal =
          queryParams[tempId].length >= 2
            ? queryParams[tempId].split(",")
            : queryParams[tempId];
        console.log(queryParams[tempId], " and ", tempVal);
        if (tempVal.length > 1) {
          console.log("helloooooo");
          tempVal.forEach((term) => {
            if (topics.indexOf(term) != -1) {
              newList[tempId].push(term);
            }
          });
        } else {
          if (topics.indexOf(queryParams[tempId]) != -1) {
            newList[tempId].push(queryParams[tempId]);
          }
        }
      }
      console.log(newList);
      return newList;
    }

    function storeData(element, base, name) {
      const results = [];
      element.find("style").remove();
      const title = element.text();
      const urlRaw = element.attr("href");
      const url =
        urlRaw.includes("www") || urlRaw.includes("http")
          ? urlRaw
          : base + urlRaw;

      // Check for duplicated url
      if (tempUrls.indexOf(url) === -1) {
        // Check for social media links and skip
        if (!exceptions.some((el) => url.toLowerCase().includes(el))) {
          tempUrls.push(url);

          // Get img if child of anchor tag
          const imageElement = element.find("img");
          if (imageElement.length > 0) {
            // Get the src attribute of the image element

            results.push({
              title: title.replace(/(\r\n|\n|\r)/gm, ""),
              url,
              source: name,
              imgUrl: getImageFromElement(imageElement),
            });
          } else {
            results.push({
              title: title.replace(/(\r\n|\n|\r)/gm, ""),
              url: url,
              source: name,
            });
          }
        }
      }
      return results;
    }

    function getElementsCheerio(html, base, name, searchterms) {
      console.log(html, base, name);
      const $ = cheerio.load(html);
      console.log(searchterms);
      const concatInfo = [];

      if (searchterms) {
        const termsAlso = searchterms.also;
        const termsOnly = searchterms.only;

        termsAlso.forEach((term) => {
          $(`a:has(:contains("climate"):contains(${term}))`).each(function () {
            const tempData = storeData($(this), base, name);
            tempData.map((el) => concatInfo.push(el));
          });
        });

        termsOnly.forEach((term) => {
          // $(`a:has(:contains(${term}))`).each(function () {
          $(`a:contains(${term})`).each(function () {
            const tempData = storeData($(this), base, name);
            tempData.map((el) => concatInfo.push(el));
          });
        });
      } else {
        $('a:contains("climate")').each(function () {
          const tempData = storeData($(this), base, name);
          tempData.map((el) => concatInfo.push(el));
        });
      }
      return concatInfo;
    }

    const cluster = await Cluster.launch({
      concurrency: Cluster.CONCURRENCY_CONTEXT,
      maxConcurrency: 2,

      puppeteerOptions: {
        headless: true,
        args: ["--no-sandbox", "--disable-setuid-sandbox"],
        userDataDir: "./tmp",
        defaultViewport: false,
      },
    });

    await cluster.task(async ({ page, data }) => {
      await page.goto(data.address);
      await page.waitForSelector("body");

      // console.log here prints that data.name is a Promise :(
      const elements = await getElementsCheerio(
        document.body.innerHTML,
        data.base,
        data.name,
        wordsToSearch
      );
      result.push(elements);
    });

    newspapers.map((newspaper) => {
      console.log("queue" + newspaper); // This logs correctly: queue[object Object]
      cluster.queue(newspaper);
    });

    await cluster.idle();
    await cluster.close();

    // Display final object
    res.json(result);
  })();
});

module.exports = router;

I don't get any errors, but on screen I get an empty [ ]. Anyone can see what I am doing wrong here? :(

A: In general, it's an antipattern to mix Puppeteer with another selection library like Cheerio. In addition to being redundant, the extra HTML parser doesn't work on the live document as Puppeteer does, so you have to snapshot the HTML at a particular moment with Puppeteer to capture it as a string and plug that string into Cheerio, where it's re-parsed back to a traversible tree structure.
Introducing this extra step creates opportunity for bugs and confusion to creep in, and that's what happened here.
The code
const elements = await getElementsCheerio(
    document.body.innerHTML,
    data.base,
    data.name,
    wordsToSearch
);

is problematic. document.body.innerHTML doesn't refer to anything related to Puppeteer. Instead, use Puppeteer's await page.content() to snapshot the HTML.
As a minor point, there's no need for Cheerio functions to be async, because they never use await. It's a fully synchronous API.
Here's a minimal set up for using Cheerio with Puppeteer, assuming you accept the terms and conditions and are sure that intoducing this usually unnecessary layer of indirection is appropriate for your use case:
const cheerio = require("cheerio"); // 1.0.0-rc.12
const puppeteer = require("puppeteer"); // ^19.0.0

let browser;
(async () => {
  browser = await puppeteer.launch();
  const [page] = await browser.pages();
  const url = "https://www.example.com";
  await page.goto(url, {waitUntil: "domcontentloaded"});
  const html = await page.content();
  const $ = cheerio.load(html);

  // do cheerio stuff synchronously
  console.log($("h1").text()); // => Example Domain
})()
  .catch(err => console.error(err))
  .finally(() => browser?.close());

It's basically the same for puppeteer-cluster: just drop the lines starting with const html = await page.content(); into the cluster.task callback that operates on page.


text:
Q: Titanic Dataset/TensorFlow input_fn() error and setup I am trying my best to implement a DNN with tensorflow so far I have been able to download the files and parse them so that all the data in the Pandas dataframe is noncatagorical however I have tried to fit my data inside a tensorflow DNN and I am not sure how to proceed forward. any help would be much appreciated
#==============================================================================
#
# Import statements
#
#==============================================================================
import tensorflow as tf
import pandas as pd
from pandas import Series, DataFrame
from sklearn.preprocessing import LabelEncoder

import tempfile

Columns = ['PassengerId', 'Survived', 'Pclass', 'Sex', 'Age', 'SibSp', 'Parch', 'Embarked']
#==============================================================================
#
# read data from given file and return a pandas dataset
#
#==============================================================================
def readData(FileName):
    titanic_df = pd.read_csv(FileName)
    titanic_df = titanic_df.dropna()
    return titanic_df

def processData(data):
    gender = LabelEncoder()
    gender.fit(['male', 'female'])
    data["Sex"]= gender.transform(data["Sex"])

    Embarked = LabelEncoder()
    Embarked.fit(['S', 'C','Q'])
    data["Embarked"] = Embarked.transform(data["Embarked"])

    return data

def input_fn(data):
    Continuous_cols = {k: tf.constant(data[k].values) for k in Columns}
    label = tf.constant(data['Survived'].values)
    return dict(Continuous_cols.items()),label

def train_input_fn(train_data):
    return input_fn(train_data)

def eval_input_fn(test_data):
    return input_fn(test_data)

def main():
    test_data = readData('test.csv')
    train_data = readData('train.csv')
    Col_To_Drop =['Name','Ticket','Cabin','Fare']
    for col in Col_To_Drop:
        test_data = test_data.drop(col,1)
        train_data = train_data.drop(col,1)

    test_data = processData(test_data)
    train_data = processData(train_data)

    Columns = list(train_data.columns.values)
    print(Columns)
    print(test_data.info())
    print(train_data.info())

    print(train_data.head())

    model_dir = tempfile.mkdtemp()
    features = []
    for c in Columns:
        features.append(tf.contrib.layers.real_valued_column(str(c)))

    m = tf.contrib.learn.LinearClassifier(feature_columns=features,
        model_dir=model_dir)
    m.fit(input_fn=lambda: train_input_fn(train_data), steps=200)
    results = m.evaluate(input_fn=lambda: eval_input_fn(test_data), steps=1)
    for key in sorted(results):
        print("%s: %s" % (key, results[key]))

if __name__ == "__main__":
    main()

------------------------Output---------------------
NOTE: The Python console is going to be REMOVED in Spyder 3.2. Please start to migrate your work to the IPython console instead.

['PassengerId', 'Survived', 'Pclass', 'Sex', 'Age', 'SibSp', 'Parch', 'Embarked']
<class 'pandas.core.frame.DataFrame'>
Int64Index: 87 entries, 12 to 414
Data columns (total 7 columns):
PassengerId    87 non-null int64
Pclass         87 non-null int64
Sex            87 non-null int64
Age            87 non-null float64
SibSp          87 non-null int64
Parch          87 non-null int64
Embarked       87 non-null int64
dtypes: float64(1), int64(6)
memory usage: 5.4 KB
None
<class 'pandas.core.frame.DataFrame'>
Int64Index: 183 entries, 1 to 889
Data columns (total 8 columns):
PassengerId    183 non-null int64
Survived       183 non-null int64
Pclass         183 non-null int64
Sex            183 non-null int64
Age            183 non-null float64
SibSp          183 non-null int64
Parch          183 non-null int64
Embarked       183 non-null int64
dtypes: float64(1), int64(7)
memory usage: 12.9 KB
None
    PassengerId  Survived  Pclass  Sex   Age  SibSp  Parch  Embarked
1             2         1       1    0  38.0      1      0         0
3             4         1       1    0  35.0      1      0         2
6             7         0       1    1  54.0      0      0         2
10           11         1       3    0   4.0      1      1         2
11           12         1       1    0  58.0      0      0         2
WARNING:tensorflow:Rank of input Tensor (1) should be the same as output_rank (2) for column. Will attempt to expand dims. It is highly recommended that you resize your input, as this behavior may change.
WARNING:tensorflow:Rank of input Tensor (1) should be the same as output_rank (2) for column. Will attempt to expand dims. It is highly recommended that you resize your input, as this behavior may change.
WARNING:tensorflow:Rank of input Tensor (1) should be the same as output_rank (2) for column. Will attempt to expand dims. It is highly recommended that you resize your input, as this behavior may change.
WARNING:tensorflow:Rank of input Tensor (1) should be the same as output_rank (2) for column. Will attempt to expand dims. It is highly recommended that you resize your input, as this behavior may change.
WARNING:tensorflow:Rank of input Tensor (1) should be the same as output_rank (2) for column. Will attempt to expand dims. It is highly recommended that you resize your input, as this behavior may change.
WARNING:tensorflow:Rank of input Tensor (1) should be the same as output_rank (2) for column. Will attempt to expand dims. It is highly recommended that you resize your input, as this behavior may change.
WARNING:tensorflow:Rank of input Tensor (1) should be the same as output_rank (2) for column. Will attempt to expand dims. It is highly recommended that you resize your input, as this behavior may change.
WARNING:tensorflow:Rank of input Tensor (1) should be the same as output_rank (2) for column. Will attempt to expand dims. It is highly recommended that you resize your input, as this behavior may change.
WARNING:tensorflow:From C:\ProgramData\Anaconda3\lib\site-packages\tensorflow\contrib\learn\python\learn\estimators\head.py:615: scalar_summary (from tensorflow.python.ops.logging_ops) is deprecated and will be removed after 2016-11-30.
Instructions for updating:
Please switch to tf.summary.scalar. Note that tf.summary.scalar uses the node name instead of the tag. This means that TensorFlow will automatically de-duplicate summary names based on the scope they are created in. Also, passing a tensor or list of tags to a scalar summary op is no longer supported.
 up CPU computations.
e are available on your machine and could speed up CPU computations.
2017-07-23 17:48:29.227623: W d:\nwani\l\tensorflow_1498062690615\work\tensorflow-1.1.0\tensorflow\core\platform\cpu_feature_guard.cc:45] The TensorFlow library wasn't compiled to use FMA instructions, but these are available on your machine and could speede\platform\cpu_feature_guard.cc:45] The TensorFlow library wasn't compiled to use AVX2 instructions, but thes98062690615\work\tensorflow-1.1.0\tensorflow\core\platform\cpu_feature_guard.cc:45] The TensorFlow library wasn't compiled to use AVX instructions, but these are available on your machine and could speed up CPU computations.
2017-07-23 17:48:29.227119: W d:\nwani\l\tensorflow_1498062690615\work\tensorflow-1.1.0\tensorflow\cor_1498062690615\work\tensorflow-1.1.0\tensorflow\core\platform\cpu_feature_guard.cc:45] The TensorFlow library wasn't compiled to use SSE4.2 instructions, but these are available on your machine and could speed up CPU computations.
2017-07-23 17:48:29.226681: W d:\nwani\l\tensorflow_14and could speed up CPU computations.
2017-07-23 17:48:29.225877: W d:\nwani\l\tensorflow_1498062690615\work\tensorflow-1.1.0\tensorflow\core\platform\cpu_feature_guard.cc:45] The TensorFlow library wasn't compiled to use SSE4.1 instructions, but these are available on your machine and could speed up CPU computations.
2017-07-23 17:48:29.226233: W d:\nwani\l\tensorflowe_guard.cc:45] The TensorFlow library wasn't compiled to use SSE3 instructions, but these are available on your machine -07-23 17:48:29.224819: W d:\nwani\l\tensorflow_1498062690615\work\tensorflow-1.1.0\tensorflow\core\platform\cpu_feature_guard.cc:45] The TensorFlow library wasn't compiled to use SSE2 instructions, but these are available on your machine and could speed up CPU computations.
2017-07-23 17:48:29.225278: W d:\nwani\l\tensorflow_1498062690615\work\tensorflow-1.1.0\tensorflow\core\platform\cpu_featur\tensorflow\core\platform\cpu_feature_guard.cc:45] The TensorFlow library wasn't compiled to use SSE instructions, but these are available on your machine and could speed up CPU computations.
20172017-07-23 17:48:29.224365: W d:\nwani\l\tensorflow_1498062690615\work\tensorflow-1.1.0

Traceback (most recent call last):
  File "C:\ProgramData\Anaconda3\lib\site-packages\pandas\core\indexes\base.py", line 2393, in get_loc
    return self._getitem_column(key)
  File "C:\ProgramData\Anaconda3\lib\site-packages\pandas\core\frame.py", line 2069, in _getitem_column
    return self._get_item_cache(key)
  File "C:\ProgramData\Anaconda3\lib\site-packages\pandas\core\generic.py", line 1534, in _get_item_cache
    values = self._data.get(item)
  File "C:\ProgramData\Anaconda3\lib\site-packages\pandas\core\internals.py", line 3590, in get
    loc = self.items.get_loc(item)
  File "C:\ProgramData\Anaconda3\lib\site-packages\pandas\core\indexes\base.py", line 2395, in get_loc
    return self._engine.get_loc(self._maybe_cast_indexer(key))
  File "pandas\_libs\index.pyx", line 132, in pandas._libs.index.IndexEngine.get_loc (pandas\_libs\index.c:5239)
  File "pandas\_libs\index.pyx", line 154, in pandas._libs.index.IndexEngine.get_loc (pandas\_libs\index.c:5085)
  File "pandas\_libs\hashtable_class_helper.pxi", line 1207, in pandas._libs.hashtable.PyObjectHashTable.get_item (pandas\_libs\hashtable.c:20405)
  File "pandas\_libs\hashtable_class_helper.pxi", line 1215, in pandas._libs.hashtable.PyObjectHashTable.get_item (pandas\_libs\hashtable.c:20359)
KeyError: 'Survived'
    return self._engine.get_loc(key)
  File "pandas\_libs\index.pyx", line 132, in pandas._libs.index.IndexEngine.get_loc (pandas\_libs\index.c:5239)
  File "pandas\_libs\index.pyx", line 154, in pandas._libs.index.IndexEngine.get_loc (pandas\_libs\index.c:5085)
  File "pandas\_libs\hashtable_class_helper.pxi", line 1207, in pandas._libs.hashtable.PyObjectHashTable.get_item (pandas\_libs\hashtable.c:20405)
  File "pandas\_libs\hashtable_class_helper.pxi", line 1215, in pandas._libs.hashtable.PyObjectHashTable.get_item (pandas\_libs\hashtable.c:20359)
KeyError: 'Survived'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Users\jamil\Desktop\Code\Python\TensorFlow\titanic\titanic.py", line 90, in <module>
    main()
  File "C:\Users\jamil\Desktop\Code\Python\TensorFlow\titanic\titanic.py", line 83, in main
    results = m.evaluate(input_fn=lambda: eval_input_fn(test_data), steps=1)
  File "C:\ProgramData\Anaconda3\lib\site-packages\tensorflow\python\util\deprecation.py", line 281, in new_func
    return func(*args, **kwargs)
  File "C:\ProgramData\Anaconda3\lib\site-packages\tensorflow\contrib\learn\python\learn\estimators\estimator.py", line 518, in evaluate
    log_progress=log_progress)
  File "C:\ProgramData\Anaconda3\lib\site-packages\tensorflow\contrib\learn\python\learn\estimators\estimator.py", line 801, in _evaluate_model
    features, labels = input_fn()
  File "C:\Users\jamil\Desktop\Code\Python\TensorFlow\titanic\titanic.py", line 83, in <lambda>
    results = m.evaluate(input_fn=lambda: eval_input_fn(test_data), steps=1)
  File "C:\Users\jamil\Desktop\Code\Python\TensorFlow\titanic\titanic.py", line 49, in eval_input_fn
    return input_fn(test_data)
  File "C:\Users\jamil\Desktop\Code\Python\TensorFlow\titanic\titanic.py", line 40, in input_fn
    Continuous_cols = {k: tf.constant(data[k].values) for k in Columns}
  File "C:\Users\jamil\Desktop\Code\Python\TensorFlow\titanic\titanic.py", line 40, in <dictcomp>
    Continuous_cols = {k: tf.constant(data[k].values) for k in Columns}
  File "C:\ProgramData\Anaconda3\lib\site-packages\pandas\core\frame.py", line 2062, in __getitem__

A: The problem comes from these lines:
m.fit(input_fn=train_input_fn(train_data), steps=200)
results = m.evaluate(input_fn=eval_input_fn(test_data), steps=1)

The input_fn argument is expected to be a function that takes no arguments and returns a tuple, whereas you are calling the train_input_fn()/eval_input_fn() functions and passing their return values (a tuple).
The easiest way to fix this problem is to wrap train_input_fn(train_data) and eval_input_fn(test_data) in a lambda expression, as follows:
m.fit(input_fn=lambda: train_input_fn(train_data), steps=200)
results = m.evaluate(input_fn=lambda: eval_input_fn(test_data), steps=1)

The expression lambda: train_input_fn(train_data) is a function that takes no arguments, and when called it returns the value of train_input_fn(train_data), which is a tuple.


text:
Q: Remove all tags except for img tag I need an regular expression or something else to remove all tags in a contentEditable div, but to keep img tag with specific class or id, how I can do this?
Now I use:
.replace(/(<\/?.*?>)/gi, '');

but it removes all tags.
I made this :
var element = document.getElementById("myDiv").children;
   for(var i=0; i<element .length;i++)
   {
     if(element[i].tagName != "IMG" || element[i].className != "requiredClassName")
     {
       element[i].parentNode.removeChild(element[i]);
     }
   }

A: ( if you need plain JS ): Maybe the better way is to collect all elements then after check their class/id and perform action. Good idea is to use DOM, not regexp. DOM is for HTML elements manipulation.
( or use jQuery ): Simple code can do that thing. Just collect all div's children and check their class in .each() loop;
For e.g.:
$('#contentEditable').each( function( index ) {
    if( !this.is( 'img' ) && ( this.is('.someclass') || this.is('#someid') ) ) {
        this.remove();
    }
});

Hope it helps you.
P.S.:
Be careful when you are using greedy quantification .*
It will get all text between any < >, so if you have code listed below regexp (<\/?.*?>) will collect whole code.

            Stack Exchange

A: var child=document.getElementById('editableDIV').firstChild;
while(child) {
  var removeNode=null;
  if(child.tagName&&(child.tagName.toUpperCase()!=='IMG'||
     child.id!=='myid'||
     child.className!=='myclass')) removeNode=child;
  child=child.nextSibling;
  if(removeNode)removeNode.parentNode.removeChild(removeNode);
}

A: var editableDiv = document.getElementById("MyEditableDiv")
var editableDivImgs = editableDiv.getElementsByTagName("img")
for (var i = 0; i < editableDivImgs.length; i++) {
    if(editableDivImgs[i].className != "safe")
    {
        editableDivImgs[i].parentNode.removeChild(editableDivImgs[i])
    }
}

have you tried something like that?

A: Instead of removing all other elements extract all imgs and concatenate them into a new string:
var regex = //gmi;
var imgsOnly = '';
var img;
while( ( img = regex.exec(str) ) !== null ) {
    imgsOnly += img;
}
alert( imgsOnly );


text:
Q: Get url of document library from REST call I am working with O365 SharePoint site where I need to get the name and URL for the document libraries in a site collection. I have made a rest call for it as:
https://site/_api/web/lists and select BaseTemplate = 101.
I have managed to get the name of the document library from below code:
$.ajax({
        url: siteUrl  + "/_api/web/lists",
        method: "GET",
        headers: { "Accept": "application/json; odata=verbose" },
        success: function (data) {
            var tempArray = data.d.results;
             $.each(data.d.results, function(index, item){
                 if(item.BaseTemplate == "101")
                 {
                    var tempArray = new Array(2);
                    tempArray[0]= item.Title;
                 }
            });
        },
        error: function (data) {
           alert(JSON.stringify(error));
        }

Now, I need to get the URL of the each document library. When I access the value of
        item.__metadata.uri

it gives me a value which is a url that is not accessible otherwise. Please get me out of this problem.

A: In order to return list url you could utilize List.RootFolder.ServerRelativeUrl property.
Some recommendations
From performance perspective prefer server side filtering over client side one, the example below demonstrates how to query lists filtered by BaseTemplate:
/_api/Web/Lists?filter=BaseTemplate eq '101'

Example
$.ajax({
        url: _spPageContextInfo.webAbsoluteUrl  + "/_api/web/lists?filter=BaseTemplate eq '101'&$expand=RootFolder",
        method: "GET",
        headers: { "Accept": "application/json; odata=verbose" },
        success: function (data) {
            var lists = data.d.results;
             $.each(lists, function(i, list){
                 var listUrl = list.RootFolder.ServerRelativeUrl;
                 console.log(listUrl);
             });
        },
        error: function(data) {
           console.log(JSON.stringify(data));
        }
      });


text:
Q: What is the maximum size of azure easy tables? I searched on the internet and not found any answer related to it.
Could someone tell what is the maximum size of data we can accommodate with azure easy tables?
What is the maximum size we can have a backup of?
Thanks

A: Before using the Azure Easy Table, we need to configure the connections of Azure SQL and Azure Storage. The data of Azure Easy Table will be stored in Azure SQL database and Azure Storage.

Could someone tell what is the maximum size of data we can accommodate with azure easy tables?

So the maximum size of data we can accommodate with azure easy tables depends on the Azure SQL database which you choose.


text:
Q: Polymer 1.x: How to format a number while typing it into paper-input? TL;DR: I want my numbers to look like 1,500 (not 1500) when entering it in an <input (actually <paper-input or even <iron-input?) form field. Similar to this example except using Polymer only and not AngularJS.
I want to format a number in paper-input (using, say, Numeral.js) while it's being entered by the user. I don't really know where to begin or what to try. I want to access the numeric value in the JS, but I want the user to be able to see the nicely formatted (string) version while entering it.
Is this even possible? Or perhaps I might need a separate display field? But then that would defeat the purpose of the paper-elements from a UX standpoint? Any help?
Also, note per the second comment on this SO question:

Worth noting that Number.prototype.toLocaleString still does not work in Safari, in 2016. Instead of actually formatting the number, it just returns it, no error thrown. Having the biggest facepalm today as a result of that... #goodworkApple – aendrew

Here is the jsbin. ... http://jsbin.com/wosoxohixa/1/edit?html,output

http://jsbin.com/wosoxohixa/1/edit?html,output

<!doctype html>
<head>
  <meta charset="utf-8">
  <base href="https://polygit.org/components/">
  <script src="webcomponentsjs/webcomponents-lite.min.js"></script>
  <link href="polymer/polymer.html" rel="import">
  <link href="paper-input/paper-input.html" rel="import">
  <script src="//cdnjs.cloudflare.com/ajax/libs/numeral.js/1.4.5/numeral.min.js"></script>
</head>
<body>

<dom-module id="x-element">

<template>
  <style></style>

<paper-input value="{{num}}"></paper-input>

</template>

<script>
  (function(){
    Polymer({
      is: "x-element",
      properties: {
        num: {
          type: Number,
          value: function() {
            return numeral(1500).format('0,0');
          },
        },
      },
    });
  })();
</script>

</dom-module>

<x-element></x-element>

</body>

A: Based on the answer from @akc42, I constructed the following working jsBin. ... http://jsbin.com/zunezojuzu/1/edit?html,console,output

http://jsbin.com/zunezojuzu/1/edit?html,console,output

<!doctype html>
<head>
  <meta charset="utf-8">
  <base href="https://polygit.org/components/">
  <script src="webcomponentsjs/webcomponents-lite.min.js"></script>
  <link href="polymer/polymer.html" rel="import">
  <link href="paper-input/paper-input.html" rel="import">
  <script src="//cdnjs.cloudflare.com/ajax/libs/numeral.js/1.4.5/numeral.min.js"></script>
</head>
<body>

<dom-module id="x-element">

<template>
  <style></style>

<paper-input value="{{num}}"></paper-input>

</template>

<script>
  (function(){
    Polymer({
      is: "x-element",
      properties: {
        num: {
          type: String,
          observer: '_numChanged',
        },
      },
      attached: function() {
        this.numBeingChanged = false;
      },
      _numChanged: function(num) {
        console.log('num', num);
        if (!this.numBeingChanged) {
          this.numBeingChanged = true; //prevent recursion
          var x = num.replace(/\D/g,'')
          x = parseInt(x);
          console.log('x', x);
          this.set('num', numeral(x).format('0,0'));
          this.numBeingChanged = false;
        }
      }
    });
  })();
</script>

</dom-module>

<x-element></x-element>

</body>

A: I do something similar with a datepicker based around paper input.  Put an observer on the num property, and it will get called as every new character arrives.
You also need to be careful with validation as you may end up trying to validate 1,0 if that is the way the user has typed it in. (assuming he may type with or without your formatiing


text:
Q: How to target update 1 / update 2, etc .. in instruction {$IF CompilerVersion > xx} I often do stuff like this :
  {$IF CompilerVersion > 31} // berlin
    {$MESSAGE WARN 'check the code below'}
  {$ENDIF}

but how to also target berlin update 1, berlin update 2, etc ... ?
because 31 is for berlin and 32 is for tokyo ... no gap between.

A: Peek in your registry.
I have Seattle Update 1, my about box mentions Delphi 10 Seattle and C++Builder 10 Seattle Subscription Update 1 *.
That is in Computer\HKEY_CURRENT_USER\Software\Embarcadero\BDS\17.0\InstalledUpdates under a value named Main Product Update.
You may have to do some detective work to determine the actual strings
(or readers here can supply the value strings they have).
You can't use your conditional compilation, but at least you can warn from code.

Notes:
- Looking at the version info of a CodeGear DLL could also be an option.
- That same info is also in C:\programdata\embarcadero\bds\17.0\installedupdates.dat and C:\users\all users\embarcadero\bds\17.0\installedupdates.dat
* Note the missing space in C++Builder


text:
Q: PHP create backup /copy file + counter I have file called test.json
I should create a backup file in any action and I just do the following action
copy()

and then it creates "test_backup_1.json"
but in the next action again I need to create "test_backup_2.json" and in the next action call: "test_backup_3.json" and so on...
How can I do that in a dynamically way . ?

A: The best way to store or backup of the file using unique key(UUID/GUID) or date prefix or suffix to the file name.
$fileName = 'test_backup_' .  date("d-m-Y_H:i:s") . '.json';
copy("file.json", $fileName);

But as per your request, we can achieve that using glob
Get all the json files from your back-up folder,
$files = glob("/path/to/directory/*.json");

If you want to get exactly matched pattern files.
$uploadDir = 'path/to/your/upload/dir';
chdir($uploadDir);
// Will give all the files which file names starts as test_backup
$files = glob('test_backup_*');

The $files array contains the following from the example directory:
Array
(
    [0] => /path/to/directory/test_backup.json
    [1] => /path/to/directory/test_backup_1.json
    [2] => /path/to/directory/test_backup_2.json
)

Get the count of array then generate the index based on the count, i.e
$count = count($files);
$fileName = 'test_backup_' . $count  . '.json';
copy("file.json", $fileName);

For more info about glob - http://php.net/manual/en/function.glob.php


text:
Q: Prevent browser from forced scroll I have a problem, I'm working with draggable elements in my page, the entire parent elements has overflow: hidden and it's working fine, but, if I force the page to scroll dragging elements outside, an unwanted scrolling will happen. You can see it in action in the fiddle bellow dragging the gray box to the right...
Fiddle: http://jsfiddle.net/a6vzhk2z/

EDIT: it is expected that half of the element can go outside the page

A: Did you mean this?
$(".draggable-box").draggable({
    containment: [-100,100,windowWidth - 200,100]
});

Demo
EDIT: Maybe this would be nicer:
$(".draggable-box").draggable({
    containment: [0,100,windowWidth - 200,100]
});

EDIT #2: The problem isn't the box. The mouse is the problem. It only happens if the mouse moves outside the window. Prevent the mouse going out of the window should solve the problem.

A: So when you drag the box all the way to the right, it increases the screen size slightly beyond the scoll bar, correct?
This may not be what you want, but when I subtracted an additional 100 from the windowWidth, it seemes to have fixed the problem:
$(".draggable-box").draggable({
    containment: [-100,100,windowWidth-200,100]
});

A: I found the solution, my solution was an position to the parent element.
This is my new SCSS for #container:
#container{
  position: relative;
  height: calc(100% - 50px);
  overflow: hidden;

  #text{
    @include full-height();
    overflow-y: auto;
    overflow-x: hidden;
  }
}

Here is a fiddle: http://jsfiddle.net/o8Lrpzb2/1/


text:
Q: Split a string but keep the Comma I need to split a sentence string that keeps the non-whitespace such as . or ,. I need them to be included within the array string being split. Not in their own seperate array index.
const regex = /\W(?:\s)/g

function splitString (string) {
  return string.split(regex)
}

console.log(splitString("string one, string two, thing three, string four."))

// Output ["string one", "string two", "thing three", "string four."]
// Desired ["string one,", "string two,", "string three,", "string four."]

A: Perhaps using a match approach instead of a split approach:
"string one, string two, thing three, four four.".match(/\w+(?:\s\w+)*\W?/g);
// [ 'string one,', 'string two,', 'thing three,', 'four four.' ]

or something more specific (this way you can easily choose one or several delimiter characters):
"string one, string two, thing three, four four.".match(/\S.*?(?![^,]),?/g);


text:
Q: Tables with rounded corners I was wondering what would be the best approach for creating tables in a pdf that have rounded corners using the iTextSharp 5.x+ library.

A: There's no way to create an iTextSharp PdfPTable with rounded corners but what you could do is draw a table border with rounded corners using the PdfContentByte.RoundRectangle() method.
Here's a snippet that demonstrates this:
Document doc = new Document();
using (FileStream fs = new FileStream("RoundRectangle Demo.pdf", FileMode.Create)) {
PdfWriter writer = PdfWriter.GetInstance(doc, fs);
    doc.Open();
    PdfContentByte cb = writer.DirectContent;

    // Bottom left coordinates x & y, followed by width, height and radius of corners.
    cb.RoundRectangle(100f, 500f, 200f, 200f, 2f);
    cb.Stroke();

    doc.Close();
}

This snippet is a condensed version of code I found in the article iTextSharp - Drawing shapes and Graphics on www.mikesdotnetting.com.  You'll want to take a close look at his other articles if you haven't already.

A: I assume that if you are wanting a table with rounded corners, you're looking for some flashy (or at least pretty) formatting on your table.  If that is the case, I would recommend turning off all the borders in your iTextSharp table, and using a graphic image as the background on your page.  You can then make the graphic background as intricate and fancy as you want (shading, gradients, rounded corners, etc.) with very little trouble.  Then, just line up your table with the background image.
If your data format will change often, you will not want to use this approach.

A: If you have iTextSharp source code, add the following to PdfContentByte class:
/// <summary>
        /// Enumuration for defining corners you want rounded.
        /// </summary>
        [Flags()]
        public enum Corners {None = 0,All=15,Top=3,Bottom=12, TopLeft = 1, TopRight=2, BottomLeft=4, BottomRight=8};

        /// <summary>
        /// Adds a round rectangle to the current path, with rounded conrners as specified by roundCorners.
        /// </summary>
        /// <param name="x"></param>
        /// <param name="y"></param>
        /// <param name="w"></param>
        /// <param name="h"></param>
        /// <param name="r"></param>
        /// <param name="roundCorners"></param>
        public void RoundRectangle(float x, float y, float w, float h, float r,Corners roundCorners)
        {
            if (w < 0)
            {
                x += w;
                w = -w;
            }
            if (h < 0)
            {
                y += h;
                h = -h;
            }
            if (r < 0)
                r = -r;
            float b = 0.4477f;
            if((roundCorners & Corners.BottomLeft) == Corners.BottomLeft)
                MoveTo(x + r, y);
            else
                MoveTo(x, y);

            if ((roundCorners & Corners.BottomRight) == Corners.BottomRight)
            {
                LineTo(x + w - r, y);
                CurveTo(x + w - r * b, y, x + w, y + r * b, x + w, y + r);
            }
            else
                LineTo(x + w, y);

            if ((roundCorners & Corners.TopRight ) == Corners.TopRight)
            {
                LineTo(x + w, y + h - r);
                CurveTo(x + w, y + h - r * b, x + w - r * b, y + h, x + w - r, y + h);
            }
            else
                LineTo(x + w, y + h);

            if ((roundCorners & Corners.TopLeft)  == Corners.TopLeft)
            {
                LineTo(x + r, y + h);
                CurveTo(x + r * b, y + h, x, y + h - r * b, x, y + h - r);
            }
            else
                LineTo(x , y + h);

            if ((roundCorners & Corners.BottomLeft) == Corners.BottomLeft)
            {
                LineTo(x, y + r);
                CurveTo(x, y + r * b, x + r * b, y, x + r, y);
            }else
                LineTo(x, y);
        }

Next step is to implment IPdfPCellEvent interface:
public class myCellEvent : IPdfPCellEvent
    {
        #region members
        PdfContentByte.Corners _roundedCorners;
        float _roundness;
        #endregion

        #region ctor
        public myCellEvent()
            :this( PdfContentByte.Corners.All,2f)
        {

        }

        public myCellEvent(PdfContentByte.Corners roundedCorners)
            : this(roundedCorners, 2f)
        {

        }

        public myCellEvent(PdfContentByte.Corners roundedCorners,float roundness)
        {
            _roundedCorners = roundedCorners;
            _roundness = roundness;

        }
        #endregion

        #region IPdfPCellEvent Members
        public void CellLayout(PdfPCell cell, Rectangle position, PdfContentByte[] canvases)
        {
            PdfContentByte cb = canvases[PdfPTable.LINECANVAS];
            cb.RoundRectangle(position.Left, position.Bottom, position.Right - position.Left, position.Top - position.Bottom, this._roundness, this._roundedCorners);
            cb.SetColorStroke(new BaseColor(System.Drawing.Color.Black));
            cb.SetColorFill(new BaseColor(System.Drawing.Color.Beige));
            cb.FillStroke();
            cb.Stroke();
        }
        #endregion
    }

Then you round what ever corners you want to produce the rounded table of choice:
PdfPTable table = new PdfPTable(1);

                PdfPCell cell = new PdfPCell(new Phrase(10, atext, f2));
                cell.Border = 0;
                cell.Padding = 5f;
                cell.CellEvent = new myCellEvent(PdfContentByte.Corners.Top,2f);
                table.AddCell(cell);

If you like the answer ... give it a vote :)

A: Private Function pdfDIF() As Byte()
     Dim celevent As New PdfPCellEvent
 Dim tableImportes As New PdfPTable(1)
 tableImportes.SetTotalWidth({10 * dpixcm})

 Dim cellImportes = New PdfPCell(New Phrase("IMPORTE", COURIER9Bold))
 cellImportes.BorderWidth = 0
 cellImportes.HorizontalAlignment = Element.ALIGN_CENTER
 cellImportes.CellEvent = celevent
 tableImportes.AddCell(cellImportes)

end function
Public Class PdfPCellEvent
    Implements IPdfPCellEvent
Public Sub CellLayout(cell As iTextSharp.text.pdf.PdfPCell, position As iTextSharp.text.Rectangle, canvases() As iTextSharp.text.pdf.PdfContentByte) Implements iTextSharp.text.pdf.IPdfPCellEve`enter code here`nt.CellLayout
    Dim cb As PdfContentByte = canvases(PdfPTable.LINECANVAS)
   cb.RoundRectangle(position.Left,position.Bottom,position.Width,position.Height,10)
    cb.SetLineWidth(1)
    cb.SetCMYKColorStrokeF(0.0F, 0.0F, 0.0F, 1.0F)
    cb.Stroke()
End Sub

End Class


text:
Q: Problem in subsetting on the base of date:comparison (6) is possible only for atomic and list types I have Dataset like this:
 1 CCL    2022-05-31  13.9  21.2
 2 CCL    2022-02-28  20.3  26.0
 3 CCL    2021-11-30  17.6  25.5
 4 CCL    2021-08-31  24.1  30.4
 5 CCL    2021-05-31  30.2  36.4
 6 CCL    2021-02-28  26.3  35.1
 7 CCL    2020-11-30  20.0  32.2
 8 CCL    2020-08-31  16.5  27.0
 9 CCL    2020-05-31  16.8  26.3
10 CCL    2020-02-29  33.5  35.4

I want to filter on the base of "date" that is a date variable.
I used this code:
DFC<- dfc %>% filter (
  dfc$date > "2020-05-31")

Everything was ok, but now R gives me this error:
comparison (6) is possible only for atomic and list types

How Can I solve this problem?
Best regards


text:
Q: count number of records every month on group by clause in sql I need to exceute a report  every month where I have town, street name, t_number,t_date_time_issued where the t_number is the ticket issued on every town. I need to now how many tickets been issued every month in each year and what is the difference between the last year this month  total issued tickets  - present year this month total issued tickets . I tied the following but for no luck.
SELECT [Town],
      [Site Name],

  SUM(CASE datepart(month,t_date_time_issued) WHEN 1 THEN 1 ELSE 0 END) AS 'January',
  SUM(CASE datepart(month,t_date_time_issued) WHEN 2 THEN 1 ELSE 0 END) AS 'February',
  SUM(CASE datepart(month,t_date_time_issued) WHEN 3 THEN 1 ELSE 0 END) AS 'March',
  SUM(CASE datepart(month,t_date_time_issued) WHEN 4 THEN 1 ELSE 0 END) AS 'April',
  SUM(CASE datepart(month,t_date_time_issued) WHEN 5 THEN 1 ELSE 0 END) AS 'May',
  SUM(CASE datepart(month,t_date_time_issued) WHEN 6 THEN 1 ELSE 0 END) AS 'June',
  SUM(CASE datepart(month,t_date_time_issued) WHEN 7 THEN 1 ELSE 0 END) AS 'July',
  SUM(CASE datepart(month,t_date_time_issued) WHEN 8 THEN 1 ELSE 0 END) AS 'August',
  SUM(CASE datepart(month,t_date_time_issued) WHEN 9 THEN 1 ELSE 0 END) AS 'September',
  SUM(CASE datepart(month,t_date_time_issued) WHEN 10 THEN 1 ELSE 0 END) AS 'October',
  SUM(CASE datepart(month,t_date_time_issued) WHEN 11 THEN 1 ELSE 0 END) AS 'November',
  SUM(CASE datepart(month,t_date_time_issued) WHEN 12 THEN 1 ELSE 0 END) AS 'December',
  SUM(CASE datepart(year,t_date_time_issued) WHEN 2012 THEN 1 ELSE 0 END) AS 'TOTAL'
FROM
    [VCS].[dbo].[manual issued sites]  as a

  inner join icps.dbo.tickets as b on
  b.[t_street_name]COLLATE DATABASE_DEFAULT  = a.[Town] COLLATE DATABASE_DEFAULT and
  b.[t_zone_name]COLLATE DATABASE_DEFAULT  = a.[Site Name] COLLATE DATABASE_DEFAULT

where year(t_date_time_issued) = '2012'
  GROUP BY  month(t_date_time_issued),town,sitename

   order by town

but i need something like
town sitename  jan feb march april june july..... total
abc  bbb         10 10  15   25     30   45       xyz..
ybb  jjjj        25  14  45  25  312  455    ....uuu
----------

the query above excuted like this....
Town    Site Name   January February    March   April   May June    July    August  September   October November    December    TOTAL
Bawtry  Market Hill 155 0   0   0   0   0   0   0   0   0   0   0   155
Bawtry  Market Hill 0   194 0   0   0   0   0   0   0   0   0   0   194
Bawtry  Market Hill 0   0   144 0   0   0   0   0   0   0   0   0   144
Bawtry  Market Hill 0   0   0   114 0   0   0   0   0   0   0   0   114
Formby  The Cloisters   0   0   0   0   0   0   0   0   0   0   0   36  36
Kidderminster   Crossley Retail Park    27  0   0   0   0   0   0   0   0   0   0   0   27
Kidderminster   Crossley Retail Park    0   15  0   0   0   0   0   0   0   0   0   0   15
Kidderminster   Crossley Retail Park    0   0   20  0   0   0   0   0   0   0   0   0   20


text:
Q: Optimizing a multivariate symmetric (permutation-invariant) function Let $\ell$ and $d$ be two integers such that $\ell \le d$.
I would like to find the global maxima of the following symmetric function $f\colon (0,1]^n \to \mathbb{R}$,
$$f(x_1, \ldots, x_n) := \sum_{\substack{S \subseteq [n] \\ |S| = \ell}} \sum_{\substack{z \in [d]^S \\ \sum_i z_i = d}} \prod_{i \in S} x_i \left(\ln\Bigl(\frac{e}{x_i^{1/z_i}}\Bigr)\right)^{z_i/2},$$
subject to $x_1 + \dots + x_n = 1$.
Note that this function has the same value under any permutation of the coordinates of $x$.
For example, when $n = 3, d = 2, \ell = 2$, we have
$$f(x,y,z) = xy \sqrt{\ln(e/x) \ln(e/y)} + yz \sqrt{\ln(e/y) \ln(e/z)} + xz \sqrt{\ln(e/x) \ln(e/z)} .$$
When $n=3, d=3, \ell=2$, we have
\begin{multline*}
f(x,y,z) = xy \ln(e/\sqrt{x}) \sqrt{\ln(e/y)} + xy \sqrt{\ln(e/x)} \ln(e/\sqrt{y}) + yz \ln(e/\sqrt{y}) \sqrt{\ln(e/z)} + \\yz \sqrt{\ln(e/y)} \ln(e/\sqrt{z}) + xz \ln(e/\sqrt{x}) \sqrt{\ln(e/z)} + xz \sqrt{\ln(e/x)} \ln(e/\sqrt{z}) .
\end{multline*}
The Purkiss Principle says that the point $(1/n, \ldots, 1/n)$ is a local maxima.
I believe this is also the global maximum, but cannot think of a way to prove this.
One possible way is to show that this function is strictly concave, but it's not clear at all if this is true and I don't know how to show its Hessian is strictly negative-definite.
Is there an easy way to see this? or is my guess simply not true?
Edit: In the original question, the factor $\ln\Bigl(\frac{e}{x_i^{1/z_i}}\Bigr)$ was $\ln\Bigl(\frac{e}{x_i}\Bigr)$, which was clearly false as pointed out by @fedja.

A: One can show that this function is Schur-concave using the Schur-Ostrowski criterion, which then implies the maximum is attained at the diagonal.
See also
https://math.stackexchange.com/questions/439649/are-elementary-symmetric-polynomials-concave-on-probability-distributions
I will omit the calculations here.


text:
Q: Chinese punctuation problem I am trying to move a Chinese punctuation mark to the head of a character. I am using the following macro, which works fine. But if I redefine the \CJKpunctsymbol, it will be a messy. Can any one help me on this?
works fine code - which directly apply to a punctuation:
\hskip -0.9em \vbox to 0.1em {\vskip -1em{\hbox to 0.9em {。}}}

Redefine \CJKpunctsymbol - the \hbox will be very long and can't resize.
\def\vCJKpunctsymbol#1{\hskip -0.9em \vbox to 0.1em {\vskip -1em {\hbox to 0.9em {\CJKsymbol{#1}}}}}
\let\CJKpunctsymbol\vCJKpunctsymbol

The following 2 pictures are examples. I use \fbox to make it clear.

A: For old-style punctuation (句读), I think it can be defined like this:
\catcode`。\active
\def。{\makebox[0pt][l]{\hskip-.25em\raisebox{1ex}{\string。}}}

No xeCJK punctuation features should be used, since the current version of xeCJK does not support vertical typesetting properly.
An example:
\documentclass{article}
\usepackage{xeCJK}

\setCJKmainfont[RawFeature={script=hani:language=CHN:vertical:+valt}]{SimSun}

\catcode`。\active
\def。{\makebox[0pt][l]{\hskip-.25em\raisebox{1ex}{\string。}}}
\catcode`、\active
\def、{\makebox[0pt][l]{\hskip-.25em\raisebox{1ex}{\string、}}}

\begin{document}

\rotatebox{-90}{%
子曰。学而时习之、不亦说乎。}

\end{document}


text:
Q: change vim status line while executing command I would like to change the vim status line which is shown while vim is busy executing an external command.
I have a vim script which pipes lines of text from vim into some external program using "!". After execution vim waits for the output of the command to replace the lines with it. While it is waiting I would like to show the status of the external command in the statusline.
Is this possible?

A: I would solve this using a temporary global variable. Here is a simple function that returns the value of a variable g:temp_var if it exists, otherwise it returns an empty string:
function! TemporaryStatus()
    if exists("g:temp_var")
        return g:temp_var
    else
        return ""
    endif
endfunction

You can set the statusline to use the return value of this function like this:
set statusline=%!TemporaryStatus()

Then, when you call the slow external command, just set the temporary variable beforehand (using the message you want to be displayed), and unlet it afterwards. For example:
...
let g:temp_var = "I am calling a slow external command"
redraw!
call SlowExternalCommand()
unlet g:temp_var
redraw!
...

Note that the redraw! commands are necessary to make sure Vim updates the display (and therefore uses the updated value of g:temp_var in the statusline).
EDIT
Of course it would be much simpler to display the message by echoing it and clearing the display afterwards, like this:
...
redraw!
echo "I am calling a slow external command"
call SlowExternalCommand()
redraw!
...

This way the message will be displayed on the Vim command line, rather than in the statusline. You don't need any of the functions defined above.