text:
Q: Setting property of a class dependent on autogenerated value of the same class I have 2 properties in a class,
MpzId which is autogenerated on save
and PledgeId which I want to copy the string value of MpzId after it gets autogenerated. Right now I am saving the instance and then fetching the MpzId from the saved, re-assigning to PledgeId and resave. Is there any better solution to this?


text:
Q: Check if laravel model got saved or query got executed I've seen alot of people using this way to check if a laravel model got saved. So now I wonder if it is a safe way.
And also can I check if the queries bellow got executed like this
Check if model got saved
Eg:
$myModel = new User();

$myModel->firstname = Input::get('firstname');
$myModel->lastname = Input::get('lastname');

$myModel->save();

//Check if user got saved
if ( ! $myModel->save())
{
  App::abort(500, 'Error');
}

//User got saved show OK message
return Response::json(array('success' => true, 'user_added' => 1), 200);

Is the above a safe way to check whenever my model got saved or not?
Check if query returned a result
Eg:
$UserProduct = Product::where('seller_id', '=', $userId)->first();

if (! $UserProduct)
{
    App::abort(401); //Error
}

Does above return an error if no product where found?
Check if query got executed
Eg:
$newUser = User::create([
        'username' => Input::get('username'),
        'email' => Input::get('email')
]);

//Check if user was created
if ( ! $newUser)
{
    App::abort(500, 'Some Error');
}

//User was created show OK message
return Response::json(array('success' => true, 'user_created' => 1), 200);

Does above check if a user was created?

A: Check if model got saved
save() will return a boolean, saved or not saved. So you can either do:
$saved = $myModel->save();

if(!$saved){
    App::abort(500, 'Error');
}

Or directly save in the if:
if(!$myModel->save()){
    App::abort(500, 'Error');
}

Note that it doesn't make sense to call save() two times in a row like in your example. And by the way, many errors or problems that would keep the model from being saved will throw an exception anyways...
Check if query returned a result
first() will return null when no record is found so your check works find. However as alternative you could also use firstOrFail() which will automatically throw a ModelNotFoundException when nothing is found:
$UserProduct = Product::where('seller_id', '=', $userId)->firstOrFail();

(The same is true for find() and findOrFail())
Check if query got executed
Unfortunately with create it's not that easy. Here's the source:
public static function create(array $attributes)
{
    $model = new static($attributes);

    $model->save();

    return $model;
}

As you can see it will create a new instance of the model with the $attributes and then call save(). Now if save() where to return true you wouldn't know because you'd get a model instance anyways. What you could do for example is check for the models id (since that's only available after the record is saved and the newly created id is returned)
if(!$newUser->id){
    App::abort(500, 'Some Error');
}

A: You can also check the public attribute $exists on your model.
if ($myModel->exists) {
    // Model exists in the database
}

A: I would do such move to when I use Model::create method :
$activity = Activity::create($data);

if ($activity->exists) {
   // success
} else {
   // failure
}

As for the Save method it's easier because $model->save() returns Bool :
$category = new Category();
$category->category_name = $request->category_name;
$is_saved = $category->save();

if ($is_saved) {
    // success
} else {
    // failure
}

A: /**
 * Store a newly created country in storage.
 *
 * @url /country
 * @method POST
 * @param Request $request
 * @return \Illuminate\Http\JsonResponse
 */
public function store(Request $request)
{
  # Filer & only get specific parameters.
  $request = $request->only('code', 'name', 'status');

  # Assign login user(Auth Control).
  $request['created_by'] = Auth::user()->id;

  # Insert data into `countries` table.
  $country = Country::create($request);

  if(!$country)
    throw new Exception('Error in saving data.');
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Flat families and section of family of curves Let $X$ be a smooth projective surface. Let $L$ be an ample line bundle on $X$. Consider $Y=\{(x,C) : C\in |L|, x\in C\}\subset X\times |L|$. Then $p_2:Y\longrightarrow |L|$ is a family of curves over $|L|$ right?
1) Is this a flat family? How do we check that it is a flat family?
2) Does $p_2:Y\longrightarrow |L|$ admit a section? That is to every $C$ we need to associate a point of $C$ in a continuous manner. Is this possible?
Thanks in advance!

A: For 1), use the fact that $Y$ is a Cartier divisor on $X\times |L|=Z$ and the fibers of $p_2$ are one dimensional. We have an exact sequence, $0\to \mathcal{O}_Z(-Y)\to\mathcal{O}_Z\to \mathcal{O}_Y\to 0$. Tensoring with $k(x)$ for $x\in |L|$, the sequence remains exact and so the Tor is zero, showing $\mathcal{O}_Y$ is flat over $|L|$.
2) is false. For example, take $|L|$ to be the quadrics in $\mathbb{P}^2$. If $p_2$ had a section, it would mean at least that every fiber has  one point which is reduced since the section meets every fiber once. But, there are double lines in the fiber.


text:
Q: Equinumerosity between equivalence classes set and power set I´m currently working on the following problem:
"Let $\xi$ = $\{ $ $\bot$  $\mid $$\bot$ is a equivalence relation over  $\mathbb{N} $$\} $
Show that $\xi$ and $2^\mathbb{N} $ (power set) are equinumerous."
Edit: After some research, I found that I need to proof that $2^\mathbb{N} $ is equinumerous with  $2^\mathbb{NxN} $, because $\xi $ $\space{ }$  $\subseteq$ $\space{ }$$2^\mathbb{NxN} $. Any ideas?

A: To inject $2^{\Bbb N}$ into $\xi$ (to within a factor $2$, but that is finite and can be patched up), given a subset you have an equivalence relation by the partition that subset/its complement.
To show that $|\xi| \le |\Bbb R|$, if $A_i$ is an element of the partition, associate with it the real number $a_i=\sum_{j \in A_i}3^{-j}$.  Now associate the whole partition with the real $\sum_{i=1}^{|A|} a_i4^{-i}$


text:
Q: Mechnical drawing, Tikz, damper + spring + 2 masses I have the following tikz code which I based on https://tex.stackexchange.com/a/13952/15360. Now I want to have the spring, the damper and the 3 arrows have labels. Like for example, F for force and k as spring constant, and d as damper constant.
Do I have to use fixed coordinates? \node[draw] at (0,0) {$F$};?
Or can I do this more clever? Because at the moment the spring is not a node so I have no coordinates of it...
\documentclass{standalone}
\usepackage{tikz}
\usetikzlibrary{calc,patterns,decorations.pathmorphing,decorations.markings}

\begin{document}
\begin{tikzpicture}[every node/.style={draw,outer sep=0pt,thick}]

\tikzstyle{spring}=[thick,decorate,decoration={zigzag,pre length=0.3cm,post
length=0.3cm,segment length=6}]

\tikzstyle{damper}=[thick,decoration={markings,
  mark connection node=dmp,
  mark=at position 0.5 with
  {
    \node (dmp) [thick,inner sep=0pt,transform shape,rotate=-90,minimum
width=15pt,minimum height=3pt,draw=none] {};
    \draw [thick] ($(dmp.north east)+(2pt,0)$) -- (dmp.south east) -- (dmp.south
west) -- ($(dmp.north west)+(2pt,0)$);
    \draw [thick] ($(dmp.north)+(0,-5pt)$) -- ($(dmp.north)+(0,5pt)$);
  }
}, decorate]

\tikzstyle{ground}=[fill,pattern=north east lines,draw=none,minimum
width=0.75cm,minimum height=0.3cm]

\node (M1) [minimum width=1.5cm, minimum height=1.5cm] {$m_1$};
\node (M2) at (3,0) [minimum width=1.5cm, minimum height=1.5cm] {$m_2$};
\draw[spring] ($(M1.east) - (0,0.5)$) -- ($(M2.west) - (0,0.5)$);
\draw[damper] ($(M1.east) + (0,0.5)$) -- ($(M2.west) + (0,0.5)$);
\draw[thick, dashed] ($(M1.north west)$) -- ($(M1.north west) + (0,1)$);
\draw[thick, dashed] ($(M2.north west)$) -- ($(M2.north west) + (0,1)$);
\draw[ultra thick, -latex] ($(M2.north west) + (0,0.75)$) --
                           ($(M2.north west) + (1,0.75)$);
\draw[ultra thick, -latex] ($(M1.north west) + (0,0.75)$) --
                           ($(M1.north west) + (1,0.75)$);
\draw[ultra thick, -latex] ($(M1.west) - (1,0)$) -- ($(M1.west)$);

\end{tikzpicture}

\end{document}

A: If I understand your question correctly this is fairly easy to do. I have included two examples below by modifying your code, by labeling your spring and one arrow. E.g. after
\draw[spring] ($(M1.east) - (0,0.5)$) -- ($(M2.west) - (0,0.5)$)

You can add
node [midway,above] {$k$};

which places a node above and between
($(M1.east) - (0,0.5)$) and ($(M2.west) - (0,0.5)$)
The following code
 \documentclass{standalone}
 \usepackage{tikz}
 \usetikzlibrary{calc,patterns,
                 decorations.pathmorphing,
                 decorations.markings}

 \begin{document}
 \begin{tikzpicture}

 \tikzstyle{spring}=[thick,decorate,decoration={zigzag,pre length=0.3cm,post
 length=0.3cm,segment length=6}]

 \tikzstyle{damper}=[thick,decoration={markings,
   mark connection node=dmp,
   mark=at position 0.5 with
   {
     \node (dmp) [thick,inner sep=0pt,transform shape,rotate=-90,minimum
 width=15pt,minimum height=3pt,draw=none] {};
     \draw [thick] ($(dmp.north east)+(2pt,0)$) -- (dmp.south east) -- (dmp.south
 west) -- ($(dmp.north west)+(2pt,0)$);
     \draw [thick] ($(dmp.north)+(0,-5pt)$) -- ($(dmp.north)+(0,5pt)$);
   }
 }, decorate]

 \tikzstyle{ground}=[fill,pattern=north east lines,draw=none,minimum
 width=0.75cm,minimum height=0.3cm]

 \node[draw,outer sep=0pt,thick] (M1) [minimum width=1.5cm, minimum height=1.5cm] {$m_1$};
 \node[draw,outer sep=0pt,thick] (M2) at (3,0) [minimum width=1.5cm, minimum height=1.5cm] {$m_2$};
 \draw[spring] ($(M1.east) - (0,0.5)$) -- ($(M2.west) - (0,0.5)$)
 node [midway,above] {$k$};
 \draw[damper] ($(M1.east) + (0,0.5)$) -- ($(M2.west) + (0,0.5)$);
 \draw[thick, dashed] ($(M1.north west)$) -- ($(M1.north west) + (0,1)$);
 \draw[thick, dashed] ($(M2.north west)$) -- ($(M2.north west) + (0,1)$);
 \draw[ultra thick, -latex] ($(M2.north west) + (0,0.75)$) --
                            ($(M2.north west) + (1,0.75)$)
                            node [midway, below] {$F_x$};
 \draw[ultra thick, -latex] ($(M1.north west) + (0,0.75)$) --
                            ($(M1.north west) + (1,0.75)$);
 \draw[ultra thick, -latex] ($(M1.west) - (1,0)$) -- ($(M1.west)$);

 \end{tikzpicture}
 \end{document}

gives
 .
Note that I moved the styling of your boxed nodes from the tikzpictureenvironment to the nodes itself to avoid having boxes surrounding the labels.
Also, if you add the positioning library:
\usetikzlibrary{positioning}

You can position new nodes relative to your existing named nodes:
\node (label1) [below=of M1] {A label};

For more information regarding placement of nodes you could take a look at chapter 16.5 in the PGF manual.


text:
Q: What do Netherworld Citizens do? I can convert prisoners into Netherworld Citizens. There are multiple quests that ask you to add them. But nothing explains what their purpose actually is. It just says they give several benefits.

A: Making them citizens doesn't appear to do anything useful beyond side quests and the trophy for making 100 prisoners citizens.

A: The sidequest name is what tells you what making citizens does, quest is called boost pop , items and weapons have a pop limit the amount of innocents it can hold. so making citizen increases your interrogators (random item equipped by them) innocent pop cap higher.


text:
Q: How to bringback an object to its original position after rotation in unity? I have created a project where a cube is rotated when we touch on it. I want the cube to return back to its original position when the user stops touching the cube. Below I have added the source code of rotating a cube:
using UnityEngine;

using System.Collections;

[RequireComponent(typeof(MeshRenderer))]

public class dr : MonoBehaviour
{

    #region ROTATE
    private float _sensitivity = 1f;
    private Vector3 _mouseReference;
    private Vector3 _mouseOffset;
    private Vector3 _rotation = Vector3.zero;
    private bool _isRotating;

    #endregion

    void Update()
    {
        if(_isRotating)
        {
            // offset
            _mouseOffset = (Input.mousePosition - _mouseReference); // apply rotation
            _rotation.y = -(_mouseOffset.x + _mouseOffset.y) * _sensitivity; // rotate
            gameObject.transform.Rotate(_rotation); // store new mouse position
            _mouseReference = Input.mousePosition;
        }

    }

    void OnMouseDown()
    {
        // rotating flag
        _isRotating = true;

        // store mouse position
        _mouseReference = Input.mousePosition;
    }

    void OnMouseUp()
    {
        // rotating flag
        _isRotating = false;
    }

}

edited code:-
using UnityEngine;
using System.Collections;
[RequireComponent(typeof(MeshRenderer))]
public class pt : MonoBehaviour
{
#region ROTATE
private float _sensitivity = 1f;
private Vector3 _mouseReference;
private Vector3 _mouseOffset;
private Vector3 _rotation = Vector3.zero;
private bool _isRotating;
private Quaternion original;

#endregion
void start(){
    original = transform.rotation;
}

void Update()
{
    if(_isRotating)
    {
        // offset
        _mouseOffset = (Input.mousePosition - _mouseReference); // apply rotation
        _rotation.y = -(_mouseOffset.x + _mouseOffset.y) * _sensitivity; // rotate
        gameObject.transform.Rotate(_rotation); // store new mouse position
        _mouseReference = Input.mousePosition;
    }

}

public void OnMouseDown()
{
    // rotating flag
    _isRotating = true;

    // store mouse position
    _mouseReference = Input.mousePosition;
}

public void OnMouseUp()
{
    // rotating flag
    _isRotating = false;
    transform.rotation = original;
}

}
"im trying to rotate a 3d model of a sofa and return to its starting rotation.but if i used this code " whenever if i stopped touching the sofa , it turns to **backside of sofa"**
 i want it to return to initial rotation.u can see initally this is how the sofa looks like and if i stopped touching it returns to its backside of sofa. i want it to return to its front side again if i stopped rotation

A:
I want the cube to return back to its original position when the user
  stopped touching the cube

I can't exactly tell which part of this you are struggling with but you can simply get the position of the GameObject in  the Start or Awake function then set the transform.position to that value when OnMouseUp is called.
private Vector3 originalPos;

void Start()
{
  //Get the original position
  originalPos = transform.position;
}

void OnMouseUp()
{
    _isRotating = false;
    //Reset GameObject to the original position
    transform.position = originalPos;
}

EDIT:
For rotation, it is also the-same thing. Just use Quaternion and transform.rotation instead of Vector3 and transform.position.
private Quaternion originalPos;

void Start()
{
  //Get the original rotation
  originalPos = transform.rotation;
}

void OnMouseUp()
{
    _isRotating = false;
    //Reset GameObject to the original rotation
    transform.rotation = originalPos;
}

You still have to incorporate that into the original code from your answer. If this is something you can't do then consider watching Unity's scripting tutorial here.


text:
Q: Facebook account api not returning tasks when page is added to business manager as a business asset When I add a Facebook Page to Business Manager and then I call the account api as follows:
https://graph.facebook.com//accounts?access_token=&fields=name,access_token, tasks

I get back this response:
{ "data": [ { "name": "", "access_token": "", "id": "" } ] }

But I would expect this response:
{ "data": [ { "name": "", "access_token": "", "id": "", "tasks": [ "ANALYZE", "ADVERTISE", "MESSAGING", "MODERATE", "CREATE_CONTENT", "MANAGE" ] } ] }

In other words, tasks are not returned anymore. How can I know if I still have full access to a page, if the list of tasks is not returned? Is there a way to get the list of tasks, even after I add a page to business manager as a business asset?


text:
Q: Can we install Business Central Workbench 7.36 on TomcatServer? Can we install the business central workbench  7.36 on the tomcat server. In the documentation , only the wars related to the wildfly server are present.
https://www.drools.org/download/download.html
Business Central Workbench
Business Central Workbench is the web application and repository to govern Drools and jBPM assets. See documentation for details about installation.
WildFly 14 WAR
Can you point me to the tomcat installation version of it

A: Yes, you can refer to this link for installing Business central or jBPM on tomcat.

A: It only refers to the wildfly or jboss eap servers. It doesnt show the war file for installing it on tomcat server.

*Business Central (General)
11.1. Installation
11.1.1. War installation
Use the war from the Business Central distribution zip that corresponds to your application server. The differences between these war files are mainly superficial. For example, some JARs might be excluded if the application server already supplies them.

eap7: tailored for Red Hat JBoss Enterprise Application Platform 7
wildfly14: tailored for Wildfly 14


text:
Q: Are capacitive display(s) capable of measuring what fraction of a finger is touched? I'm really curious to get an answer for this question. Since I don't know the functioning of a capacitive display and Google didn't help me on this issue, I landed here. :)

Are capacitive displays used in most modern phones capable of measuring relative fraction of the finger being touched? For example, if I touch the screen and then apply pressure gently, will the system be able to make out the increase in the surface area of contact?

A: A projected capacitance touch screen like the type in your phone is quite capable of creating a reasonably detailed map of the areas of the screen that are covered by your fingers. You could definitely use this to infer the amount of pressure being applied by looking at the contact patch size, and indeed this is apparently how Apple's Force Touch on the watch works (note, the Macbook's new trackpad has actual force sensors on each corner). However, you can probably imagine a lot of issues with making this work reliably, as everyone's fingers are different sizes, and you don't always touch the screen with the same part of your finger.
Another thing is that you can tune the sensitivity of a touch screen so that it can detect objects nearer or further away (which is how glove mode works on some phones) but then you lose the ability to differentiate the actual contact patch of a finger. It may be that Apple is using a sort of analog sensing system where they can infer the contact patch and the part of your finger that is slightly above the surface by actually measuring the amount of projected capacitance rather than just apply a threshold. Unfortunately you would not be able to do anything like this without your own hardware.


text:
Q: Fi Binary Number A Fi-binary number is a number that contains only 0 and 1. It does not contain any leading 0. And also it does not contain 2 consecutive 1. The first few such number are 1, 10, 100, 101, 1000, 1001, 1010, 10000, 10001, 10010, 10100, 10101 and so on. I have n. How to calculate the nth Fi-binary number ?

A: Hint:  Let $F_k$ denote the $k$-th Fibonacci number; i.e., $F_0=0$, $F_1=1$, and $F_k=F_{k-1}+F_{k-2}$ for all integers $k\geq 2$.  Every positive integer $n$ can uniquely be written as a sum of nonconsecutive pairwise distinct Fibonacci numbers $F_k$'s with $k\geq 2$.    If $n=\sum_{j=1}^m\,F_{k_j}$ is such a representation, then the $n$-th Fi-binary number is $\sum_{j=1}^m\,10^{k_j-2}$.  If you are talking about the base-$2$ representation, then replace $10$ by $2$.


text:
Q: Should I use my models in a library? I've got my auth library in codeigniter which accesses the database to check to see if the email/password combination is correct.
If I'm sticking to the MVC practice, should I move the function that interacts with the database to my model, or is it best practice to leave it where it is so I can use it in the future?
Doesn't make much difference to me, other than the fact I'd have to re-write the library and create the function in my model, but if that's the way it should be then so be it.

A: Well generally the rule of thumb is to have all functions that are involved with processing data and performing database queries go in the model. Different developers have different methods, but I think you shouldn't break the MVC model and put database code in your controllers.
I've been developing an auth library myself called WolfAuth for anyone to fork and contribute too / use: https://github.com/Vheissu/WolfAuth-for-Codeigniter-2.0-
As you can see in my model I have a get user function which can accept a needle and haystack value. So I can write a whole bunch of different functions in my library for getting a user by ID or logging a user in by calling this model function with different parameters instead of calling different functions.
In WolfAuth you can see that all functions will call the model function get_users with different values. I believe having one function that can retrieve multiple pieces of data instead of writing separate functions is much cleaner than having 6 functions when one function can do everything those 6 functions can do.
So to answer your question: write the function that interacts with the database in your model, but keep the same function in your library to call the model function and return its value.
Also, if you want feel free to take pieces of code and borrow ideas from my auth library and use them in yours if it helps you understand breaking code up better.


text:
Q: Can't find Localhost files Hope you can help.  This is my first time trying Ubuntu/Linux.
I am logged in as root
I have downloaded and installed LAMP and PHPMYADMIN.
I get the test page under localhost say that It works and is installed Correctly.
I have also put my files in the /var/www. they are PHP files
When I put the address localhost/(page name.php) I get an error saying
 Not Found

 The requested URL /index.php was not found on this server.
 Apache/2.2.22 (Ubuntu) Server at localhost Port 80

I Have put the files in the wrong folder?? If I look in the "/etc/ap[ache2/sites-available/default", It tells my my DocumentRoot is /var/www
Would love somehelp on this please
Many thanks
GF

A: Check out error log (tail /var/log/apache2/error.log) in order to find out exact path that Apache tries to find.

A: I had the same problem and using the apache logs I've found that the solution is to place your php code inside /html folder so -
sudo mv /var/www/FILENAME.php /var/www/html


text:
Q: Using elementree, lxml - the only (.//) wildcard works for findall - cannot use relative paths? I have a highly nested and long xml file that I need to parse and get into a pandas DataFrame.
This is my XML:
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE PPP
  SYSTEM 'PPP.DTD'>
<book chg="R" model="AB" >
    <chapter chapnbr="09" chg="U" key="EN49" >
        <effect effrg="Afcd"/>
        <title>HOW TO WIN</title>
        <section chapnbr="09" chg="U" key="Edff" revdate="20100701" sectnbr="102">
            <title>What a start</title>
            <subject chapnbr="09" chg="U" key="Edff" revdate="20100701" sectnbr="102" subjnbr="00">
                <title>1.A</title>
                <pgblk chapnbr="09" chg="U" confnbr="00" key="Edff00" pgblknbr="00" revdate="20200701" sectnbr="102" subjnbr="00">
                    <effect effrg="12"/>
                    <title>1.A.i) Plan Ahead for the worst</title>
                    <prclist1>
                        <prcitem1 adns-numbering="8" adns-title="learning my way with help of good people" >
                            <effect effrg="Edff"/>
                            <prcitem asFragment="true">
                                <title>1.A.i) Plan Ahead for the worst</title>
                                <para>It was a cold January night, and I had too much whisky.
                                    <refblock>
                                        09-102-00
                                        <refint rrr="22,445,555,555,555" refid="Edff0898">
                                            <effect effrg="Edff0899"/>
                                            0910200</refint>
                                    </refblock>. </para>
                                <para>In more usual circumstances, I possesed the self-control. Not this time
                                    <refblock>
                                        09-102-00-1111
                                        <refint rrr="sdf,2323,2323" refid="Edff123">
                                            <effect effrg="Edff12434"/>
                                            09-102-00</refint>
                                    </refblock>. </para>
                            </prcitem>
                        </prcitem1>
                    </prclist1>
                </pgblk>
            </subject>
        </section>
    </chapter>
</book>

For a reason unknown to me, I cannot extract using relative XPath. Only findall('.//') works, but of course that outputs the complete file.
At a high level, I can get the xml parsed
from lxml import etree

tree = etree.parse('file.xml')
root = tree.getroot()

I am also able to get the absolute paths for each element:

for e in root.iter():
    print(tree.getpath(e))

which gives (below is a sample, my actual xml is more nested and outputs x3 times the paths below):
/book
/book/chapter
/book/chapter/effect
/book/chapter/title
/book/chapter/section
/book/chapter/section/title
/book/chapter/section/subject

I then need to extract both tags and text from specific areas of the xml
However, if trying to use either absolute or relative path, the dictionary output, d, remains empty.
d={}

for item in root.findall('./section/title'):
    d[item.tag] = item.text

same for
findall('.//section/title')

and again, empty dict for
findall('/book/chapter/section/title')

The only xpath that does work is:
findall('.//')

A: findall() does not accept absolute path names. You need relative path names.
'.//section/title' does work, but it returns title tags. So, no matter how many matches there are, you will end up with one single key named title in your dict, why may be not what you want.
If you want to use the title as index to the chapter, you could do like this:
d = dict((item.text, item.getparent()) for item in root.findall('.//section/title'))

From your sample XML, this creates a dict with key What a start and the chapter element as value.
If you want to use the full power of XPath expressions, I would recommend to use XPathEvaluator:
from lxml import etree

tree = etree.parse('file.xml')

xev = etree.XPathEvaluator(tree)

d = dict((item.text, item.getparent()) for item in xev('/book/chapter/section/title'))

for k, v in d.items():
    print(f"{k} -> {v.tag}")

Output:
What a start -> section


text:
Q: Is the name of winreg module name is different in pip install? How can i install winreg module?
When I try this
pip install winreg

It gives me this error:
  Could not find a version that satisfies the requirement winreg (from versions:)
  No matching distribution found for winreg

Is the name of winreg module name is different in pip install?

A: winreg is a built-in module, no need to install it.


text:
Q: Didn't get value from range slider in flutter I want to save loan amount request to database. But when I save it to database, the result is 0 (email is sensored)

This is my Range Value of loan amount request
RangeValues loanamountrequest = const RangeValues(1000000, 50000000);

here is my widget build of loan amount request
    Text(
              "Loan Amount Request"
          ),
RangeSlider(
values: RangeValues(loanamountrequest.start,loanamountrequest.end),
min: 1000000,
max: 50000000,
divisions: 10,
labels: RangeLabels(
loanamountrequest.start.round().toString(),
loanamountrequest.end.round().toString(),
),
onChanged: (RangeValues values) {
  setState(() {
    loanamountrequest = values;
  });
}),
          Text(
              "Interest :"  + interest
          ),
          SizedBox(
            height: 20.0,
          ),
          Text(
             "DP : " +  DP
          ),
          SizedBox(
            height: 20.0,
          ),
          TextFormField(
            validator: (value) {
              if (value.isEmpty) {
                return 'Reason cannot be empty';
              }
              return null;
            },
            onSaved: (value) => reason = value,
            decoration: kTextFieldDecoration.copyWith(
              hintText: 'Reason',
            ),
          ),

          FullWidthRoundButton(
            textButton: 'Submit Form',
            getPressed: () {
              check(); //this process is save to database from API

Here is the value when save in database

this is submit async function
 void check() {
    final form = _key.currentState;
    if (form.validate()) {
      form.save();
      submit();
    }
  }

  void submit() async {
    LoanFormModel loanFormModel;
    await LoanFormModel.submit(
        email: emailAPI,
        periodtime : periodtime,
        loanamountrequest: loanamountrequest.toString(),
        totalloanamountrequest: totalloanamountrequest,
        interest: interest,
        reason : reason,
        url: BaseURL.kInsertLoan)
        .then((value) => loanFormModel = value);
    print(loanFormModel.success);
    _scaffoldKey.currentState.showSnackBar(SnackBar(
      content: Text(loanFormModel.message),
      duration: Duration(seconds: 10),
    ));
    if (loanFormModel.success == 1) {
      Text(loanFormModel.message);
    } else {
      _scaffoldKey.currentState.showSnackBar(SnackBar(
        content: Text(loanFormModel.message),
        duration: Duration(seconds: 3),
      ));
    }
  }

here is submit
 static Future<LoanFormModel> submit(
      {String email, String periodtime, String interest, String loanamountrequest, String totalloanamountrequest, String reason, String url}) async {
    var response;
    if (email != null && periodtime != null) {
      response = await http.post(url, body: jsonEncode(<String, String>{
        'email': email,
        'product_id': "1",
        'loan_status_id': "1",
        'AgreementDate': "2021-05-24",
        'DisbursementDate': "2021-05-24",
        'periodtime': periodtime,
        'interest': interest,
        'amount_without_interest': loanamountrequest,
        'totalamount': totalloanamountrequest,
        'LoanQuality': "Good",
        'LoanStatus': "In Process",
        'Reason': reason
      }));
      if (response.statusCode == 200) {
        print(json.decode(response.body));
      } else {
        print(response.statusCode);
      };
      return LoanFormModel.fromJson(jsonDecode(response.body));
    }
    response = await http.post(url, body: {
      'email': "${email}",
      'product_id': "1",
      'loan_status_id': "1",
      'AgreementDate': "2021-05-24",
      'DisbursementDate': "2021-05-24",
      'periodtime': "${periodtime}",
      'interest': "${interest}",
      'amount_without_interest': "${loanamountrequest}",
      'totalamount': "${totalloanamountrequest}",
      'LoanQuality': "Good",
      'LoanStatus': "In Process",
      'Reason': reason
    });
    return LoanFormModel.fromJson(jsonDecode(response.body));
  }

How to solve this error? Is this my model or something?


text: Q: KonvaJS at backend: Can we directly load a stage with background videos using Konva.Node.Create and then export to video? I actually want to generate videos with Konva at backend. I found an example where they were creating multiple frames first and then combining them using fffmpeg to generate the video. But how do we do that if the created a konva preview in the frontend that had a video background ?


text:
Q: Any faster way to search each value of one column through another column in python? I need to search through each value of a column, do some comparison with all entries of another column and, if certain conditions are met, print. I'm using the python code below and it works, but the drawback is that both columns have tens of thousands of entries, so it's very slow. Is there a more efficient way to do this?
for i in df1.index:
    for j in df2['pdb']:
        if df1['pdb'][i] == df2['pdb'][j]:
            if df1['res1'][i] >= df2['start'][j] and df1['res2'][i] <= df2['end'][j]:
                print(df1['pdb'][i], df2['PFAM_ACC'][j])

Example:
df1 =
pdb    res1   res2
4xhfA   76    83
4xhfA   126   133
2mx1A   179   186
3s8lA   111   118
4ucmA   115   122
1pigA   119   126
4mavA   263   270
4mavA   289   296
3sbrA   101   108
3sbrA   148   155
3sbrA   158   165
3sbrA   222   229
3sbrA   394   401
5zeaA   83    90
5zeaC   562   569
5zeaD   32    39
5zeaD   89    96
5zeaG   277   284

df2 =
 pdb    start  end  PFAM_ACC
 4xhfA  140    236  PF04205
 1pigA  61     332  PF00128
 1pigA  409    493  PF02806
 3sbrA  171    241  PF18793
 3sbrA  424    494  PF18764
 3sbrA  558    635  PF00116
 5zeaA  13     75   PF02874
 5zeaC  13     75   PF02874
 5zeaD  15     81   PF02874
 5zeaG  13     75   PF02874

and I want to get as output:
 1pigA     PF00128
 3sbrA     PF18793
 5zeaD     PF02874

I hope it's more clear now.
Please let me know if you have any suggestions

A: Try:
x = df1.merge(df2, on="pdb")
out = x.loc[
    (x["res1"] >= x["start"]) & (x["res2"] <= x["end"]), ["pdb", "PFAM_ACC"]
]
print(out)

Prints:
      pdb PFAM_ACC
2   1pigA  PF00128
13  3sbrA  PF18793
21  5zeaD  PF02874


text:
Q: Nginx log location I am trying to figure out if it is possible to log the exactly location uri.
If the following url was accessed
location / {
}

The nginx log would have "/" as part of the log.
If the following location was accessed
location /myLocation {
}

The nginx log would have "/myLocation" as part of the log.
Is this possible?

A: You could specify exact filename you want to use to avoid this strange behaviour.
server {
    listen 80 ;
    server_name     mysite.com ;
    location / {
        root /var/www/webapp;
    }
    location /mylocation {
        root /var/www/webapp/notmylocation;
    }
    access_log  /var/log/mysite.com-access.log;
    error_log   /var/log/mysite.com-error.log warn;
}


text:
Q: C program buffer overflow issue I have a code for which the char array size is 8. If the gcc to compile the code with -fno-stack-protector, the stack smashing detected will only be detected after the string size is 12, such as 12345678901234567890. If I use -fstack-protector, size 9 input will cause segmentation fault as shown below. May I know why the error only be detected at size 12 String input, not other numbers?
I did try different inputs with different char array sizes, the error will be detected when the overflow size is 11 to 13 (input size - char array size).
Code:
#include <stdio.h>

int i;

void readinput()
{
    char c, buf[8];
    int i;

    printf("Enter a string: ");
    for (i = 0; (c = getchar()) != '\n'; i++) buf[i] = c;
    buf[i] = '\0';
    printf("string = [%s]\n", buf);
}

int main(int argc, char *argv[])
{
    readinput();
    return 0;
}

A: The code does not check that i is less than the length of the array, so it has undefined behavior if user input exceeds 7 characters. Enabling compiler options for buffer overflow checking is not foolproof, not every offending access is tested. The C programmer is in charge, good practices are needed to try and avoid such problems.
Here is a modified version:
#include <stdio.h>

void readinput(void) {
    char buf[8];
    size_t i;
    int c;

    printf("Enter a string: ");
    for (i = 0; (c = getchar()) != EOF && c != '\n';) {
        if (i + 1 < sizeof(buf))
            buf[i++] = c;
    }
    buf[i] = '\0';
    printf("string = [%s]\n", buf);
}

int main(int argc, char *argv[]) {
    readinput();
    return 0;
}


text:
Q: Count items from relationschip in faker I have a page model and a textblock model for creating pages with as many textblocks as needed. I'm using sortable from jquery ui to sorter the textblocks by position field in migration table. So every time I'm creating a textblock the position will count + 1, starting from 1.
Now I'm setting up 2 faker factories, 1 for pages and 1 for generating dummy textblocks on the pages. I'm wondering how I can count the amount of random textblocks the factory will create? So I can say every time the page factory creates a page with a few textblocks the counter won't override the amount of textblocks each page has.
 $factory->define(Textblock::class, function (Faker $faker) {

return [
    'page_id' => Page::all()->random()->id,
    'title' => $faker->sentence(rand(2, 5)),
    'summary' => $faker->text,
    'position' => // how can i code this ?
    'visible' => $faker->boolean($chanceOfGettingTrue = 50),

]; });

A: You could create a Counter object to keep all the incrementations in memory. Something similar to:
class Counter
{
    private static $counters = [];

    public static function nextCounterFor($key, $default = 0)
    {
        if (!isset(self::$counters[$key])) {
            if (is_callable($default)) {
                 $default = $default();
            }
            if (!is_int($default)) {
                 throw new \RuntimeException('The default value must be an integer');
            }
            self::$counters[$key] = $default;
        }

        return ++self::$counters[$key];
    }
}

Then you can use it to generate new positions for the given page ID. If there is no key defined yet, you must take the last position used for that page from the db (if it exists)
$factory->define(Textblock::class, function (Faker $faker) {

  $page = Page::inRandomOrder()->first();

  $position = Counter::nextCounterFor($page->id, static function() use ($page) {
       $lastPosition = Textblock::where('page_id', $page->id)->orderBy('position', 'DESC')->first();
       return $lastPosition !== null ? $lastPosition->position : 0;
  });

  return [
    'page_id' => $page->id,
    'title' => $faker->sentence(rand(2, 5)),
    'summary' => $faker->text,
    'position' => $position,
    'visible' => $faker->boolean($chanceOfGettingTrue = 50),
  ];
});


text:
Q: MAC OpenGL shader error: "version '150' is not supported " I follow the book "OpenGL SuperBible 5th Edition" to study openGL, the capture 6th demo to create shader by hand all not work. Like the demo of "ShadedTriangle",  to  create a triangle but only create a black ground window.
The error is:
The shader at ShadedIdentity.vp failed to compile with the following error:
ERROR: 0:5: '' :  version '150' is not supported"

and I change the GLSL version to 330,440, 150 etc, but all not work.
and now my mac version is 10.12.5 (16F73) , and the version of code glGetString(GL_VERSION) is 2.1 INTEL-10.25.13
the follow is the full code:
#include <GLTools.h>            // OpenGL toolkit
#include <GLShaderManager.h>    // Shader Manager Class

#ifdef __APPLE__
#include <glut/glut.h>          // OS X version of GLUT
#else
#define FREEGLUT_STATIC
#include <GL/glut.h>            // Windows FreeGlut equivalent
#endif

GLBatch triangleBatch;
GLShaderManager shaderManager;

GLint   myIdentityShader;

///////////////////////////////////////////////////////////////////////////////
// Window has changed size, or has just been created. In either case, we need
// to use the window dimensions to set the viewport and the projection matrix.
void ChangeSize(int w, int h)
    {
    glViewport(0, 0, w, h);
    }

///////////////////////////////////////////////////////////////////////////////
// This function does any needed initialization on the rendering context.
// This is the first opportunity to do any OpenGL related tasks.
void SetupRC()
    {
    // Blue background
    glClearColor(0.0f, 0.0f, 0.0f, 1.0f );

    shaderManager.InitializeStockShaders();

    // Load up a triangle
    GLfloat vVerts[] = { -0.5f, 0.0f, 0.0f,
                          0.5f, 0.0f, 0.0f,
                          0.0f, 0.5f, 0.0f };

    GLfloat vColors [] = { 1.0f, 0.0f, 0.0f, 1.0f,
                           0.0f, 1.0f, 0.0f, 1.0f,
                           0.0f, 0.0f, 1.0f, 1.0f };

    triangleBatch.Begin(GL_TRIANGLES, 3);
    triangleBatch.CopyVertexData3f(vVerts);
    triangleBatch.CopyColorData4f(vColors);
    triangleBatch.End();

    myIdentityShader = gltLoadShaderPairWithAttributes("ShadedIdentity.vp", "ShadedIdentity.fp", 2,
                                    GLT_ATTRIBUTE_VERTEX, "vVertex", GLT_ATTRIBUTE_COLOR, "vColor");
    }

///////////////////////////////////////////////////////////////////////////////
// Cleanup
void ShutdownRC()
   {
   glDeleteProgram(myIdentityShader);

   }

///////////////////////////////////////////////////////////////////////////////
// Called to draw scene
void RenderScene(void)
    {
    // Clear the window with current clearing color
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);

    glUseProgram(myIdentityShader);
    triangleBatch.Draw();

    // Perform the buffer swap to display back buffer
    glutSwapBuffers();
    }

///////////////////////////////////////////////////////////////////////////////
// Main entry point for GLUT based programs
int main(int argc, char* argv[])
    {
    gltSetWorkingDirectory(argv[0]);

    glutInit(&argc, argv);
    glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGBA | GLUT_DEPTH | GLUT_STENCIL);
    glutInitWindowSize(800, 600);
    glutCreateWindow("Shaded Triangle");
    glutReshapeFunc(ChangeSize);
    glutDisplayFunc(RenderScene);

    GLenum err = glewInit();
    if (GLEW_OK != err) {
        fprintf(stderr, "GLEW Error: %s\n", glewGetErrorString(err));
        return 1;
        }

    SetupRC();

    const char* version = (const char*)glGetString(GL_VERSION);
    fprintf(stderr, "OpenGLVersion: %s\n", version);

    glutMainLoop();

    ShutdownRC();

    return 0;
    }

and the ShadedIdentity.vp is :
// The ShadedIdentity Shader
// Vertex Shader
// Richard S. Wright Jr.
// OpenGL SuperBible
#version 150

in vec4 vColor;
in vec4 vVertex;

out vec4 vVaryingColor;

void main(void)
    {
    vVaryingColor = vColor;
    gl_Position = vVertex;
    }

so ,how to solve this problem

A: On Mac you need to tell OpenGL which version to use before creating the window.
This answer explains how to do it with GLFW:
I'm still searching for a way to do this with GLUT.
something like this:
glfw.window_hint(glfw.CONTEXT_VERSION_MAJOR, 4)
glfw.window_hint(glfw.CONTEXT_VERSION_MINOR, 1)
glfw.window_hint(glfw.OPENGL_FORWARD_COMPAT, GL_TRUE)
glfw.window_hint(glfw.OPENGL_PROFILE, glfw.OPENGL_CORE_PROFILE)
window = glfw.create_window(800,600,"My OpenGL Window", None, None)

A: 1.50 requires OpenGL 3.2 support. Unless you can get a newer driver (or a GPU), I think you're out of luck on this one.

A: macOS' system GLUT does not have the capability of creating an OpenGL 3+ context.
FreeGLUT provides a way to do it, taken from here:
glutInitContextVersion(3,2); /* or later versions, core was introduced only with 3.2 */
glutInitContextProfile(GLUT_CORE_PROFILE);

Or you can take @izzy's advice and use GLFW.


text:
Q: How to show diferent total on cart shopify I am showing different prices on the cart based on the quantity of an item, if the item in the cart has more than 6 in the item.quantity it should count the price saved in a metafield, else it shown the default price. knowing this i want to show the total on the cart based on those prices, for example
//i declare a variable for the subtotal
{% assign subtotal = 0 &}
{% item.quantity >= 6 %}
    //if the item qty is greater than 6 i show a different prices, in this case a price saved on a metafield
    {% subtotal += item.product.metafields.global.wholesale_price | times:item.quantity %}
{% else %}
    {% subtotal+= item.price | times:item.quantity %}
{% endif %}

and finally show the subtotal
{{ 'general.cart_info.sub_total' | t }}{{ subtotal | money }}

as i have seen doing subtotal += value is not supported or i am using it wrong, is there a way to do this?
Edited
i did a workaround using hidden inputs and a js function like this
//on the liquid file i added the hidden field with a custom class with the sub-total of that row
{% for item in cart.items %}
    {% item.quantity >= 6 %}
        <input type="hidden" value="{{ price | times: item.quantity }}" class="subtotals">
    {% else %}
        <input type="hidden" value="{{ sca_price }}" class="subtotals">
    {% endif %}
{% endfor %}
//in the function i calculate de sum of all the rows and show the result on a div called show_subtotal
function calculateSubtotal()
{
    var subtotal = parseInt(0);
    $('.subtotals').each(function(index, el) {
        subtotal += parseInt($(el).val());
    });
    subtotal = '$'+subtotal;
    subtotal = subtotal.slice(0,-2)+'.'+subtotal.slice(-2)
    $('.show_subtotal').html(subtotal);
}

this work but it is not the best way to do it, i should be able to do that on server side. any advice?

A: Hm, just use assign again
{% assign subtotal = 0 &}
{% item.quantity >= 6 %}
    //if the item qty is greater than 6 i show a different prices, in this case a price saved on a metafield
    {% assign subtotal = item.product.metafields.global.wholesale_price | times: item.quantity %}
{% else %}
    {% assign subtotal =  item.price | times: item.quantity %}
{% endif %}

A: You can try this:
{{ item.final_line_price | money }}


text:
Q: Junk character is not visible in Oracle SQL developer I am not able to view a junk character in Oracle SQL developer, but it is visble in PLSQL developer. Below screenshot is from PLSQL developer:

Below is the screenshot from Oracle SQL developer:

The junk character is visible in notepad too but not visible here.
Please explain how can it be made visible in Oracle SQL developer as this is the only tool I am allowed to use officially.

A: Use the locale command:
$ jim>  locale
LANG=C
LC_COLLATE="C"
LC_CTYPE="C"
LC_MONETARY="C"
LC_NUMERIC="C"
LC_TIME="C"
LC_MESSAGES="C"
LC_ALL=

Usual locale setting on our DB servers == UTF-8  If you use non-Latin characters in in your language it will be different.


text:
Q: How to interpolate zeros in a time series data in R Could anyone help answer how to interpolate zeros in a time series data using linear interpolation? I know there is function to interpolate NA (missing values) in a time series data, is there something  similar function to deal with zeros?

A: Try this.  It also works with zoo and with ts series:
> library(zoo)
> x <- c(1, 0, 2) # sample data
> na.approx(replace(x, x == 0, NA))
[1] 1.0 1.5 2.0

Please provide sample data next time.


text:
Q: How to avoid going to a user for access token generation I am writing a server which connects to a facebook account on behalf of a corporation, so the account is known and fixed.
The method my prototype code uses to access the facebook feed is as follows
1) use a WebBrowser UI component top request https://www.facebook.com/dialog/oauth with client_id (AKA AppID) and redirect_uri parameters passed.  When this returns it either returns an access token or, if this is not cached by the web browser, prompts the user to login. If this is successful the Web Browser response is fired with the access token.
From there I
2) check the access token is application to the app, and then
3) generate a longer life token from that.
4) read the feed
It seems to work OK.
However my problem is that when I turn this into server code, there will be no user.  So when the access token is not known I have no way of getting it.
Is there a way around this??
Thanks.


text:
Q: can find string if a variable batch (existing code needs editing) I have devised a way to remove a files name from its path and extension (replacing the files name with an asterisk).
However the out put file adds an extra space just before the closing quotation marks and i dont know why or how to fix this?
@echo off

SET EXTENT=%~x1
SET PATH=%~dp1

SET /P FILETYPE=

rem SET FILETYPE="%PATH%*%EXTENT%"

echo %FILETYPE%

pause

Type C:\HELLO.txt | findstr /I /V /C:%FILETYPE% >>C:\TEMP.txt

DEL /S/Q "C:\HELLO.txt"

ren "C:\TEMP.txt" "HELLO.txt"

DEL /s/q "C:\TEMP.txt"

A: UPDATED
I changed this answer after gaining a better understanding of the question.
I think this code is close to what you want. You may need to play around with regexes for the FINDSTR command.
@ECHO OFF

SET EXT=%~x1

FINDSTR /I /V /C:%EXT% HELLO.TXT >>TEMP.TXT
DEL /Q HELLO.TXT
REN TEMP.TXT HELLO.TXT


text:
Q: One report as attachment and another as email body in ssrs 2008 I have one summary report and one detailed report, i need to send mail to my client daily attaching detailed report (excel file) as attachment of mail and the summary report as body for the same mail.
How do I do this? How do I include two reports to one email? Can this be done in SSRS 2008?

A: That functionality is not supported out-of-the-box. You might be able to write a custom extension to do it, but it's not going to be trivial.


text:
Q: How to check overdispersion of binomial GLMMs, lme4 package I have the following model
fit1 <- glmer(Res~FA+FB+FC+(1|fsite), family=binomial(), data=DATA)

the result of summary() is:
summary(fit1)
Generalized linear mixed model fit by maximum likelihood
 (Laplace Approximation) ['glmerMod']
 Family: binomial  ( logit )
Formula: Res ~ FA + FB + FC + (1 | fsite)
   Data: DATA

     AIC      BIC   logLik deviance df.resid
   202.3    229.9    -92.1    184.3      150

Scaled residuals:
    Min      1Q  Median      3Q     Max
-2.1768 -0.6167 -0.4967  0.6815  2.0132

Random effects:
 Groups Name        Variance Std.Dev.
 fsite  (Intercept) 0        0
Number of obs: 159, groups:  fsite, 28

Fixed effects:
            Estimate Std. Error z value Pr(>|z|)
(Intercept)  1.55573    0.55830   2.787 0.005327 **
FA2         -0.11914    0.37344  -0.319 0.749692
FB2         -1.38652    0.39967  -3.469 0.000522 ***
FC2         -0.14976    0.61984  -0.242 0.809076
FC3         -0.06794    0.63171  -0.108 0.914350
FC4         -1.20114    0.61670  -1.948 0.051452 .
FC5         -1.44951    0.62817  -2.308 0.021025 *
FC6         -1.13590    0.65427  -1.736 0.082538 .
---
Signif. codes:  0 ?**?0.001 ?*?0.01 ??0.05 ??0.1 ??1

Correlation of Fixed Effects:
        (Intr) fspcs2    FB2    FC2    FC3    FC4    FC5
FA2     -0.466
FB2     -0.456  0.169
FC2     -0.572 -0.021  0.017
FC3     -0.596  0.050  0.036  0.506
FC4     -0.582 -0.005  0.020  0.519  0.509
FC5     -0.558  0.019 -0.038  0.508  0.500  0.511
FC6     -0.391 -0.101 -0.288  0.485  0.467  0.486  0.492

*

*Why are the variance and Std.Dev of the random effects zero?

*How do I check for overdispersion in this model?

*What should do if there is overdispersion?

A:
Why are the variance and Std.Dev of the random effects zero?

Because the marginal variance among sites in your data is less than would be expected from a binomial variable; the variance can't be negative, so it's estimated as zero. The GLMM FAQ discusses this.

How do I check for overdispersion in this model?

This looks like a binary (not just binomial) regression, i.e. your responses are 0/1 (if you had "m out of N" responses where N>1, you either need a two-column response variable of (successes,failures), or you need to specify the weights argument). Therefore, overdispersion is not identifiable (e.g., see here or here). tl;dr, you don't need to worry about it.  If you did have N>1, the previously linked GLMM FAQ gives some guidance ... the overdisp_fun from there can be used; depending on your philosophy of model-building you can use a hypothesis test (e.g. $p<0.05$?) or a rule of thumb (e.g. overdispersion factor > 1.1) to decide whether you should worry about it.

What should do if there is overdispersion?

See previous answer (i.e., don't worry about if you have Bernoulli responses; otherwise, see the FAQ or elsewhere for strategies).

What do I do if the data are unbalanced? (asked in comments)

Unless you have data that are severely unbalanced, or unless the data are structured that you have complete separation (all zeros or all ones for some combinations of predictor variables), GLMMs will handle unbalanced data fine; there's no need for manual adjustment.


text:
Q: How to use continuation monad transformer with spawn/exec in purescript? I want to execute a command using spawn in Node.ChildProcess but i have no clue on how to hook the the function which spawns the command and the rest of the application with spawn. I have a vague idea that i need to use ContT for hooking up the error and success callbacks and am not able to figure out the data pipeline as a single program.
This is the program I am trying to write -

*

*Wait for a request (let's say as an HTTP server)

*On request, write something to a file

*Fire a terminal command

*Collect output from terminal command

*Send response

A: I would go for the easier solution and use Aff. I have an example of how I'm doing spawned child processes here: https://github.com/justinwoo/vidtracker/blob/b5756099a4f683d262bc030d33b68343a47f14d7/src/GetIcons.purs#L44-L54
curl :: forall e.
  String
  -> String
  -> Aff
      _
      Unit
curl url path = do
  cp <- liftEff $ spawn "curl" [url, "-o", path] defaultSpawnOptions
  makeAff \e s -> do
    onError cp (e <<< Exc.error <<< unsafeStringify)
    onClose cp (s <<< const unit)

I have another example here where I'm collecting the output: https://github.com/justinwoo/simple-rpc-telegram-bot/blob/09e894c81493f913fe316f6689cb94ce1f5056e6/src/Main.purs#L149


text:
Q: Как мне превратить пары чисел (str) в пары чисел (int) Например у меня есть:
lst = ['1,2' , '3,4' , '6,5']

Как мне сделать так, чтобы стало:
lst = [[1,2] , [3,4] , [6,5]]

A: lst = ['1,2' , '3,4' , '6,5']
newLst = [[int(j) for j in i.split(',')] for i in lst]
print(newLst)  # [[1, 2], [3, 4], [6, 5]]

A: Например вот так:
lst = ['1,2' , '3,4' , '6,5']
new_list = []
for element in lst:
    data = element.split(',')
    print(data)
    nlst = []
    nlst.append(int(data[0]))
    nlst.append(int(data[1]))
    new_list.append(nlst)

print(new_list)

A: lst = ['1,2', '3,4', '6,5']
newLst = [list(map(int, x.split(','))) for x in lst]
print(newLst)


text:
Q: Setting a Column Value Using 'Range' is Giving An Error The below code copies data from multiple worksheets and consolidates into database (database worksheet). I am trying to add a new column at the last unused column of database worksheet that gives the name of the sheets in each row, the data is copied from with the column header as "Sheet Name". The problem is, I am trying to start with adding the header by using wsData.Range(1, wsData.Cells(1, Columns.Count).End(xlToLeft).Offset(0, 1)).Value = "SheetName", but unfortunately, it is giving an error.
The program is currently taking 6 minutes to process around 25,000 rows, so is there a way to make it faster?
I am not very well-versed with VBA and I received the below code from another stack overflow question. Below is my code. Any help will be appreciated.
Sub ProcessWorkbooks()

    Application.ScreenUpdating = False
    Application.EnableEvents = False
    Application.DisplayAlerts = False

    Dim f, wsData As Worksheet, wbSrc As Workbook, map As Object

    Set wsData = ThisWorkbook.Sheets("Database")
    wsData.UsedRange.ClearContents 'clear any existing data

    Dim fldr1 As FileDialog
    Dim iFile As String
    Set fldr1 = Application.FileDialog(msoFileDialogFolderPicker)
    With fldr1
        .Title = "Select InputFile Folder... "
        .ButtonName = "Select"
        .AllowMultiSelect = False
        .InitialFileName = Application.DefaultFilePath
        If .Show = -1 Then
            iFile = .SelectedItems(1)
        Else
            Exit Sub
        End If
    End With

    Dim strPath As String
    strPath = iFile

    Dim oFSO As Object
    Dim oFolder As Object
    Dim oFile As Object

    Set oFSO = CreateObject("Scripting.FileSystemObject")
    Set oFolder = oFSO.GetFolder(strPath)

    Dim abc As Boolean
    abc = False
    For Each oFile In oFolder.Files
        If oFile.Name Like "*xls*" Then
            Set wbSrc = Workbooks.Open(oFolder & "\" & oFile.Name)
            ImportData wbSrc, wsData, abc
            wbSrc.Close False
        End If
    Next oFile

      With wsData.Range("A1").CurrentRegion
        .Font.Size = 9
        .Font.Name = "Calibri"
        .Borders.LineStyle = xlLineStyleNone
        .EntireColumn.AutoFit
    End With

    Application.ScreenUpdating = True
    MsgBox Title:="Task Box", Prompt:="Database Created!"

End Sub

Sub ImportData(wbIn As Workbook, wsData As Worksheet, abc as Boolean)

    Dim lrData As Long, lrSrc As Long, ws As Worksheet, c As Range
    Dim Process, hdr, m, n

    Process = Array("Manila", "Cebu", "Davao", "CDO", "Bacolod")
    Application.ScreenUpdating = False

    For Each ws In wbIn.Worksheets
            Call KillFilter
            n = ws.Name
            lrData = wsData.Cells(Rows.Count, "A").End(xlUp).Row + 1
            'lrData = SheetLastRow(wsData) + 1
            If lrData = 1 Then lrData = 2 'in case no headers yet...
            lrSrc = SheetLastRow(ws)
            For Each c In ws.Range("A1", ws.Cells(1, Columns.Count).End(xlToLeft)).Cells
                hdr = c.Value

                m = Application.Match(hdr, wsData.Rows(1), 0) 'existing column match?
                If IsError(m) Then
                    m = Application.CountA(wsData.Rows(1))
                    m = IIf(m = 0, 1, m + 1)
                    wsData.Cells(1, m).Value = hdr 'add as new column header
                End If

                ws.Range(c.Offset(1), ws.Cells(lrSrc, c.Column)).Copy _
                        wsData.Cells(lrData, m)
                Next c
            If abc = False Then
                wsData.Range(1, wsData.Cells(1, Columns.Count).End(xlToLeft).Offset(0, 1)).Value = "SheetName"
                abc = True
            End If
    Next ws
End Sub

'return the last used row in a worksheet
Function SheetLastRow(ws As Worksheet) As Long
    Dim f As Range
    Set f = ws.Cells.Find("*", ws.Range("A1"), xlFormulas, xlPart, xlByRows, xlPrevious)
        If Not f Is Nothing Then SheetLastRow = f.Row 'otherwise 0
End Function

A: See below for how to add the sheet name, and some other suggestions:
Option Explicit

Sub ProcessWorkbooks()

    Dim f, wsData As Worksheet, wbSrc As Workbook, map As Object, strPath As String
    Dim oFSO As Object, oFile As Object, nextRow As Long

    On Error GoTo haveError   'ensures event/calc settings are restored

    Application.ScreenUpdating = False
    Application.EnableEvents = False
    Application.Calculation = xlCalculationManual

    strPath = ChooseFolder("Select InputFile Folder... ") 'made this a new Function
    If Len(strPath) = 0 Then Exit Sub

    Set wsData = ThisWorkbook.Sheets("Database")
    With wsData
        .UsedRange.ClearContents           'clear any existing data
        .Range("A1").value = "Sheet Name"  'add the sheet name header
    End With

    Set oFSO = CreateObject("Scripting.FileSystemObject")
    For Each oFile In oFSO.getfolder(strPath).Files
        If oFile.name Like "*.xls*" Then
            Set wbSrc = Workbooks.Open(oFile.Path)
            ImportData wbSrc, wsData
            wbSrc.Close False
        End If
    Next oFile

    With wsData.Range("A1").CurrentRegion
        .Font.Size = 9
        .Font.name = "Calibri"
        .Borders.LineStyle = xlLineStyleNone
        .EntireColumn.AutoFit
    End With

haveError:

    Application.ScreenUpdating = True
    Application.EnableEvents = True
    Application.Calculation = xlCalculationAutomatic

    MsgBox Title:="Task Box", Prompt:="Database Created!"

End Sub

'assumes there's always a "sheet Name" header in A1 of wsData
Sub ImportData(wbIn As Workbook, wsData As Worksheet)

    Dim lrData As Long, lrSrc As Long, ws As Worksheet, c As Range
    Dim Process, hdr, m

    Process = Array("Manila", "Cebu", "Davao", "CDO", "Bacolod") '????

    For Each ws In wbIn.Worksheets
        If ws.FilterMode Then ws.ShowAllData                     'remove any filtering
        lrData = wsData.Cells(Rows.Count, "A").End(xlUp).Row + 1 'paste row
        lrSrc = SheetLastRow(ws)
        wsData.Cells(lrData, "A").Resize(lrSrc - 1).value = ws.name  '<<< add the sheet name....
        For Each c In ws.Range("A1", ws.Cells(1, ws.Columns.Count).End(xlToLeft)).Cells
            hdr = c.value
            m = Application.Match(hdr, wsData.Rows(1), 0) 'existing column match?
            If IsError(m) Then                            'need to add this header?
                m = wsData.Cells(1, Columns.Count).End(xlToLeft).Column + 1
                wsData.Cells(1, m).value = hdr
            End If

            ws.Range(c.Offset(1), ws.Cells(lrSrc, c.Column)).Copy _
                    wsData.Cells(lrData, m)
        Next c
    Next ws
End Sub

'Ask user to select a folder. Returns empty string if none selected
Function ChooseFolder(prmpt As String) As String
    Dim fldr1 As FileDialog, fldr As String
    Dim iFile As String
    Set fldr1 = Application.FileDialog(msoFileDialogFolderPicker)
    With fldr1
        .Title = prmpt
        .ButtonName = "Select"
        .AllowMultiSelect = False
        .InitialFileName = Application.DefaultFilePath
        If .Show = -1 Then ChooseFolder = .SelectedItems(1)
    End With
End Function

'return the last used row in a worksheet
Function SheetLastRow(ws As Worksheet) As Long
    Dim f As Range
    Set f = ws.Cells.Find("*", ws.Range("A1"), xlFormulas, xlPart, xlByRows, xlPrevious)
        If Not f Is Nothing Then SheetLastRow = f.Row 'otherwise 0
End Function


text:
Q: Insert if NOT EXISTS not working I am trying to copy data from table to another mysql table from two different databases
First I get all data from first table and stored them into php variable
then I loop on that var to insert data to the other table
using this query
INSERT INTO `users` (`nUserId`, `vLoginName`, `vFirstName`, `vLastName`, `vEmail`)
    VALUES ('$entity_id','$name','$firstname','$lastname','$email')
    WHERE NOT EXISTS (SELECT `nUserId`,`vEmail`
                      FROM `users`
                      WHERE `nUserId`='$entity_id'
                      AND   `vEmail` = '$email')

but it's not working
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 'WHERE NOT EXISTS (SELECT `nUserId`,`vEmail` FROM users '

What the correct syntax to make this work ?

A: I think the problem might be VALUES and I would write the statement as the following:
INSERT INTO `users`
    (`nUserId`, `vLoginName`, `vFirstName`, `vLastName`, `vEmail`)
SELECT
    '$entity_id', '$name', '$firstname', '$lastname', '$email'
FROM dual
WHERE NOT EXISTS (SELECT *
                    FROM `users`
                    WHERE `nUserId`='$entity_id'
                    AND   `vEmail` = '$email')

A: you can try something like
delimiter $$
create procedure select_or_insert()
begin
  IF EXISTS (select * from users where username = 'something') THEN
    update users set id= 'some' where username = 'something';
 ELSE
insert into users (username) values ('something');
  END IF;
end $$
delimiter ;

A: You cannot use WHERE clause in an INSERT statement.
However, you may use INSERT IGNORE if in your targer table you define nUserId or vEmail as unique keys.
More info about INSERT syntax: https://dev.mysql.com/doc/refman/5.6/en/insert.html

A: No need to store them in php.
Creates a table excactly like the one specified, Note: copies only columns
CREATE TABLE tbl_name LIKE db_name.tbl_name;

If you want specific column names:
CREATE TABLE tbl_name SELECT column_name, column_name FROM db_name.tbl_name;

Then if you want to copy all the data do
INSERT INTO tbl_name SELECT * FROM db_name.tbl_name;

Or specific column data do
INSERT INTO tbl_name SELECT column_name, column_name FROM db_name.tbl_name;

If you want specific data add a WHERE clause.

A: $existeEmail=$mysqli->query("SELECT * FROM tb_users WHERE email = '$email'");
 if(!$existeEmail=mysqli_fetch_array($existeEmail))/*si existe en la tabla tblreseteopass*/
{

}else{
    $email = $existeEmail['email'];
      // Direccionado hacia el registro con la Alerta 001
            // ya existe una cuenta asociada a este email, si no recuerda la contraseña, solicite una nueva
            header("Location: https://www.yourpage.com/b/?m=f_lg);
}


text:
Q: Map method in React and native js I'm having trouble understanding how the map method works in React.
In javascript, the map returns a new array and doesn't iterate,
Why in React it is loop the elements

A: The map method does iterate over an array in Javascript. It just also happens to return a new array, whose elements are built using a callback function passed in to map which acts on each element of the original array.
For example:
let arr = [1, 2, 3, 4]

console.log(arr.map(num => num + 1))

===> [2, 3, 4, 5]

It works exactly like forEach, but instead of simply iterating, it returns a new array.
You can also use map to just make a shallow copy of the array:
let arr = [1, 2, 3, 4]
let arrCopy = arr.map(num => num)

console.log(arrCopy)

===> [1, 2, 3, 4]

Hence why it's easy to build out an array of elements using map in React:
let names = ["Mark", "Kelly", "Mike"]

return (

    {names.map(name => {
      return (

{name}

      )})}

)


text:
Q: Why accessing the SRAM is slower with AVR XMega load instructions? The AVR XMega has 16 GPIO registers in I/O space in addition to its internal SRAM. Interestingly the timing of LD instructions differ to these locations: Accessing the (rather large) I/O space is faster than accessing the internal SRAM.
This can be observed more or less in the instruction set documentation:
http://ww1.microchip.com/downloads/en/devicedoc/atmel-0856-avr-instruction-set-manual.pdf (from Page 22)
(Rather "less" as it is quite ambiguous).
Not being sure on how the timing works I made tests with actual hardware, measuring the timings of various instructions.
Accessing the SRAM:
                    Mega   XMega
LD reg, ptreg       2cy    2cy
LD reg, ptreg+      2cy    2cy
LD reg, -ptreg      2cy    3cy
LDD reg, ptreg+imm  2cy    3cy
LDS reg, imm16      2cy    3cy
ST ptreg, reg       2cy    1cy
ST ptreg+, reg      2cy    1cy
ST -ptreg, reg      2cy    2cy
STD ptreg+imm, reg  2cy    2cy
STS imm16, reg      2cy    2cy

Accessing the I/O area (tested with GPIO and UART registers), the loads are one cycle faster:
                    Mega   XMega
LD reg, ptreg       2cy    1cy
LD reg, ptreg+      2cy    1cy
LD reg, -ptreg      2cy    2cy
LDD reg, ptreg+imm  2cy    2cy
LDS reg, imm16      2cy    2cy
ST ptreg, reg       2cy    1cy
ST ptreg+, reg      2cy    1cy
ST -ptreg, reg      2cy    2cy
STD ptreg+imm, reg  2cy    2cy
STS imm16, reg      2cy    2cy

Anyone could provide some insight on why it could have been desinged in this manner? The performance difference is rather significant for memory intensive tasks, and the 16 GPIO registers are not much if someone needed some faster RAM (while the I/O space is huge in comparison, apparently wholly capable to operate by the faster timing, which is a design choice I can't really understand if this faster access required more costly hardware).
A particularly bad case is the 3 cycle displacement loads which are very frequent, and even AVR-GCC seems to lean towards using those rather than trying to walk through memory areas with post-increments when optimizing.


text:
Q: Query with parameters in C# (using SQL Server) I have a problem with query in C#.
I have this part of code :
string query1 = @"
            SELECT TOP @howManyRows * FROM
            (
            SELECT
               PRODUCTCODE_.ID_ AS PRODUCTCODE_ID_,
               PRODUCTCODE_.CATEGORY_ AS CATEGORY_,
               PRODUCTCODE_.DESCRIPTION_ AS DESCRIPTION_,
               PRODUCTCODE_.MANUFACTURER_ AS MANUFACTURER_,
               PRODUCTLINE_.CREATION_DATE_ AS CREATION_DATE_,
               ROW_NUMBER() OVER (ORDER BY PRODUCTCODE_.CATEGORY_) AS ROWNUMBER_,
               TOTALROWS_ = COUNT(*) OVER()
            FROM
               PRODUCTCODE_
            INNER JOIN
               PRODUCTLINE_ ON PRODUCTLINE_.ID_ = PRODUCTCODE_.PRODUCTLINE_ID_
            ) _tmpList
            WHERE
               ROWNUMBER_ >= @startingWith
               ORDER BY CATEGORY_
            ";

SqlParameter param1 = new SqlParameter();
param1.ParameterName = "@howManyRows";
param1.Value = resultPerPage; //`resultPerPage` is an integer function parameter

SqlParameter param2 = new SqlParameter();
param2.ParameterName = "@startingWith";
param2.Value = startsWith;  //`startWith` is an integer function parameter

SqlCommand cmd = new SqlCommand( query1, connect );
cmd.Parameters.Add( param1 );
cmd.Parameters.Add( param2 );

When debug arrived to SqlDataReader reader = cmd.ExecuteReader(); then the exception is thrown:

Incorrect syntax near @howManyRows ...

Why ? I defined and added howManyRows with Parameters property.
Where is my mistakes ?

A: Change your top query syntax from
SELECT TOP @howManyRows * FROM

to
SELECT TOP (@howManyRows) * FROM

A: Try wrapping the parameter specified next to TOP in parentheses, like so:
SELECT TOP (@howManyRows) * FROM

A: You need parenthesis to parametrise TOP
SELECT TOP (@howManyRows) * FROM

A: This will work.
SELECT
           PRODUCTCODE_.ID_ AS PRODUCTCODE_ID_,
           PRODUCTCODE_.CATEGORY_ AS CATEGORY_,
           PRODUCTCODE_.DESCRIPTION_ AS DESCRIPTION_,
           PRODUCTCODE_.MANUFACTURER_ AS MANUFACTURER_,
           PRODUCTLINE_.CREATION_DATE_ AS CREATION_DATE_,
           ROW_NUMBER() OVER (ORDER BY PRODUCTCODE_.CATEGORY_) AS ROWNUMBER_,
           TOTALROWS_ = COUNT(*) OVER()
        FROM
           PRODUCTCODE_
        INNER JOIN
           PRODUCTLINE_ ON PRODUCTLINE_.ID_ = PRODUCTCODE_.PRODUCTLINE_ID_
        ) _tmpList
        WHERE
           ROWNUMBER_ between @startingWith and (@startingWith + @howManyRows)
           ORDER BY CATEGORY_

A: You need to add a couple of parenthesis to make it work.
SELECT TOP (@howManyRows) * FROM

A: You can do
SELECT TOP (@howManyRows) * FROM

But this really depends on the Database Server you are using. For example, this is only supported from MSSQL Server 2005 upwards
If this does not work you can do the following...
You can include this into your query string. But this can result in Sql Injection if you don't check the value of your variable.
Sample
int top = 10;
Int32.TryParse(howManyRows.ToString(), out top);

string query1 = "SELECT TOP " + top.ToString() + @" * FROM
(
SELECT
    PRODUCTCODE_.ID_ AS PRODUCTCODE_ID_,
    PRODUCTCODE_.CATEGORY_ AS CATEGORY_,
    PRODUCTCODE_.DESCRIPTION_ AS DESCRIPTION_,
    PRODUCTCODE_.MANUFACTURER_ AS MANUFACTURER_,
    PRODUCTLINE_.CREATION_DATE_ AS CREATION_DATE_,
    ROW_NUMBER() OVER (ORDER BY PRODUCTCODE_.CATEGORY_) AS ROWNUMBER_,
    TOTALROWS_ = COUNT(*) OVER()
FROM
    PRODUCTCODE_
INNER JOIN
    PRODUCTLINE_ ON PRODUCTLINE_.ID_ = PRODUCTCODE_.PRODUCTLINE_ID_
) _tmpList
WHERE
    ROWNUMBER_ >= @startingWith
    ORDER BY CATEGORY_
";

A: Use SELECT TOP(@howManyRows) syntax


text:
Q: No more location available since IOS 9.0 my project won't work anymore since IOS release 9.0, in particular location (CLLocationManager).
My WiFi is Ok, I've corrected new errors due to new XCode version.
I've put some breakpoint, and the program never goes there :
func locationManager(didUpdateLocations locations: [AnyObject]) {
    if (locationFixAchieved == false) {
        locationFixAchieved = true
        let locationArray = locations as NSArray
        let locationObj = locationArray.lastObject as! CLLocation
        let coord = locationObj.coordinate

        print(coord.latitude)
        print(coord.longitude)
    }
}

More, I have these errors when I call this new method :
// Start location services
// NOTHING HAPPENS HERE
locationManager.startUpdatingLocation()

if #available(iOS 9.0, *) {
  // ERRORS ARE DISPLAYED WHEN THIS IS CALLED !!
  locationManager.requestLocation()
} else {
    // Fallback on earlier versions
}

2015-09-20 20:12:35.537 My fruits now[25113:3351106] XPC connection interrupted
2015-09-20 20:12:44.880 My fruits now[25113:3350891] Location to Allowed
2015-09-20 20:12:51.060 My fruits now[25113:3350891] *** Assertion failure in -[CLLocationManager requestLocation], /BuildRoot/Library/Caches/com.apple.xbs/Sources/CoreLocationFramework_Sim/CoreLocation-1861.0.9/Framework/CoreLocation/CLLocationManager.m:815
2015-09-20 20:12:51.072 My fruits now[25113:3350891] *** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Delegate must respond to locationManager:didUpdateLocations:'
*** First throw call stack:
(
    0   CoreFoundation                      0x0000000106d69f65     __exceptionPreprocess + 165
    1   libobjc.A.dylib                     0x0000000108d19deb     objc_exception_throw + 48
    2   CoreFoundation                      0x0000000106d69dca +[NSException raise:format:arguments:] + 106
    3   Foundation                          0x0000000107459ae2 -[NSAssertionHandler handleFailureInMethod:object:file:lineNumber:description:] + 198
    4   CoreLocation                        0x000000010731f88c CLClientGetCapabilities + 10487
    5   My fruits now                       0x0000000106b3d2ee _TFC13My_fruits_now14ViewController15locationManagerfS0_FTCSo17CLLocationManager28didChangeAuthorizationStatusOSC21CLAuthorizationStatus_T_ + 814
    6   My fruits now                       0x0000000106b3d480 _TToFC13My_fruits_now14ViewController15locationManagerfS0_FTCSo17CLLocationManager28didChangeAuthorizationStatusOSC21CLAuthorizationStatus_T_ + 64
7   CoreLocation                        0x0000000107321849 CLClientGetCapabilities + 18612
    8   CoreLocation                        0x000000010731e583 CLClientGetCapabilities + 5614
    9   CoreLocation                        0x000000010731907d CLClientInvalidate + 923
    10  CoreFoundation                      0x0000000106c9608c __CFRUNLOOP_IS_CALLING_OUT_TO_A_BLOCK__ + 12
    11  CoreFoundation                      0x0000000106c8bd15 __CFRunLoopDoBlocks + 341
    12  CoreFoundation                      0x0000000106c8bac8 __CFRunLoopRun + 2472
    13  CoreFoundation                      0x0000000106c8ae98 CFRunLoopRunSpecific + 488
    14  GraphicsServices                    0x000000010bdd7ad2 GSEventRunModal + 161
    15  UIKit                               0x000000010782c676    UIApplicationMain + 171
    16  My fruits now                       0x0000000106b46acd main + 109
    17  libdyld.dylib                       0x000000010986a92d start + 1
)
libc++abi.dylib: terminating with uncaught exception of type NSException

Can you give me some advices, things to check, parameters to set, tips ... ?
Thank you !

A: Try adding this to implementation.
// Location Manager Delegate Methods
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
{


text:
Q: Apache Pivot - location of the BXML file I am using maven to build application and I would like to try out apache pivot for the GUI rendering. However, it looks like most pivot tutorials assume that you are using eclipse. I added 2.0 version in my pom.xml (and tried with 2.0.2 as well), but, I get this error:
[DEBUG] joining on thread Thread[Timer-1,5,com.polyglot.HelloBXML]
java.lang.IllegalArgumentException: location is null.
at org.apache.pivot.beans.BXMLSerializer.readObject(BXMLSerializer.java:604)
at org.apache.pivot.beans.BXMLSerializer.readObject(BXMLSerializer.java:568)
at org.apache.pivot.beans.BXMLSerializer.readObject(BXMLSerializer.java:534)
at com.polyglot.HelloBXML.startup(HelloBXML.java:21)

It seems like it is unable to find the BXML file. I had put it in src/main/resources.
I searched the forums and it looks like it is because BXML file is not in the classpath. I tried with target/classes, but still no avail. Can somebody guide me what is the correct location of the BXML file?

A: For the HelloBXML.java example
change
window = (Window)bxmlSerializer.readObject(HelloBXML.class, "hello.bxml");

to
window = (Window)bxmlSerializer.readObject(HelloBXML.class, "/hello.bxml");

and put hello.bxml in src/main/resources.
(may need to be backslash for MS Windows environment, but I don't know)

A: The solution to put it in the classpath was correct. I copied it in src/main/resources/{my package path} and it works. My mistake was I was putting it in src/main/resources directly.


text:
Q: How to create gradient blur in HTML & CSS? I have Layout.js which has Navigationbar inside navigation bar is just unordered list of list items
function Layout(props) {
    return <div>
        <NavigationBar />
        <main className={classes.main}>
            {props.children}
        </main>
    </div>
}

navbar.module.css is
.container {
    position: fixed;
    top: 0px;
    ..
    background: linear-gradient(rgba(37, 47, 81, 0.6),rgba(37, 47, 81, 0));
    backdrop-filter: blur(3px);
    ..

}

I want backdrop-filter: blur to be linear gradient as color because now it's just line where its starts to blur. Can someone help me easily fix this?
I tried webkit but it write warning that it is not supported by browsers.


text:
Q: Could the creation of many methods in Java affect performance? I was told by a colleague that in Java, the performance may be worse if we create more methods, stacking many methods calling over them in JVM, specially in a Java EE environment.
This seems to somewhat defeat the concept of object oriented programming. Like if we write long methods - what isn't good for code readability - we can achieve more performance due to less methods in JVM stack.
So, write many methods who call and interact with each other is worse to performance than write a few long methods to use less stacks in JVM? Is this is a correct affirmation?

A: It's probabbly an wrong assumption, first as common sense nested calls shouldn't have any (measurable) performance hit at all. After doing some research you'll find that the JVM can do some optimizations in your code "automagically":
Adaptive Optimization
And more importantly:
Inline Expansion
As you can see:

In computing, inline expansion, or inlining, is a manual or compiler
  optimization that replaces a function call site with the body of the
  callee

So probabbly, if you as programmer can say "hey, one big method is better than nesting tons of other methods", the JIT/JVM/javac can figure that for you and fix it >>IF<< it's worth.
I think that unless you get some numeric statistics, you are fine with tons of methods instead a monolithic piece of software.

A: The JVM have this thing called JIT, which would optimize the application's code with various techniques.
One of those is called "inline optimization". In this particular optimization, the JIT will automatically inline methods when needed, so, you might lost some processor cycles in this particular instant, even if it does, it's not sufficient to justify this kind of argument in my opinion.
It's always nice to remember that usually the performance hotspots are the I/O and database access. Also nice to remember that, nowadays, machine time is cheap and developer's time are expensive.
Further reading:

*

*http://docs.oracle.com/cd/E13150_01/jrockit_jvm/jrockit/geninfo/diagnos/underst_jit.html

*https://stackoverflow.com/questions/6495030/java-how-expensive-is-a-method-call

*http://java.dzone.com/articles/how-expensive-method-call-java

A: As others said, in Java its generally better to use lot of short methods, because they are JITed and inlined better.
But it's plausible that in EE enviroment situation can be different. At least for method that are not simply called, but there is aditional overhead because of 1) Transaction handling, 2) Interceptors 3) EJB remote calls (stay away from highly granual remote calls)
But if you split large method into multiple private methods, these overheads should not happen.
tl,dr:
Method call itself is not problem, additional overhead is (and you have controll over it)
PS: I would not even consider NOT splitting methods for performance reasons untill proven there actually is some performance problem. With clearer code you usually achieve better performance, because you much easier identify parts that are 1) not actually needed 2) are called multiple times with same result


text:
Q: Should I put connection.close() on all finaly in java Should I put connection.close() inside finally on try catch block? I tried to put connection.close() but i got and error "java.lang.NullPointerException"
here is the code on logging in is it Good to put rs.close() and pst.close() in every statement likeso below i insert it becuz if it is not there something pop up like database is locked..
Login
if(evt.getKeyCode()==KeyEvent.VK_ENTER){
        String sql = "select * from User_Table\n" +
                 "inner join Role_Table on User_Table.Role_ID=Role_Table.Role_ID\n" +
                 "where Username = ? and Password = ? and Role_Name = ?";
    try {
        pst = conn.prepareStatement(sql);
        pst.setString(1, jTextField1.getText());
        pst.setString(2, jPasswordField1.getText());
        pst.setString(3, (String) RoleComboBox.getSelectedItem());

        rs=pst.executeQuery();
    if(rs.next()){
        String A = rs.getString("First_Name");
        String B = rs.getString("Role_Name");
    if(RoleComboBox.getSelectedItem().toString().equals("Admin")){
        JOptionPane.showMessageDialog(null, "Hello "+B+" "+A,"Successfully Login",JOptionPane.INFORMATION_MESSAGE);
        rs.close();
        pst.close();
        AdminPortal AP = new AdminPortal();
        AP.setVisible(true);
        this.dispose();
    .... //and so on

    }else if(RoleComboBox.getSelectedItem().toString().equals("Laboratorist,EO")){
        JOptionPane.showMessageDialog(null, "Successfully Login");
        rs.close();
        pst.close();
    }}
    else{
        JOptionPane.showMessageDialog(null, "Incorrect Input","Error",JOptionPane.ERROR_MESSAGE);
    }
    }catch(Exception e){
        JOptionPane.showMessageDialog(null, e);
    }finally {
       try {
           rs.close();
           pst.close();
           conn.close();
       }catch(Exception e){

       }
    }
    }

here is the code on logout when I didn't put the con.close() there my system works fine but when i logout and login again it starts to got some error like database is locked but when I put the con.close()" i got some error "java.lang.NullPointerException"
Logout
int YesOrNo = JOptionPane.showConfirmDialog(null, "Do you want to logout?", "Logout",JOptionPane.YES_NO_OPTION);
    if(YesOrNo == 0){
        try {
            dispose();
            LoginForm LF = new LoginForm ();
            LF.setVisible(true);
            AddPatient.getObj().dispose();
            AddAppointments.getObj().dispose();
        } catch (Exception ex) {

        }finally{
            try{
                rs.close();
                pst.close();
                conn.close();
            }catch(Exception e){

            }
        }
    }else{

    }

i hope someone can help

A: If you have no further use of the connection you can close it on finally block.

A: Yes, all types of connections should be  closed in finally block.


text:
Q: What is the difference between OpenVPN via terminal and via network manager? When setting up an OpenVPN connection via network manager I need to import a CA.crt file. This is the minimum requirement.
When using the terminal command sudo openvpn config.conf I just need the config file but no extra certificate.
Why is this?

A: Surely config.conf has the certificate inside it? OpenVPN config files I have used in the past all contain the relevant certificate.


text:
Q: How to TAB out of quotes in Android Studio like Eclipse I have a question transitioning from Eclipse whenever I start to type something for a string or even for a Log.d i would get "" to automatically appear, which I've found out how to do this in Android Studio no problem, but in eclipse I use to be able to hit [TAB] and it would instantly jump outside of the " on the end so I can continue to type quickly anyone know if this is possible in Android Studio?

A: Unfortunately, this is currently not supported in Android Studio. The closest command to the desired behaviour would be Complete Current Statement (Ctrl+Shift+Enter) which only really works if you have only one parameter.


text:
Q: Embaressingly parallel processing using Open MPI and OpenMP It may be a silly question, anyway I am working on an embarrassingly parallel problem. I can divide the work into independent tasks (no communication) that can be performed in parallel.
In a shell script.sh one can use the following:
#!/bin/bash
let MY_ID=${OMPI_COMM_WORLD_RANK}
./a.out $MY_ID

In prog.c we have a simple independent program:
#include <string.h>
#include <stdlib.h>
#include <stdio.h>

int main(int argc, char *argv[]){
  int myid = atoi(argv[1]);
  if(myid%2==0)
    printf("\nI am %d and I am an even process\n", myid);
  else
    printf("\nI am %d and I am an odd process\n", myid);
  return 0;
}

And finally, to execute the program with 12 different processors:
mpirun -np 12 script.sh

My question is that is it possible to do the same thing using OpenMP and perhaps environment variables like OMP_NUM_THREADS ?

A: There is no OpenMP environment variable which, when passed to a program in the way you indicate, will be given a value different for each invocation of the program.  If you think about how OpenMP works you might think, as I do, that this doesn't make much sense - since the OpenMP program is implemented as a collection of threads.  This is in marked contrast to the model of operations of MPI in which each process is a separate process, bolstered with a library for inter-process communications - in this case it makes sense that each process have a unique identifier for facilitating communication.  When an OpenMP program executes communication between threads is effected by operations on shared memory locations, not by passing messages to specified threads.
In passing, you're not really writing an MPI program, just using one of the facilities its environment provides for making your shell-script writing a little easier.  You could almost as easily write a shell-script to send a different id to each invocation of the program without the MPI environment - and you could do the same for invocations of an OpenMP program.  Though why you would do either if your programs really are independent I don't know.

A: Too long to post it as a comment. Actually, this kind of parallel processing is useful for ensemble modeling. When your program runs for different initial condition, and each run creates different folder or output file.
I came up to this :
export OMP_NUM_THREADS=4
g++ prog.cpp -fopenmp
./a.out

in prog.cpp we have:
#include<stdio.h>
#include<stdlib.h>
#include<omp.h>
#include<string>

using std::string;

int main(){
    int nthreads, tid;
    string cmd;

    #pragma omp parallel private(tid)
    {
        tid = omp_get_thread_num();
        cmd = "echo 'this is a test. I am thread :' " + std::to_string(tid) ;
        system(cmd.c_str());  //each thread can creat a folder and run a script
        // system("./my_script.sh");
    }

    return 0;
}

with the output as follows:
this is a test. I am thread : 0
this is a test. I am thread : 3
this is a test. I am thread : 2
this is a test. I am thread : 1


text:
Q: Mac Error: Undefined symbols for architecture x86_64 I'm trying to install the MIT Language Modeling Toolkit. I've installed the dependencies, and ./autogen.sh works fine. However, when I compile with make, I get the error below. I am running OSX 10.10.3.
Undefined symbols for architecture x86_64:
  "std::__detail::_Prime_rehash_policy::_M_need_rehash(unsigned long, unsigned long, unsigned long) const", referenced from:
      std::_Hashtable<unsigned long, std::pair<unsigned long const, int>, std::allocator<std::pair<unsigned long const, int> >, std::__detail::_Select1st, std::equal_to<unsigned long>, std::hash<unsigned long>, std::__detail::_Mod_range_hashing, std::__detail::_Default_ranged_hash, std::__detail::_Prime_rehash_policy, std::__detail::_Hashtable_traits<false, false, true> >::_M_insert_unique_node(unsigned long, unsigned long, std::__detail::_Hash_node<std::pair<unsigned long const, int>, false>*) in evaluate-ngram.o
ld: symbol(s) not found for architecture x86_64
collect2: error: ld returned 1 exit status
make[1]: *** [evaluate-ngram] Error 1
make: *** [all-recursive] Error 1

A: Is it possible that the library uses C++11?
You'll have to add the following compiler flags:
-std=c++11 -stdlib=libc++

Mac OSX comes with two versions of the Standard Library, the older libstdc++ and the newer libc++. C++11 is only supported by the latter. More details can be found in this answer.
EDIT:
According to this source, to make your build system aware of your changes to the compiler flags, try the following:
$ export CXXFLAGS="-std=c++11 -stdlib=libc++"
$ export CC=`which clang` # optional step to make sure clang is being used
$ export CXX=`which clang++` # optional step to make sure clang is being used
$ ./autogen.sh
$ make


text:
Q: Need help understanding Scala Futures with Scrimage image package I'm trying to wrap my head around futures, and have a little sample of scaling a directory of images going...
Can some explain to me how this should work?
import com.sksamuel.scrimage._
import scala.concurrent._
import ExecutionContext.Implicits.global
import java.io._

object Test {

    def main(args: Array[String]) = {
        val dir = new File("/Users/bthibault/Downloads/ff_images/")
        dir.listFiles().foreach(file => AsyncImage(file).map( x => x.scale(0.5) ).onSuccess {
            case image => image.writer(Format.PNG).withMaxCompression.write(file)
        })
    }
}

I'm using the Scrimage package  https://github.com/sksamuel/scrimage/ where he gives an example of the Async operation... here is the actual Async file:
https://github.com/sksamuel/scrimage/blob/master/core/src/main/scala/com/sksamuel/scrimage/AsyncImage.scala
Can somebody help me understand what I need to do to get this working? I was playing with the map() function ... my thought was I need to return a real 'image' onSuccess rather than an AsyncImage ....

A: If you are trying to asynchronously resize all the images in the folder, and are asking for guidance on the correct syntax, then this will work:
object AsyncBatch extends App {

  val dir = new File(args(0))
  dir.listFiles.map(file =>
    AsyncImage(file)
      .flatMap(x => x.scale(0.5))
      .onSuccess {
      case image => image.writer(Format.PNG).write(file)
    })
}

Note: The withMaxCompression isn't supported on AsyncWriters. That's an oversight of the library.
Another way you can do this is with for comprehensions:
  val dir = new File(args(0))
  for ( file <- dir.listFiles;
        image <- AsyncImage(file);
        scaled <- image.scale(0.5) ) {
    scaled.writer(Format.PNG).write(file)
  }

Which I think is easier to read when you have lots of flatMaps and maps going on.


text:
Q: Prevent pages from rendering if the user is not logged in I'm using Lazy loading to render pages in my application.
{ path: 'dashboard', loadChildren: './dashboard/dashboard.module#DashboardModule', canActivate: [AuthGuard] }

Problem is if I type www.mydomain.com/dashboard in the URL, the browser actually renders the dashboard page even though the user is not logged in and the redirect to the login screen after a second or two.
How do I prevent the browser from rendering any page at all if the user is not logged in? Basically it should straightaway redirect to the login page.
AuthGuard Class
export class AuthGuard implements CanActivate {

  result: boolean = false;
  auth: any;
  outRes: any;

  constructor(private _authService: JwtService, private _router: Router) {

  }

  canActivate(next: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {

    this.outRes = this._authService.isAuthenticated();

    if (this.outRes) {
      this.outRes.subscribe(o => o ? true : this._authService.redirectToLogin());

      return true;
    } else {

      this._authService.redirectToLogin();
      return false;
    }

  }

}

Service Class
  public isAuthenticated() {

    if (!this.loggedIn)
      this.redirectToLogin();

    return this.httpClient.get<boolean>(`${this.settings.getApiSettings('uri')}/api/auth/IsTokenValid`, {
      params: { token: this.getToken }
    }).map( /// <<<=== use `map` here
      (response) => {

        if (response !== null) {

          var receivedToken = response["securityStamp"];
          var availableToken = localStorage.getItem('access_token');

           //Check if received a refreshed token. (tokens are refreshed every 15 minutes)
          if (receivedToken && receivedToken !== availableToken) {

            localStorage.removeItem('access_token');
            localStorage.setItem('access_token', response["securityStamp"]);

          }

        }

        let data = response;
        if (data == null)
          return false;
        else
          return true;

      }
    );

  }

  redirectToLogin() {

    localStorage.removeItem('access_token');
    window.location.href = "./login";

  }

A: Your main issue is this if (this.outRes) and this o => o ? true : this._authService.redirectToLogin() , you always get true because your function will always return a response and it will never be null;
you're basically checking if there is response but not what type of response (true/false);
 canActivate(next: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {

    let isAuth: any;
    this._authService.isAuthenticated()
       .subscribe(response => isAuth = response); //<== this can true or false based on service

    if (!isAuth) {
      this._authService.redirectToLogin();
    }
     return isAuth;
  }


text:
Q: How to join several big arrays into one? I'm fairly new to python, and I have 5 big arrays A,B,C,D,E with shapes:
((1000000, 8), (1000000, 7), (1000000, 13840), (1000000, 204), (1000000, 3))

dtypes:
(dtype('float64'), dtype('float64'), dtype('int64'), dtype('int64'), dtype('float64'))

Now i would like to join them all into a single array with a shape of
(1000000, 8+7+13840+204+3) = (1000000, 14062)

I have tried all possible ways (hstack/concate),
data_feature = np.concatenate((A,B,C,D,E), axis=1)
data_feature = np.hstack([A,B,C,D,E])
data_feature = np.hstack((A,B,C,D,E))
data_feature = np.column_stack([A,B,C,D,E])

but it all kills my system (Macbook Pro 2017/ 2.8GHz Intel Core i7/16 GB 2133 MHz LPDDR3), I think this could be a kernel problem, any suggestions that i can do this with my computer?

A: Given 64-bit (8 byte) values, you are trying to process:
1000000 * 14062 * 8 * 2 = 224'992'000'000 bytes

The 2 on the end is because you have inputs plus equal-size outputs.
That is 209 GiB of data.  You have 16 GiB of RAM.  It is not feasible.  You'll need to think harder about how you're processing your data, and how you can reduce it by a factor of 10.  Or buy a machine with 192 GiB of RAM (which is very possible these days, just not on a laptop).


text:
Q: Change color of line at runtime like microsoft paint in cocos2d I have a scene where I have few colored buttons and upon clicking on that colored button's respective colored line should be drawn in cocos2d. Please help me out with this.
I have tried passing different colors in -(void)draw function but that doesn't work. What I want is like MS Paint where user can have different color selction whereas I have put few color buttons.

A: While I can't think of answer for you directly you should take a look on the Cocos 2D forums for your answer.  I tried searching for "draw colored line" in the Cocos2D forums...
http://www.cocos2d-iphone.org/forum/search.php?q=draw+colored+line
Looks like it might be relevant to your situation.


text:
Q: Looking for an original citation of Hilbert Do the axioms of complete ordered number fields come from the geometry Axioms of Hilbert? "The Foundations of Geometry (1899)" or did Hilbert publish some other axioms which evolved into the field axioms?  I read this:

Hilbert had taken a totally different approach to defining the real
  numbers in 1900. He defined the real numbers to be a system with
  eighteen axioms. Sixteen of these axioms define what today we call an
  ordered field, while the other two were the Archimedean axiom and the
  completeness axiom.

The year seems not to line up 1899 vs 1900, and there were 21 geometry axioms as opposed to the 18 cited in the link.  If there was a separate paper in 1900 defining the reals, does anyone have the original citation?  I am not finding it, thanks.

A: See Foundations (1899) §13. COMPLEX NUMBER-SYSTEMS (page 23).
Hilbert enumerates 12 proerties of connection: $+, \cdot, 0, 1$, followed by 4 properties regarding order: $<$ and Archimedes axiom.
Up to now, 17 axioms.
Then he develops the so-called Algebra of segments, based on the plane geometry axioms (§24-on) and uses this "geometrical model" to show that:

theorems 1–6 of Section 13 are fulfilled. Moreover, [...] we have already shown that the laws 7–11 of operation, as given in Section 13, are all valid in this algebra of segments.
With the single exception of the commutative law of multiplication, therefore, all of the theorems of connection hold.

Then, in §28:

Upon the basis of the axioms of group II, we can easily show also that, in our algebra of segments, the laws 13–16 of operation given in Section 13 are fulfilled. Consequently, the totality of all the different segments forms a complex number system for which the laws 1–11, 13–16 of Section 13 hold; that is to say, all of the usual laws of operation except the commutative law of multiplication and the theorem of Archimedes.

Finally (§32), he proves the commutative law of multiplication.
The 18th axiom is the Axiom of Completeness (Vollständigkeit).