Assigning a value to a variable from another variable in SSIS (Properties -> Expression)

Question: I have a SSIS task that will assign a value from a variable (@[User::strLgtyInst]) to another variable (@[User::LgtyPer]). This is what I have:
<code>SET '" +  @[User::LgtyPer] +"' =  (SELECT [CUR_PRD_DATE]
FROM [Log_DP_Ctrl].[Ma].[Log_CUR_PRD]
WHERE [L_Instance] =  '" +  @[User::strLgtyInst] +"'')
</code>
When I evaliate the expression, it gives me this error:
Expression cannot be evaluated.
The data types "DT_WSTR" and "DT_DATE" are incompatible for binary operator "+". The operand types could not be implicitly cast into compatible types for the operation. To perform this operation, one or both operands need to be explicitly cast with a cast operator.
Attempt to set the result type of binary operation ""SET '" + @[User::LgtyPeriod]" failed with error code 0xC0047080.
So...
Error 1: Have to cast the variable being read. -> Please help with the syntax.
Error 2: SET... -> Don't know if that syntax is right.
Thank you.
Answer: You cannot set your SSIS variable the way you have tried to do since you are running a SQL query to set it. You will need to use an Execute SQL Task . Here are the steps.

Create a Variable @[User::SQLStatement] and in the expressions paste this  -
"SELECT [CUR_PRD_DATE]
FROM [Log_DP_Ctrl].[Ma].[Log_CUR_PRD]
WHERE [L_Instance] =  '" + (DT_WSTR, 50) @[User::strLgtyInst] +"'"
In your Execute SQL Task, select SQL source type as "Variable" and set the Source variable as User::SQLStatement. Set the ResultSet property to Single Row.
In the Result Set tab map CUR_PRD_DATE to @[User::strLgtyInst]

Hope this helps, let me know incase you have any additional questions.
Comment: I got an error. The @[User::strLgtyInst] variable is of type datetime, and [CUR_PRD_DATE], that is retrieved with the expression in "@[User::SQLStatement]", is also datetime.
This Is the error:
Comment: Error at Pkg_Fcst_Snapshot: The data types "DT_WSTR" and "DT_DATE" are incompatible for binary operator "+". The operand types could not be implicitly cast into compatible types for the operation. To perform this operation, one or both operands need to be explicitly cast with a cast operator.
Error at Pkg_Fcst_Snp: Attempt to set the result type of binary operation ""SELECT '" + @[User::LgtyPeriod]" failed with error code 0xC0047080.

Help please.
Comment: Cast it as String - Updated in answer
Comment: @user1330343 Still having troubles?
Comment: Hi, sorry, it took so long. This is my expression to convert datetime to string in th expression builder, but it's not working.

    "SELECT  SUBSTRING((DT_STR, 30, 1252) [CUR_PRD_DATE], 1, 19 )
    FROM [Logility_DP_Ctrl].[Maintenance].[Logility_CUR_PRD]
 WHERE [Lgty_Instance] =  '" + @[User::strLgtyInstance] +"'"
Comment: I meant cast @[User::strLgtyInstance] to String. This should not give you an error - "SELECT [CUR_PRD_DATE]  FROM [Logility_DP_Ctrl].[Maintenance].[Logility_CUR_PRD] WHERE [Lgty_Instance] = '" + (DT_WSTR, 50) @[User::strLgtyInst] +"'"
Comment: I changed the expression to:

    "SELECT [CUR_PRD_DATE] FROM [Log_DP_Ctrl].[Ma].[Log_CUR_PRD] WHERE
    [L_Instance] = '" + (DT_WSTR, 50) @[User::strLgtyInst] +"'"

Also I changed the data type of the variable receiving the result of this query to String, but the value is not passed when the variable with the result is used as data for a column.
Comment: Whats the result set property for the Execute SQL task set as?
Comment: In General tab: Single row
In Result Set tab: Result Name->LgtyPrdRslt, Variable Name-> User::LgtyPrd
Comment: Result name should be CUR_PRD_DATE unless you changed the query.
Comment: I changed that, and the errors I get from the progress report are:

[Extract data from LT [299]] Error: There was an error with output column "CUR_PRD_DATE" (1736) on output "OLE DB Source Output" (310). The column status returned was: "The value could not be converted because of a potential loss of data.".
Comment: [Extract data from LT [299]] Error: SSIS Error Code DTS_E_INDUCEDTRANSFORMFAILUREONERROR.  The "output column "CUR_PRD_DATE" (1736)" failed because error code 0xC0209072 occurred, and the error row disposition on "output column "CUR_PRD_DATE" (1736)" specifies failure on error. An error occurred on the specified object of the specified component.  There may be error messages posted before this with more information about the failure.
Comment: [SSIS.Pipeline] Error: SSIS Error Code DTS_E_PRIMEOUTPUTFAILED.  The PrimeOutput method on component "Extract data from LT" (299) returned error code 0xC0209029.  The component returned a failure code when the pipeline engine called PrimeOutput(). The meaning of the failure code is defined by the component, but the error is fatal and the pipeline stopped executing.  There may be error messages posted before this with more information about the failure.
Comment: Set the data type for @[User::strLgtyInst] as DateTime and see if that helps.


importing contactlist in phone

Question: I want to write an application that stores the contact list records, that user enters, so that the user will later be able to import them from within Symbian (and/or Android)  phone. What I'm asking is: is this possible and if so, what the format of stores should be in order to import records? Any help is appreciated.
Answer: Yes, it is possible. What you need is the Contacts API. You can find answers to your questions in the documentation.
Comment: Thank you, this is what i've looking for. I'll dig it up.

importing contactlist in phone


LibGDX Box2D Physics Direction Inverted

Question: For some reason in my world physics direction is inverted.I mean -9.8 gravity is acting like 9.8 gravity so objects are going up.Horizontal velocity is also inverted.Something must be wrong with x,y coordinate system.
world = World(Vector2(0f,-9.8f),false)   pushes objects up
is there a problem with PPM ?
package com.mygdx.game

import com.badlogic.gdx.ApplicationAdapter
import com.badlogic.gdx.Gdx
import com.badlogic.gdx.Input
import com.badlogic.gdx.graphics.GL20
import com.badlogic.gdx.math.Vector2
import com.badlogic.gdx.physics.box2d.*
import com.badlogic.gdx.graphics.OrthographicCamera
import com.badlogic.gdx.math.Vector3
import com.badlogic.gdx.physics.box2d.World
import com.badlogic.gdx.physics.box2d.Box2DDebugRenderer

class MyGdxGame : ApplicationAdapter() {

    val PPM = 32f

    private lateinit var camera : OrthographicCamera
    private lateinit var world :World
    private lateinit var player:Body
    private lateinit var platform:Body

    private lateinit var b2dr:Box2DDebugRenderer
    override fun create() {
        var w = Gdx.graphics.width
        var h = Gdx.graphics.height
        camera = OrthographicCamera()
        camera.setToOrtho(false, w / 2f, h / 2f)

        world = World(Vector2(0f,-9.8f),false)
        b2dr = Box2DDebugRenderer()

        player = createBox(2f,10f,32,32,false)
        platform = createBox(0f,0f,64,32,true)

    }

    override fun render() {
        update(Gdx.graphics.deltaTime)

        Gdx.gl.glClearColor(0f, 0f, 0f, 1f)
        Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT)
        b2dr.render(world,camera.combined.scl(PPM))

    }

    override fun resize(width: Int, height: Int) {

        camera.setToOrtho(false, width / 2f, height / 2f)
    }

    override fun dispose() {
        world.dispose()
      b2dr.dispose()

    }

    fun update(delta:Float){
         world.step(1/60f,6,2)
        inputUpdate(delta)
         cameraUpdate(delta)

    }
    fun inputUpdate(delta:Float){
        var horizontalForce = 0f;
        if(Gdx.input.isKeyPressed(Input.Keys.LEFT)){
          horizontalForce -=1

        }
        if(Gdx.input.isKeyPressed(Input.Keys.RIGHT)){
          horizontalForce +=1

        }
        if(Gdx.input.isKeyJustPressed(Input.Keys.UP)){
            player.applyForceToCenter(0f,300f,false)
        }
        player.setLinearVelocity(horizontalForce*5,player.linearVelocity.y)
    }
    fun cameraUpdate(delta:Float){
     var position:Vector3 = camera.position
        position.x = player.position.x * PPM // if you get box2d units multiply with ppm
        position.y = player.position.y * PPM
        camera.position.set(position)
        camera.update()

    }
    fun createBox(x:Float,y:Float,width:Int,height:Int,isStatic:Boolean):Body{
     var pBody:Body
        var def:BodyDef
        def = BodyDef()
        if(isStatic){
            def.type = BodyDef.BodyType.StaticBody
        }
        else{
            def.type = BodyDef.BodyType.DynamicBody
        }

        def.position.set(x/PPM,y/PPM)
        def.fixedRotation = true
        pBody = world.createBody(def)

        var shape:PolygonShape = PolygonShape()
        shape.setAsBox(width/2/PPM,height/2/PPM) // takes from center this is 32x32 box
        pBody.createFixture(shape,1.0f)

        shape.dispose()//clean it
        return pBody

    }

}

Comment: if you want your object to go in the different direction, use 9.8f instead of -9.8f
Comment: in what orientation (landscape, portrait) do you want to play the game?
Answer: It's all correct with box2d and your code.
-9.81 pushes objects up and 9.81 pull objects down.
In the World constructor, you set the gravity of the world.

And Gravity is a natural phenomenon by which all things with mass or
  energy—including planets, stars, galaxies, and even light—are brought
  toward (or gravitate toward) one another.

Basic Gravity is the force with which object attract each other.
So on Earth gravity is the force with which objects are attracted to the center of the earth.
On Earth, we have a gravity of ~ 9.81 means all Objects will pull to the center of the earth with a force of ~ 9.81 m/s².
Finally is it logical that if gravity is a force which pulls objects down that -gravity will push objects up.
On Earth, we have a gravity of ~ 9.81 not a gravity of ~ -9.81.
If it were, we would all end up outside in the universe.

LibGDX Box2D Physics Direction Inverted


Flutter App: The method 'call' was called on null

Question: I have make an application which search for something and displys them on the list. Once the search has some data, it fails with following error.

The method 'call' was called on null.
Receiver: null
Tried calling: call()

it is failing at
child: SearchBar

Following is my body.dart file.
Widget build(BuildContext context) {
    return Scaffold(
      body: SafeArea(
        child: Padding(
            padding: const EdgeInsets.symmetric(horizontal: 20),
            child: SearchBar<BookList>(
              onSearch: _isOnline
                  ? search
                  : _showToast(constants.offlineErrorMessage),
              onItemFound: _showToast("Data Found"),
              loader: const Center(child: CircularProgressIndicator()),
              emptyWidget: Center(
                  child: SelectableText.rich(
                _isOnline
                    ? TextSpan(
                        style: TextStyle(fontSize: 18),
                        children: [
                          TextSpan(
                              text:
                                  "\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tNo Data found!"),
                        ],
                      )
                    : TextSpan(text: constants.offlineErrorMessage),
              )),
             ),
              textStyle:
                  TextStyle(color: Colors.black, fontWeight: FontWeight.bold),
            )),
      ),
    );
  }

Search function:
Future<List<BookList>> search(String search) async {
  if (!isLoadingFirstTime) _showToast("Tap on image to maximize");

      List<BookList> finalList = await fetchDownloadableLink(bookList);
      isLoadingFirstTime = true;

       return finalList;
    }
  } catch (Exception) {
    throw Exception;
  }
}

Comment: Please provide search function also
Comment: Updated the question with search function
Answer: hope u create function called search
try to create another method like this.
Function SearchFunction(){
  return search();
}

and place this method there
onSearch: _isOnline
              ? SearchFunction
              : _showToast(constants.offlineErrorMessage),

Comment: `Future> search(String search) async {`

A function is created with Future return type. It is failing while rendering all the data coming from this function.

RenderObjectElement.insertChildRenderObject() is deprecated.

insertChildRenderObject() has been deprecated in favor of insertRenderObjectChild(). See
https://github.com/flutter/flutter/issues/63269 for details.


Converting a string (e.g. "202309101010") into a date object

Question: I have a string in the format "YYYYMMDDHHMM" (e.g. "202309101010") representing a date and time. I want to convert this string into a Date object in TypeScript.
I'm using the following code to achieve this conversion:
const dateString: string = "202309101010";
const year: number = parseInt(dateString.substring(0, 4), 10);
const month: number = parseInt(dateString.substring(4, 6), 10);
const day: number = parseInt(dateString.substring(6, 8), 10);
const hour: number = parseInt(dateString.substring(8, 10), 10);
const minute: number = parseInt(dateString.substring(10, 12), 10);

const formattedDate: Date = new Date(year, month - 1, day, hour, minute);
console.log(formattedDate);

While this works fine, I'm wondering if there's a more elegant or efficient way to achieve the same result. Are there any built-in TypeScript or JavaScript functions that could simplify this process? Or any other methods that could handle this conversion more gracefully?
Comment: You can use `moment.js` https://momentjs.com/guides/#/parsing/strict-mode/
Comment: @Daviid no I don't want to be dependent on specific libraries to do a conversion like this
Comment: @Behemoth the question is a common one and many answers can be found in google and stackoverflow, whoever downvoted probably thought that but didn't bother giving an explanation
Comment: @Daviid thank you, but in my case i can't use moment.js do you know any other native handling of TS?
Comment: check answer with @Lehks suggestion or check https://momentjs.com/docs/#/-project-status/recommendations/ for recommended alternatives
Answer: The ECMAScript spec describes the method for constructing a Date object from a string like this:

The function first attempts to parse the String according to the format described in Date Time String Format (18.104.22.168), including expanded years. If the String does not conform to that format the function may fall back to any implementation-specific heuristics or implementation-specific date formats. Strings that are unrecognizable or contain out-of-bounds format element values shall cause this function to return NaN.

That "Date Time String Format" it describes is of the form YYYY-MM-DDTHH:mm:ss.sssZ, which does not match the string format you are using. So if you want to construct a Date object from it with well-defined behaviour, then you are doing the right thing by first extracting its constituent parts and then passing them into the Date constructor as separate arguments.
As to how best to extract them, what you're doing now works just fine. There's no need to change it if it's not causing a problem.
That said, a ready alternative that comes to mind would be to use a regular expression, since that could both confirm that your string has the correct format and extract its parts (as strings, not numbers) in one call of match:
function toDate(dateString: string): Date {
    const dateStringPattern = /^(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})$/;

    const [match, ...parts] = dateString.match(dateStringPattern) ?? [];
    if (!match) {
        // Handle this error somehow
        throw new Error(`Incorrectly formatted string: '${dateString}'`)
    }

    const [year, month, day, hour, minute] = parts.map((part) => parseInt(part, 10));
    const formattedDate: Date = new Date(year, month - 1, day, hour, minute);
    return formattedDate;
}

console.log(toDate('202309101010'));
try {
    console.log(toDate('abc')); // Throws an error
} catch (e) {
    console.error(e);
}

TypeScript Playground
Comment: Thank you this is good solution to make safe the date-convert through the constructor.
Answer: You could use moment.js and parse the string like so:
moment('202309101010', 'YYYYMMDDhhmmss').format()

Or
date-fns
https://date-fns.org/v2.30.0/docs/parse#usage
var parse = require('date-fns/parse') // CommonJS
import parse from 'date-fns/parse' // ES 2015
import { parse } from 'date-fns' // ESM

parse('202309101010', 'YYYYMMDDhhmmss')

Comment: https://momentjs.com/docs/#/-project-status/
Comment: yes, it isn't deprecated, but I don't want to be dependent on specific libraries, i prefer a safe method in TS, but more elegant then mine.
Comment: [https://date-fns.org/](https://date-fns.org/) would be the better alternative to the deprecated moment.js.
Comment: Technically not deprecated, just finished development. It still works just fine.


Drush aliases and Permission denied (publickey,password) problem

Question: Im trying to use Drush Aliases but getting Permission denied (publickey,password) error. I can login to server using publickey without password but Drush can not.
I've read the solution mentioned here and made the change but no success. Is there anything I'm missing here?
Answer: A possible cause is that you are not specifying your remote user in the drush alias file.
For example, if the ssh command that works to allow you to login is:
<code>ssh email@example.com
</code>
Then an alias might look like this:
<code>$aliases['dev'] = array(
  'uri' => 'http://www.example.com',
  'root' => '/var/www/vhosts/example.com/docroot/',
  'remote-host' => 'example.com',
  'remote-user' => 'myuser'
);
</code>


DividerItemDecoration will not work no matter what I do

Question: This is the code for setting the decoration :-
recyclerView.addItemDecoration(new DividerItemDecoration(recyclerView.getContext(), DividerItemDecoration.HORIZONTAL));

This is the xml :-
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle">
    <size android:height="1dp" />
    <solid android:color="@android:color/black" />
</shape>

I have tried setting the drawable using DividerItemDecoration.setDrawable(Drawable drawable)
and setting the android:listDivider item in my theme to point to the xml.
I have also tried setting the width to 1dp. Absolutely nothing works.
Any help is appreciated, thanks.
Comment: don't use "recyclerView.getContext()". if you have activity then use "ActivityName.this" as context and if you use Fragment then use "getContext" as context.
Comment: @TakeInfo Just tried, did not work
Comment: What is the orientation of your RecyclerView? I would try passing in the orientation of the RecyclerView when you set your divider.
Comment: Use LinearLayout.HORIZONTAL or RelativeLayout.HORIZOTAL which you use as root node in your xml file  instead of DividerItemDecoration.HORIZONTAL
Comment: android:listDivider is used for ListView, it's not suitable for RecycleView
Answer: If the orientation of your RecyclerView is default(vertical), then you should use DividerItemDecoration.VERTICAL instead.
I've just tried creating a RecyclerView with a default DividerItemDecoration and your xml resource, and everything worked
Comment: That did it! I mistook the orientation parameter to be the orientation I want the line to be and not the RecyclerView orientation as it should be. Thanks a ton :)


ERRO DE ATRIBUTO EM LAYOUT PYTHON

Question: Estou fazendo um projeto em Python com o PySimpleGUI usando sg pra layout simples, porém o terminal do PyCharm me retorna o erro de falta de atribuição de valor tentei ir pelo terminal do powershell e cmd e deu o mesmo erro
import PySimpleGUI as sg

class TelaPython:
    def _init_(self):

        layout = [
            [sg.Text('Nome'),sg.Input()],
            [sg.Text('Senha'),sg.Input()],
            [sg.Button('Login')],
            [sg.Button('Cadastrar')],

        ]

        janela = sg.Window(Login).layout(layout)

        self.button, self.values = janela.Read()

    def Iniciar(self):
        print(self.values)

tela = TelaPython()
tela.Iniciar()

Answer: Você está tentando acessar uma variável da classe que não foi criada.
  self.values = janela.Read()

Adicione a variável e tente novamente.
import PySimpleGUI as sg

class TelaPython:

    values = ''

    def _init_(self):

        layout = [
            [sg.Text('Nome'),sg.Input()],
            [sg.Text('Senha'),sg.Input()],
            [sg.Button('Login')],
            [sg.Button('Cadastrar')],
        ]

        janela = sg.Window(Login).layout(layout)

        self.button, self.values = janela.Read()

    def Iniciar(self):
        print(self.values)

tela = TelaPython()
tela.Iniciar()

ERRO DE ATRIBUTO EM LAYOUT PYTHON


Integrability of a function $g$ that is different at $n$ points from $f$ Riemann integrable

Question: I have proved the following statement and I would like to know if I have made any mistakes:
"Suppose $f:[a,b]\to\mathbb{R}$ is Riemann integrable. Suppose $g:[a,b]\to\mathbb{R}$ is a function such that $g(x)=f(x)$ for all except finitely many $x\in [a,b]$. Prove that $g$ is Riemann integrable on $[a,b]$ and $\int_{a}^{b}g=\int_{a}^{b}f$."
My proof:
Let $d_1,\dots, d_n$ be the points such that $g(d_i)\neq f(d_i),\ 1\leq i\leq n$.
Let $\varepsilon>0$ and $P=a=x_0<x_1<\dots<x_N=b$ a partition of $[a,b]$ such that $x_j-x_{j-1}<\frac{\varepsilon}{N(\sup_{[a,b]}g-\inf_{[a,b]}g +1)}$: then $$U(g,P,[a,b])-L(g,P,[a,b])=\sum_{j=1}^{N}(x_j-x_{j-1})(\sup_{[x_{j-1},x_j]}g-\inf_{[x_{j-1},x_j]}g)<\sum_{j=1}^{N}\frac{\varepsilon}{N}=N\frac{\varepsilon}{N}=\varepsilon$$ so we have shown that for any $\varepsilon>0$ there exists a partition P such that $U(g,P,[a,b])-L(g,P,[a,b])<\varepsilon$ so $g$ is Riemann integrable, i.e. $U(g,[a,b])=L(g,[a,b])=\int_{a}^{b}g$.
Also, since $f$ and $g$ coincide in every interval where there is not a $d$-point, and there are at most $n$ such intervals which we label $[k_{j-1},k_j]\ 1\leq j\leq n$, and $\sup_B f-\inf_B g \leq \sup_A f-\inf_A g$ if $B\subset A$ (in such a case $\inf_B f\geq \inf_A f $ and $\sup_B f\leq \sup_A f$) we have $$U(f,[a,b])-L(g,[a,b])\leq U(f,P,[a,b])-L(g,P,[a,b])\leq (x_{k_1}-{x_{k_1-1}})(\sup_{[x_{k_1-1},{x_{k_1}}]}f-\inf_{[x_{k_1-1},x_{k_1}]}g)+\dots+(x_{k_n}-x_{k_n-1})(\sup_{[x_{k_n-1},{x_{k_n}}]}f-\inf_{[x_{k_n-1},{x_{k_n}}]}g)<\frac{\varepsilon}{N(\sup_{[a,b]}g-\inf_{[a,b]}g +1)}(\sup_{[a,b]}g-\inf_{[a,b]}g) + \dots + \frac{\varepsilon}{N(\sup_{[a,b]}g-\inf_{[a,b]}g +1)}(\sup_{[a,b]}g-\inf_{[a,b]}g)<\frac{\varepsilon}{N}+\dots +\frac{\varepsilon}{N}=\varepsilon$$ so we can also conclude that $U(f,[a,b])=L(g,[a,b])$ which (since $f$ Riemann integrable means $\int_{a}^{b}f=U(f,[a,b])=L(f,[a,b])$) implies  $\int_{a}^{b}f=\int_{a}^{b}g$, as desired.
Comment: Your proof looks fine, but if you want a slightly more efficient and less technical proof, show that if a function $h$ differs from the $0$ function at finitely many points, then it is integrable and its integral is equal to $0$. Then, if $f$ and $g$ are two functions which differ at finitely many points and $f$ is integrable, define $h=f-g$ to get that $h$ is integrable. Then $g=f-h$ so $g$ is integrable, since both $f$ and $h$ are integrable. Then you're done from there.
Comment: Please use double dollar sign so your question is more or less readable.
Comment: @vitamind fixed, thanks.
Answer: Consider the function $h:[a,b]\to\mathbb{R}, h=f-g$ i.e. $h(x):=f(x)-g(x)$ for all $x\in [a,b]$. Then $h$ is $0$ except at a finite number $N$ of points, namely those where $f$ and $g$ differ: let $d_1,\dots, d_N$ denote those points.
Let $\varepsilon>0$, $H:=\max\{|h(d_i)|:1\leq i\leq n\}$, take $n>\frac{N(b-a)H}{\varepsilon}$ and let $P$ be the equally spaced partition $a = x_0, x_1\dots, x_n = b$ of $[a, b]$ with $x_j−x_{j−1} =\frac{b−a}{n}$ for each $j = 1,\dots,n$.
Then $U(h,P,[a,b])=\sum_{j=1}^{n}(x_j-x_{j-1})\sup_{[x_{j-1},x_j]}h\leq\frac{N(b-a)H}{n}$ and $L(h,P,[a,b])=\sum_{j=1}^{n}(x_j-x_{j-1})\inf_{[x_{j-1},x_j]}h=0$ so $U(h,P,[a,b])-L(h,P,[a,b])\leq\frac{N(b-a)H}{n}-0\leq\frac{N(b-a)H}{n}<\varepsilon$. Since $\varepsilon>0$ was chosen arbitrarily this implies that $h$ is integrable; hence $-h$ is integrable too and so is $g=f+(-h)=f-h$.
Also, $\int_{a}^{b}h=\sup_P L(h,P,[a,b])=\sup_P 0=0$, so $\int_{a}^{b}g=\int_{a}^{b}(f+(-h))=\int_{a}^{b}f+\int_{a}^{b}(-h)=\int_{a}^{b}f-\int_{a}^{b}h=\int_{a}^{b}f.$ $\square$


Variance of Product of Ind. Variables

Question: Whats wrong with my approach to answer the following question?
The number of customers arriving to a fast food restaurant between 7 am and 9 am has the Poisson distribution with mean 40. Suppose that each customer spends in the restaurant a random amount, uniformly distributed between $8$ and $20$ (the amounts spent by different customers are independent, and also independent of the number of the arriving customers). Let X be the total amount spent by the customers between 7 am and 9 am. Find EX and Var(X).
Let $Y$ be the number of customers in the fast food restaurant between  $7$ am and $9$ am. It is given that $f_Y = \frac{40^ye^{-40}}{y!}$ with $R_Y = \{0,1,\dots\}.$
Let $Z$ be the amount spent by a costumer between $7$ am and $9$ am. It is given that $f_Z = \frac{1}{12}$ with $R_Z = (8,20)$. $X$ is given by $X = YZ$. Since $Y$ and $Z$ are independent,
\begin{align*}
    E(X) = E(YZ) &= E(Y)E(Z)\\
    &= (40)(14)\\
    &= 560
\end{align*}
and
\begin{align*}
    Var(YZ) &= Var(Y)Var(Z) + Var(Y)E(Z)^2 + Var(Z)E(Y)^2\\
    &=(40)(12) +(40)(14)^2+ (12)(40)^2\\
    &= 27520
\end{align*}
Answer: Wait... $Z$ is the amount of time spent by which customer?
No.   If $Z_k$ is the amount of time spent by the $k$eth customer, what you seek is the expectation and variance for the random variable  $$X:=\sum_{k=1}^Y Z_k$$
That is the sum of $Y$ independent random variables, which is not the same thing as $YZ_1$, the sum of $Y$ occurrences of the same random variable.

Given $Y\sim\mathcal{Pois}(40)$, we know $\mathsf E(Y)=\mathsf{Var}(Y)=40$
Given for any $k$ that  $Z_k\sim\mathcal U(8;20)$, we know $\mathsf E(Z_k)= 14$ and $\mathsf {Var}(Z_k)=12$
We are also given that $Y, Z_1, Z_2,\ldots$ are mutually independent.
Then indeed it is that :
$$\begin{split}\mathsf E(X) &= \mathsf E(\mathsf E(\sum_{k=1}^Y Z_k\mid Y))\\[1ex]&=\mathsf E(Y)\mathsf E(Z_1)\end{split}$$
However, it is instead that: $$\begin{split}\mathsf{Var}(X) &= \mathsf E(\mathsf {Var}(\sum_{k=1}^Y Z_k\mid Y))+\mathsf{Var}(\mathsf E(\sum_{k=1}^YZ_k\mid Y))\\[1ex] &= \mathsf E(Y~\mathsf {Var}(Z_1))+\mathsf{Var}(Y~\mathsf E(Z_1))\\[1ex]& = \mathsf E(Y)~\mathsf{Var}(Z_1)+\mathsf E(Z_1)^2~\mathsf{Var}(Y)\\\end{split}$$

Variance of Product of Ind. Variables


Spring boot - jsr352 batch implementation - Beans not getting reference in jobxml

Question: I am implementing a batch application using springboot 2.4.3 + jsr352. There is a simple batchlet class(sleepybatchlet) defined. I am trying to reference it in the JSL. but It fails saying classnotfound exception when the job is started using joboperator.
sleepy-batchlet.xml:
<job xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/jobXML_1_0.xsd" restartable="true" version="1.0" id="sleepy-batchlet">
    <step id="step1">
        <batchlet ref="sleepyBatchlet">
            <properties>
                <property name="sleep.time.seconds" value="#{jobParameters['sleep.time.seconds']}" />
            </properties>
        </batchlet>
    </step>
</job>

Below is my batchlet class which is annotated with @Named
@Named
public class SleepyBatchlet extends AbstractBatchlet{
private final static Logger logger = Logger.getLogger(SleepyBatchlet.class.getName());
private Map<ReportMetaData,byte[]> pdfMetadataMap;

/**
 * Logging helper.
 */
protected static void log(String method, Object msg) {
    System.out.println("SleepyBatchlet: " + method + ": " + msg);
    // logger.info("SleepyBatchlet: " + method + ": " + String.valueOf(msg));
}

/**
 * This flag gets set if the batchlet is stopped.  This will break the batchlet
 * out of its sleepy loop.
 */
private volatile boolean stopRequested = false;

/**
 * The total sleep time, in seconds.
 */
@Inject
@BatchProperty(name = "sleep.time.seconds")
String sleepTimeSecondsProperty;
private int sleepTime_s = 3;

@Inject
private JschFileUtil jschFileUtil;

@Override
public String process() throws Exception {

    log("process", "entry");
    System.out.println("Test");
    return "exitStatus";
}

/**
 * Called if the batchlet is stopped by the container.
 */
@Override
public void stop() throws Exception {
    log("stop:", "");
    stopRequested = true;
}

}
Defined the bean in java configuration class as well.
@Autowired
private SleepyBatchlet sleepyBatchlet;
@Bean
public Batchlet fooBatchlet() {
    return sleepyBatchlet;
}

But for some reason, Its not getting referenced in the JSL.  Can someone please suggest what needs to be done to use the bean created already ?
Comment: You seem to be hitting this issue: https://github.com/spring-projects/spring-batch/issues/1175. If you provide a minimal project that reproduces the problem, I can try to see if the is a workaround until the issue is fixed.
Comment: sure, let me work on sharing the minimal project
Comment: @MahmoudBenHassine I added sample springboot+jsr352 application here . https://github.com/MekalaJ/demo
Comment: curl --location --request POST 'http://localhost:8080/job' \
--header 'Content-Type: text/plain' \
--data-raw 'sleepy-batchlet'
Comment: When we run the job by hitting the rest endpoint, It fails with classnotfound exception
Comment: ok thanks. I will take a look.
Comment: I just tried your example and added an answer. With this change, your example works without the `ClassNotFoundException`.
Comment: @MahmoudBenHassine do you have any input on it - https://stackoverflow.com/questions/67202085/springbatch-how-to-process-files-itself-as-a-item. thank you.
Answer:
I am trying to reference it in the JSL. but It fails saying classnotfound exception when the job is started using joboperator.

This is because you are referring to the class by its name and not its fully qualified name.

I added sample springboot+jsr352 application here . github.com/MekalaJ/demo

In your example, you need to update your step definition as follows:
        <batchlet ref="com.example.demo.batch.SleepyBatchlet">
            <properties>
                <property name="sleep.time.seconds" value="#{jobParameters['sleep.time.seconds']}" />
            </properties>
        </batchlet>

Comment: yeah, this would work but it will try to create a new bean of type sleepybatchlet. not refer the one thats created by @inject/@component.
Comment: do you have any suggestion on this - https://stackoverflow.com/questions/67202085/springbatch-how-to-process-files-itself-as-a-item
Comment: I accpted the answer already. Its showing as accpted answer for me.
Comment: I don't see it as accepted, but no worries, the most important thing is that you solved your issue :-) Glad to be of help.


Radial Basis Functions in $\mathbb R^3$ - How to interpolate?

Question: I am fairly new to radial basis functions. I get the concept, but I need a little explanation or coaching when it comes to the actual application.
Let's assume that I have $n$ points in $\mathbb R^3$ with their location $(x,y,z)$. Each point has a scalar value $f$ associated to it. What do I have to do to get the value of $f$ at a previously unknown point?
From my understanding $\mathbf{x}$ and $\mathbf{x}_i$ in
$y(\mathbf{x})=\sum\limits_{i=1}^Nw_i\phi(||\mathbf{x}-\mathbf{x}_i||)$
may be any n-dimensional array, so here my point locations in $\mathbb R^3$. How do I get from there to my interpolation for the value $f_K$ at a previously unknown point $(x_k,y_k,z_k)$? Unfortunately, I was unable to find an example I do understand in my initial search.
Comment: You can do something called a channel encoding of the position of new point. Have you done channel coding by some method before?
Comment: No, the subject is new to me
Answer: You can do a channel coding of the position $(x_k,y_k,z_k)$:
$$p_i({\bf x_k}) = \frac{\phi(\|{\bf x_k-x_i}\|)}{\displaystyle\sum_{\forall j}{\phi(\|{\bf x_k-x_j}\|)}}$$
The reason why we choose name p is that because of this division above we normalize so that the value for each known position is a probability. You can verify that $\sum_ip_i({\bf x_k})$ shall become 1.
Now we have probability of belonging to each channel. We can simply make weighted average according to this probability:
$${\hat {f_k}} =\sum_{\forall \text{ "known" } i} p_i({\bf x_k})f_i$$
Comment: Thanks, so the weights are gone due to the normalization? What would be the steps to solve this in pseudocode? I see a linear system of equations in there?!
Comment: We could say $p_i({\bf x_k})$ will be the weights here. Actually there is no linear equation system, I really wanted to add one, but it wasn't needed, actually. ;)
Comment: Pseudocode would be, calculate all the $\phi$ in a for loop where we also accumulate this sum. Another loop where we calculate the $p_i$ by dividing each calculated $\phi$ by the accumulated sum. In this loop we can also calculate $\hat {f_k}$ since it is just linear combination based on these $p_i$


Bayesian models: Bayesian t-test on effect posterior against 0 as index of effect existence

Question: I am fitting Bayesian models (using R and rstanarm). Beyond estimating the effect of each predictor (and extracting pointwise indices such as median, MAD and 90% CI), I am also interested in having a general index of effect existence (telling if the effect is "different" (in the common sense) from 0). Two ways I can imagine of doing this are:

Extracting the probability that the effect is in one particular
direction (i.e., the area under the density curve of one "side"
(from 0) of the posterior distribution (e.g., the probability that
an effect is positive vs. the probabiltiy that the effect is null or
opposite)).
Performing a Bayesian t.test of the posterior distribution
against mu=0 and computing the Bayes factor, the odds that the
effect distribution is different from 0. Unfortunately, due to the large size of the posterior distribution (for example 4000 draws), the Bayes factor is almost always infinite, even if the distribution heavily overlaps 0 and the opposite side.

What could I do?
Answer: The problem is not in the methods to answer, but in the question:

telling if the effect is different from 0

The effect or the coefficient or whatever have a distribution density. But given, that 0 is a point on a real scale, it has a probability of zero to begin with. There is an infinite number of points on the real scale and if each of them had a probability $P > 0$, than the sum of their probabilites would be larger then one, which cannot be.
The coefficient or the effect being in any given interval, has a probability, the coefficent or the effect being one exact value is zero. Please read about the concept of "Region of Practical Equivalence (ROPE)" and you will find good answers how to proceed.

vs. the probabiltiy that the effect is null or opposite

The probability of the effect being null or opposite is identical with the probability of it being opposite. Still, this is a valid way to proceed.
E D I T:
After I posted my answer, you edited the question from "different from 0" to "different (in the common sense)". Now this is a mathematical question and it needs a precise definition of different. "different in the common sense" is not precise. You can compute with numbers, not with senses. You will have to define, what difference is "different enough", and that is what you do, when you define the ROPE (which I advised to look up above).
Trying to test, whether a true real value is really different from a point (e.g., zero) is one of the oddities of Frequentism, that brings people to Bayesian methods.


Describing the algebra representations of the Laurent polynomials

Question: Let $k$ be your favorite field. The "Laurent polynomials" in one variable is the commutative polynomial algebra $k[x,x^{-1}]$ in the two variables $x$ and $x^{-1}$ together with the obvious relation $x.x^{-1} = 1$. Where can I find a decsription of the representations of this algebra?
Edit: By a representation I mean a linear map from $k[x,x^{-1}]$ to the matrices on a finite-dim $k$-vector space (where multiplication is composition of linear maps).
Comment: Another formulation is that you are looking for the (finite-dimensional) linear representations of the group $\mathbb{Z}$. Such a representation is just the data of a vector space $V$ and an automorphism of $V$ (the image of $x$).
Comment: Welcome to MSE. I suggest that you add the [tag:reference-request] to your question.
Comment: @Jose: Ok - it has been done!
Answer: To expand on Captain Lama's comments :
$k[x,x^{-1}]$ is canonically isomorphic to the group algebra $k[\mathbb{Z}]$. Indeed, we have a group homomorphism $\mathbb{Z}\mapsto k[x,x^{-1}]$ sending $1$ to $x$, which induces a $k$-algebra morphism $k[\mathbb{Z}]\to k[x,x^{-1}]$, which is easily seen to be an isomorphism.
Now, for any group $G$, the set of $k$-algebra representations $k[G]\to End(V)$ is canonically isomorphic to the set of (finite dimensional) linear representations $G\to GL(V)$.
Indeed, if we have a linear representation $G\to GL(V)\subset End(V)$, it extends to a $k$-algebra morphism $k[G]\to End(V)$ .
Conversely, since $G\subset k[G]^\times$, a  $k$-algebra morphism $k[G]\to End(V)$ restricts to a group morphism $G\to End(V)^\times=GL(V)$. Both constructions are mutally inverse.
Hence for $G=\mathbb{Z}$, it is enough to compute $Hom_{grps}(\mathbb{Z},GL(V))$, which is canonically isomorphic to $GL(V)$, since a morphism from $\mathbb{Z}$ to any group is uniquely determined by the image of $1$.
Note that two representations $V$, $V'$ of $\mathbb{Z}$ will be equivalent if and only if the corresponding automorphisms $u,u'$ are conjugate (by an isomorphism $V\overset{\sim}{\to} V'$).
So, if you keep track of all identifications, you will end up with the following description: all the representations $k[x,x^{-1}]\to End(V)$ have the form $\rho_{u}:k[x,x^{-1}]\to GL(V)$, where $u\in GL(V)$ and $\rho_u(\displaystyle\sum_{m\in\mathbb{Z}} a_m x^m)=\sum_{m\in\mathbb{Z}}a_mu^m$ (where the $a_m'$ s are all zero except for a finite number of them).
Moreover, equivalence  classes of algebra representations corresponds to similitary classes of automorphisms.
Comment: Thanks for the nice answer. Does that mean that each finite-dim $V$ breaks up into a direct sum of $1$-dim sub-irreps?
Comment: No. Not every $u$ is diagonalizable...
Comment: Yes, of course - good point.
Comment: So more generally, for any finitely generated torsion-free abelian group $\mathbb{Z}^n$, the linear representations will look like this? I mean to say, we would have $n$ commuting matrices and a map from each $1_k$ to the $k$-th generator?


Making a Java Application available via a Web Browser

Question: I am working on a Java program that has bunch of classes consisting of dialog boxes, JFrames, etc.
Can someone guide me where I can learn how to transform it to an 'applet' kind of. ( I don't even know if applet is the right word)
Like for example, can it be accessible through the internet browser. If I somehow make a domain www.myjavaprogram2011.com  it would be nice if it will take it straight to the java program I coded. I see this as anyone can come to this website and use that program.
Thanks!
Answer: You may want to look into Jars for distribution or probably more aptly Java Web Start as this allows Clients to be downloaded and run.
Comment: java web start...hmm this sounds like a good keyword to google. Thanks. I shall look in to this.
Answer: Java Applets isn't your best bet as there's lots of security permissions that you need to worry about as well as your jars needs to be signed (especially for client/server data access).
Try using Java Web Start, it will allow you to launch fully-featured application from the Web Browser. Oracle has tutorials on deployment of JWS, etc.
Answer: Sounds you're looking for some kind of RIA technology. Have a look at JavaFX, though it's not mature yet IMHO.
Ah, but then, if you already have a Swing application then this isn't an option probably.


Gm+6 Chord notation

Question: I've seen a chord notated as Gm+6 — is that supposed to be a Gm with a 6th so G B D# E ? it sounds really off and unrelated to the song... What is this notation?
context: https://imgur.com/a/DcmtYJC
Comment: Please post an image of the symbol with some of the surrounding context.
Comment: The updates are very helpful; however, it's now clear that the notation is non-standard — both the chord notation and the transliteration of the lyrics. If possible, please add the name of the source so that the original can be looked up.
Comment: This is not a standard notation. Maybe it could be guessed from the context. It could be either some less notation, or a typo. In particular, as Tim points out, G B D# E would likely be notated as Em(maj7)/G.
Answer: The latest picture indicates that this is a Gm+6 chord.
Since there is a Gm6/4 chord earlier in the excerpt, I am forced to assume that the "+6" means "add6" and the resulting chord is therefore G-B♭-D-E.
Comment: I don't recall ever seeing such notation before, but the explanation makes sense.
Answer: This just MIGHT be an attempt to apply chord symbols to 'classical' harmony.  There is a chord called an  Augmented 6th.
https://en.wikipedia.org/wiki/Augmented_sixth_chord
An Augmented 6th rooted on G would be (or rather COULD be, there are three flavours of the Aug6 chord) G, B, D, E♯, and would typically act as a pre-dominant to something rooted on F♯.
But I suspect it's a mis-named 'G(add6)' or just 'G6'.  Can we see some context?
LATER And now we have some context:
We're in D minor.  It precedes an A7.   Almost certainly an attempt to convey 'Gm plus the 6th'.   And probably really implies 'Em7♭5'.
Comment: How would this be different than a Gm7? (my bad, what's written is a Gm+6, I made an edit, and added a context picture)
Answer: First I'd like to point out that in decades of playing and reading music I have never encountered this specific symbol so it is probably an error or a symbol created by someone that doesn't quite know how to spell chords. Where have you seen this chord symbol? Adding some context (showing the entire page or at least surrounding bars) would be helpful in figuring out exactly what it is.
Assuming this was intentional there are two possibilities, both of which should be written differently for clarity.
The first is a G with an augmented 6th. That is G-B-D-E#. If this is what is desired then it should be written like this; G(+6) or G(add +6). This chord however is enharmonically a G7 so the only reason for writing it the other way is for some theoretical reason, for example showing some type of voice leading: G(b6)-G6-G(+6).
The other option is an augmented triad with an added 6th. That would be G-B-D#-E. That would be better described as G+(6) or G+(add 6) to clarify that it is not the 6th that is augmented. It is unusual but if someone wanted a m2 cluster of D# and E this would be the way to write it.
The bottom line is that assuming no error it is a vague symbol as is. The parentheses I added in each example make it clear one way or the other. The surrounding context might give a clue as to what the writer's intentions are.
Comment: I wonder whether the + is simply someone's attempt at "add," in other words it's not augmented at all, and is just a G chord with an E added.
Comment: @ElementsinSpace Yup. I wonder whether that's what's intended. Without the context we'll never know.
Comment: @ElementsinSpace it's possible that the context might also not even reveal what it actually is, thus my answer, if it's this write it this way, etc. These "I've seen" questions are are usually vague to begin with.
Comment: @AndyBonner Isn't that just a G6 chord?
Comment: @AndyBonner It's possible but not correct as you know. I have seen people use + and - in place of # and b, for example: C7(+9) or C7(-9) but not for adding a note to a chord.
Answer: Just like John, after decades of reading music, this is a first. Probably written by someone who didn't have much of a clue!
With some surrounding bits, or a snippet of the song at that point, it would ease an answer. However, the best guess would be Gadd6, otherwise usually called simply G6. GBDE. Try that, and hear if it fits in that place. There's often confusion with greenhorns between + and add, but they're different - + means augmented, whereas add means play this out-of-chord note too.
EDIT: on reflection - even though OP says it doesn't fit - EGBD♯ does produce a recognisable, although fleeting chord, Em (maj7), but I doubt that's the one discussed here.
EDIT (to allow for OP's edit) Gm+6 will most likely be Gm(add6), more commonly known as Gm6. Never, or rarely written as Gm+6, which gives completely the wrong name. I vtc, as the question itself contains conflicting information - calling it Gm, then spelling it GB.
Answer: While there are several different chord label systems the ones you see most often are pretty consistent and the most common chords used in songs will be fairly obvious to read in those different systems.
Usually you encounter chords that are either diatonic, common altered chords, or "add" or "sus" chords.
The confusion here is "+" usually being used to indicate an "augmented" chord (where the fifth of the chord is the augmented chord tone) or whether "+" was meant to mean "add" (mostly for "add2", "add9", or "add6" where all those intervals added are conventionally major.)
So, is it supposed to be a G augmented triad with an (assumed major) sixth added, or a G major triad with an "add6?"
G augmented triad with major sixth is G B D# E a chord that is neither diatonic nor a common altered chord. If you wanted to write that more clearly, G+(add6) would be one way to do it, Gaug(add6) is even more emphatic.
G is G B D E is both diatonic and very, very common. The usual ways to write it are Gadd6 or just G6. Does the chord sound major? If so, this is probably the way to go.
As Tim pointed out G B D# E could be Em(maj7)/G, but aurally you would expect that to have a fairly clear minor sound.
Do the chords sound unusual? If not, it's more likely the chord is meant to be conventional and it's the writer's way of naming chords that is unusual. You would need an explanation from the writer or a transcription of the song to say more.
Answer: Other answers have missed that this is a G minor chord (they all suggest using B natural).  Especially given the context and the preceding Gm chord, this is almost certainly a G minor triad, G Bb D, with an added 6th degree, E.  The plus sign is confusing I agree, and Gm6 or Gm(add6) would be clearer.  It could also be written as a half-diminished seventh on E (E G Bb D), which functions as the ii of D minor.
Comment: The answerers didn't miss anything. The question was edited after they answered. The original version asked about a "G+6" chord.
Comment: Ah, that makes sense.  I was wondering how so many people missed that!

Gm+6 Chord notation


PHP explode the string, but treat words in quotes as a single word

Question: How can I explode the following string:
Lorem ipsum "dolor sit amet" consectetur "adipiscing elit" dolor

into
array("Lorem", "ipsum", "dolor sit amet", "consectetur", "adipiscing elit", "dolor")

So that the text in quotation is treated as a single word.
Here's what I have for now:
$mytext = "Lorem ipsum %22dolor sit amet%22 consectetur %22adipiscing elit%22 dolor"
$noquotes = str_replace("%22", "", $mytext");
$newarray = explode(" ", $noquotes);

but my code divides each word into an array. How do I make words inside quotation marks treated as one word?
Comment: This sounds like a job for Regex
Comment: See also [An explode() function that ignores characters inside quotes?](http://stackoverflow.com/questions/3264775/an-explode-function-that-ignores-characters-inside-quotes)
Answer: You could use a preg_match_all(...):
$text = 'Lorem ipsum "dolor sit amet" consectetur "adipiscing \\"elit" dolor';
preg_match_all('/"(?:\\\\.|[^\\\\"])*"|\S+/', $text, $matches);
print_r($matches);

which will produce:
Array
(
    [0] => Array
        (
            [0] => Lorem
            [1] => ipsum
            [2] => "dolor sit amet"
            [3] => consectetur
            [4] => "adipiscing \"elit"
            [5] => dolor
        )

)

And as you can see, it also accounts for escaped quotes inside quoted strings.
EDIT
A short explanation:
"           # match the character '"'
(?:         # start non-capture group 1
  \\        #   match the character '\'
  .         #   match any character except line breaks
  |         #   OR
  [^\\"]    #   match any character except '\' and '"'
)*          # end non-capture group 1 and repeat it zero or more times
"           # match the character '"'
|           # OR
\S+         # match a non-whitespace character: [^\s] and repeat it one or more times

And in case of matching %22 instead of double quotes, you'd do:
preg_match_all('/%22(?:\\\\.|(?!%22).)*%22|\S+/', $text, $matches);

Comment: @prodigitalson: no, using `preg_split(...)` you cannot account for escaped characters. `preg_match_all(...)` "behaves" more like a parser which is the more natural thing to do here. Besides, using a `preg_split(...)`, you'll need to look ahead on each space to see how many quotes are ahead of it, making it an `O(n^2)` operation: no problem for small strings, but might decrease the runtime when larger strings are involved.
Comment: Is there a reason not to use `preg_split` instead of `preg_match_all`? it seems like a more natural fit IMO.
Comment: That's Awesome! I'll have to study the code for a bit to figure what just happened! thanks
Comment: @timofey, see my edit. Don't hesitate to ask for more clarification if it's not clear to you: you're the one maintaining the code, so you should understand it (and I'm more than happy to provide extra information if it's needed).
Comment: Thanks Bart K.!
I was already searching google for answers on that one:)
Comment: But then if I want to replace Lorem ipsum %22dolor sit amet%22 consectetur %22adipiscing elit%22 dolor (basically the quotation marks are listed as %22) the following doesn't seem to work:
preg_match_all('/%22(?:\\\\.|[^\\\\"])*%22|\S+/', $text, $matches);
Comment: That's beginning to make sense! Thanks
Comment: In single quoted php strings the '\' won't escape so you don't need \\\\ for one \.
Comment: Oh it's not true. \ and ' still should be escaped. sry
Comment: why is your solution doing this http://pastebin.com/bhrnMGST to this string - this has a \"quoted sentence\" inside
Comment: @Bart Kiers does your solution apply to my example?
Comment: @Bart Kiers Thanks! If I have single quotes?
Comment: @Bart Kiers Things have changed a little bit. Sorry about this. After using mysql_real_escape_string() I get this, - this has a \\\'quoted sentence\\\' inside. So I need to account for those extra slashes (i dont know if it makes a difference) and single or double quotes.
Comment: @Bart Kiers it wouldnt last 2 minutes. haha. Give me one more hit of regex and i'll be gone.
Comment: Preg split alternative: https://stackoverflow.com/a/32034603/2897386
Answer: This would have been much easier with str_getcsv().
$test = 'Lorem ipsum "dolor sit amet" consectetur "adipiscing elit" dolor';
var_dump(str_getcsv($test, ' '));

Gives you
array(6) {
  [0]=>
  string(5) "Lorem"
  [1]=>
  string(5) "ipsum"
  [2]=>
  string(14) "dolor sit amet"
  [3]=>
  string(11) "consectetur"
  [4]=>
  string(15) "adipiscing elit"
  [5]=>
  string(5) "dolor"
}

Comment: Be aware that it "ignores" the quotes. If you need them to be there in the split also then this wont work.
Comment: str_getcsv requires PHP 5.3.
Comment: This works on my development machine, but not on my production server. :-/
Comment: I've made some speed test and preg_match_all is about 3-5 times quicker. Probably not an issue for most people, specially if don't need the quotes (in this case it's much easier to use), but I think worth a mention.
Comment: @err care to share you tests?
Comment: Nothing special, just wrapped around both with a 1 to 10000 for cycle and checked microtimes before and after. Both fast enough for single use, even with the test quantity, hence I mentioned it probably won't be a problem to most of us.
Answer: You can also try this multiple explode function
function multiexplode ($delimiters,$string)
{

$ready = str_replace($delimiters, $delimiters[0], $string);
$launch = explode($delimiters[0], $ready);
return  $launch;
}

$text = "here is a sample: this text, and this will be exploded. this also | this one too :)";
$exploded = multiexplode(array(",",".","|",":"),$text);

print_r($exploded);

Comment: This answer is good, but if you ask it to split on spaces and quotes, it splits on spaces inside the quotes.
Answer: I came here with a complex string splitting problem similar to this, but none of the answers here did exactly what I wanted - so I wrote my own.
I am posting it here just in case it is helpful to someone else.
This is probably a very slow and inefficient way to do it - but it works for me.
function explode_adv($openers, $closers, $togglers, $delimiters, $str)
{
    $chars = str_split($str);
    $parts = [];
    $nextpart = "";
    $toggle_states = array_fill_keys($togglers, false); // true = now inside, false = now outside
    $depth = 0;
    foreach($chars as $char)
    {
        if(in_array($char, $openers))
            $depth++;
        elseif(in_array($char, $closers))
            $depth--;
        elseif(in_array($char, $togglers))
        {
            if($toggle_states[$char])
                $depth--; // we are inside a toggle block, leave it and decrease the depth
            else
                // we are outside a toggle block, enter it and increase the depth
                $depth++;

            // invert the toggle block state
            $toggle_states[$char] = !$toggle_states[$char];
        }
        else
            $nextpart .= $char;

        if($depth < 0) $depth = 0;

        if(in_array($char, $delimiters) &&
           $depth == 0 &&
           !in_array($char, $closers))
        {
            $parts[] = substr($nextpart, 0, -1);
            $nextpart = "";
        }
    }
    if(strlen($nextpart) > 0)
        $parts[] = $nextpart;

    return $parts;
}

Usage is as follows. explode_adv takes 5 arguments:

An array of characters that open a block - e.g. [, (, etc.
An array of characters that close a block - e.g. ], ), etc.
An array of characters that toggle a block - e.g. ", ', etc.
An array of characters that should cause a split into the next part.
The string to work on.

This method probably has flaws - edits are welcome.
Answer: In some situations the little known token_get_all() might prove useful:
$tokens = token_get_all("<?php $text ?>");
$separator = ' ';
$items = array();
$item = "";
$last = count($tokens) - 1;
foreach($tokens as $index => $token) {
    if($index != 0 && $index != $last) {
        if(count($token) == 3) {
            if($token[0] == T_CONSTANT_ENCAPSED_STRING) {
                $token = substr($token[1], 1, -1);
            } else {
                $token = $token[1];
            }
        }
        if($token == $separator) {
            $items[] = $item;
            $item = "";
        } else {
            $item .= $token;
        }
    }
}

Results:
Array
(
    [0] => Lorem
    [1] => ipsum
    [2] => dolor sit amet
    [3] => consectetur
    [4] => adipiscing elit
    [5] => dolor
)


Which VLANs need IGMP snooping?

Question: My approximate understanding is that switches and similar L2 devices employ IGMP snooping to prevent multicast "streams" from propagating out of ports that have no multicast clients downstream of them.
Questions:

It would seem that IGMP snooping is only required on VLANs where multicast streaming is occurring?
If so, what's the impact of leaving it enabled on VLANs where no multicast is occurring?

Some context (don't think this has much bearing on the questions):

I've recently implemented VLAN segregation in my network, with a dedicated VLAN for IPTV, which relies on multicast and IGMP.
I use OPNsense as a router and the os-igmp-proxy plugin to provide proxying between the IPTV VLAN and the WAN.
Switches are configured with IGMP snooping on all VLANs but - whilst everything works hunky-dory at present - I think it's only required on the IPTV VLAN.

Related: Should IGMP Snooping be configured on all Layer 2 switches on LAN?
Answer: Answer:

Yes, it's useful to limit the broadcast effects of multicast
None, provided there really is no multicast

Wrt. 2, there may be other limitations depending on the actual L2 device or operating system used.  E.g., some switches may block all unknown multicast traffic by default, when IGMP snooping is enabled, this may also affect MAC multicast (non-IP), which is prevalent in industrial networks, but may of course exist outside that domain as well.
So, as a recommendation I'd leave it enabled (usually the default) for all VLANs.  Similar to how I'd also recommend leaving RSTP/STP enabled on a bridge, it's a safety you want to prevent loops, or as in the case of multicast, unwanted multicast is like broadcast and may slow down your overall network performance.

Which VLANs need IGMP snooping?


Transition CSS3 not working in Angular2?

Question: I am trying to add fullscreen navigation area, i already made it, but the transition is not working, but another CSS code is working, what i missed here? is there something i need to add in somewhere when using angular2?
Here is my component folder looked like :

below is my css file, navbar.component.css :
body {
    margin: 0;
    font-family: 'Lato', sans-serif;
}

.overlay {
    height: 100%;
    width: 100%;
    position: fixed;
    z-index: 1;
    top: 0;
    left: 0;
    background-color: rgb(0,0,0);
    background-color: rgba(0,0,0, 0.9);
    overflow-x: hidden;
    transition: 0.5s;
}

.overlay-content {
    position: relative;
    top: 25%;
    width: 100%;
    text-align: center;
    margin-top: 30px;
}

.overlay a {
    padding: 8px;
    text-decoration: none;
    font-size: 36px;
    color: #818181;
    display: block;
    transition: 0.3s;
}

.overlay a:hover, .overlay a:focus {
    color: #f1f1f1;
}

.overlay .closebtn {
    position: absolute;
    top: 20px;
    right: 45px;
    font-size: 60px;
}

@media screen and (max-height: 450px) {
  .overlay a {font-size: 20px}
  .overlay .closebtn {
    font-size: 40px;
    top: 15px;
    right: 35px;
  }
}

below is my html file, navbar.component.html :

  ×

    About
    Services
    Clients
    Contact

Fullscreen Overlay Nav Example

Click on the element below to open the fullscreen overlay navigation menu.

In this example, the navigation menu will slide in, from left to right:

☰ open

below is my typescript file, navbar.component.ts :
import { Component } from '@angular/core';

@Component({
  moduleId: module.id,
  selector: 'app-navbar',
  templateUrl: 'navbar.component.html',
  styleUrls: ['navbar.component.css']
})
export class NavbarComponent {

  public displayNav: boolean = false;

  constructor() { }

  openNav(){
    this.displayNav = true;
    console.log(this.displayNav);

  }

  closeNav(){
    this.displayNav = false;
    console.log(this.displayNav);
  }
}

when i click on ☰ open it just show the div area with id="myNav" without transition, i already set the transition in class="overlay"
.overlay {
    height: 100%;
    width: 100%;
    position: fixed;
    z-index: 1;
    top: 0;
    left: 0;
    background-color: rgb(0,0,0);
    background-color: rgba(0,0,0, 0.9);
    overflow-x: hidden;
    transition: 0.5s;
}

but i try the transition in usual html with javascript n css, it work, what do i missed here?
Comment: can you add `!important` to your transition line and try.. i.e., `transition: 0.5s !important;`
Answer: The transition isn't working because *ngIf removes the element from the DOM. You can achieve the desired effect in a few ways. Add and remove an active class on click with NgClass or use angular 2's animations, particularly  transition(* <=> void, animation(...)).
I suggest the former because an element that should often disappear and reappear shouldn't use *ngIf.
If i got it right this is the only thing you need to change in your code:
HTML

CSS
.overlay {
  visibility: hidden;
  opacity: 0
  ...
}

.overlay.active {
  visibility: visible;
  opacity: 1
}

Comment: i already tried your code, it's not working, when i click the button, nothing happened, i change my  area just like you told and i add .overlay . active


Solving errors which i get with php and IIS

Question: I am using php 5.0 and IIS 5. When i am trying to access my application i get 2 erros like
PHP has encountered an Access Violation at 011173CD

and
HTTP/1.1 500 Server Error Server: Microsoft-IIS/5.1 Date: Thu, 15 Sep 2011 10:26:36 GMT Content-Type: text/html Content-Length: 44 -2147417842 (0x8001010e)

I have no idea why it is coming. Please let me know how to solve this problem.
Answer: Most of the time I find crashes like that in PHP due to version mismatches between IIS and PHP, or the same with extensions.
Ensure that the whole stack uses the correct version, architecture (32-bit vs. 64-bit), etc. and that they all match and are suggested to be used with one another. If using FastCGI, make sure it is patched and using the latest version. (That link is for IIS 7. Is there a reason you're using such an old version of IIS that you can't move to something not 10 years old? You're going to be plagued by problems if you don't upgrade that.)
If you're having startup problems or only problems when certain extensions are used, try disabling extensions to see if you can get it to launch without them to track down if one is causing a problem.
Try increase the logging levels by setting them lower, like to the Debug level perhaps.
If none of that works, you could try running Apache on Windows to see if that helps. Or just php.exe standalong to check if it is PHP-only vs. PHP + IIS problem.


Joining shapes together and tracing their outline

Question: EDIT: Found solution. I've added it after the question.
I'm designing a game for Android and I'm trying to come up with ways to reduce the calculations at the render stage.  I've got a method at the moment which takes all the metal and rubber blocks in the level and stores a texture id into a int[][] grid so that the renderer just reads that instead of calculating every blocks tiled textures every frame.
This works fine but now I'm trying to create a list of corner and straight pieces for the level edges and the laser blocks in the level. The level bounds and laser blocks are drawn using a set of straight laser textures and corner textures.  I'm not sure how best to tackle working out where not to render lasers where blocks overlap with other blocks and with the level edges. The pictures below shows what I mean:
drawing
ingame
Here you can see the level edge (the L shaped laser path extending beyond the pictures edges) and three/two internal laser blocks (respectively to picture order). As far as I can tell I should create a similar grid to above but with booleans so any square that kills the player on upon touching (highlighted in red) is true and the safe squares are false.
I then first thought of going through all the true (red) cells in the grid and work out what the laser outline would look like using their neighbouring grid cells but I realised this could very difficult so I'm certain now that I use the false squares to find it out. I'm sure I could get a rough solution working by starting at the lower left square of the level bounds and iterate through the grid until I find a false tile (unless the first square is false) and then travel through the grid going right until I reach a true cell to the right and so I would turn left and continue up through the grid until a true is found above to turn left OR a false is found on the right to turn right. I'd repeat this process until I reach my starting false cell.
I came up with this while writing this question out lol. It seems like the easiest way so I guess my question is is this a good way to do it and how would I work out the laser blocks which touch each other but not touch the level bounds as the above method would only trace the outer most laser path.
Thank you for taking the time to read through this. I hope I've explained it well enough and I look forward to any light that can be shed on this subject.
Answer: SOLUTION:
<code>    public static boolean[][] laserField = new boolean[(int) Static.WORLD_SIZE][(int)Static.WORLD_SIZE];
    public static List<LaserData> laserData = new ArrayList<LaserData>();
    public static void calcLaserBoundryAreas() {
        laserField = new boolean[(int) Level.levelBounds.bounds.width+5][(int) Level.levelBounds.bounds.height+5];
        for (int i=0;i<laserField.length;i++) {
            for (int j=0;j<laserField[i].length;j++) {
                if(i==0 || i==laserField.length-1 || j==0 || j==laserField[i].length-1)
                    laserField[i][j] = true;
                else
                    laserField[i][j] = false;
            }
        }
        for (LaserBlock lBlock : lBlocks) {
            int cols = (int)lBlock.bounds.width;
            int rows = (int)lBlock.bounds.height;
            float startX = lBlock.position.x - (cols-1f)/2f;
            float startY = lBlock.position.y - (rows-1f)/2f;
            for (int i=0;i<cols;i++) {
                for (int j=0;j<rows;j++) {
                    addLaserCell(startX+i, startY+j);
                }
            }
        }
        addLaserData();
    }

private static void addLaserCell(float x, float y) {
    int cellX = (int)(x- Level.levelBounds.bounds.lowerLeft.x+2);
    int cellY = (int)(y- Level.levelBounds.bounds.lowerLeft.y+2);
    if (cellX < 0 || cellX > laserField.length-1)           return;
    if (cellY < 0 || cellY > laserField[cellX].length-1)    return;
    laserField[cellX][cellY] = true;
}

private static void addLaserData() {
    laserData = new ArrayList<LaserData>();
    for (int i=1;i<laserField.length-1;i++) {
        for (int j=1;j<laserField[i].length-1;j++) {
            if (!laserField[i][j]) {
                checkNeighbours(i,j);
            }
        }
    }
    optimiseLaserData();
}

private static void checkNeighbours(int x, int y) {
    boolean u = laserField[x][y+1];
    boolean ul = laserField[x-1][y+1];
    boolean l = laserField[x-1][y];
    boolean bl = laserField[x-1][y-1];
    boolean b = laserField[x][y-1];
    boolean br = laserField[x+1][y-1];
    boolean r = laserField[x+1][y];
    boolean ur = laserField[x+1][y+1];

    /*
     *  TOP LEFT CORNER
     */
    float posX, posY;
    posX = Level.levelBounds.bounds.lowerLeft.x+x-2.5f;
    posY = Level.levelBounds.bounds.lowerLeft.y+y-1.5f;
    if(u && ul && l)
        laserData.add(new LaserData(posX, posY, true, 0, 0));
    else if(!u && ul && l)
        laserData.add(new LaserData(posX, posY, false, 1, 0));
    else if(!u && ul && !l)
        laserData.add(new LaserData(posX, posY, true, 0, 2));

    /*
     *  BOTTOM LEFT CORNER
     */
    posX = Level.levelBounds.bounds.lowerLeft.x+x-2.5f;
    posY = Level.levelBounds.bounds.lowerLeft.y+y-2.5f;
    if(l && bl && b)
        laserData.add(new LaserData(posX, posY, true, 0, 1));
    else if(!l && bl && b)
        laserData.add(new LaserData(posX, posY, false, 1, 1));
    else if(!l && bl && !b)
        laserData.add(new LaserData(posX, posY, true, 0, 3));

    /*
     *  BOTTOM RIGHT CORNER
     */
    posX = Level.levelBounds.bounds.lowerLeft.x+x-1.5f;
    posY = Level.levelBounds.bounds.lowerLeft.y+y-2.5f;
    if(b && br && r)
        laserData.add(new LaserData(posX, posY, true, 0, 2));
    else if(!b && br && r)
        laserData.add(new LaserData(posX, posY, false, 1, 2));
    else if(!b && br && !r)
        laserData.add(new LaserData(posX, posY, true, 0, 0));

    /*
     *  TOP RIGHT CORNER
     */
    posX = Level.levelBounds.bounds.lowerLeft.x+x-1.5f;
    posY = Level.levelBounds.bounds.lowerLeft.y+y-1.5f;
    if(r && ur && u)
        laserData.add(new LaserData(posX, posY, true, 0, 3));
    else if(!r && ur && u)
        laserData.add(new LaserData(posX, posY, false, 1, 3));
    else if(!r && ur && !u)
        laserData.add(new LaserData(posX, posY, true, 0, 1));

}

private static void optimiseLaserData() {
    List<LaserData> optiLaserData = new ArrayList<LaserData>();
    for(LaserData ld : laserData) {
        if(ld.cornerPiece)
            optiLaserData.add(ld);
        else if(ld.dir == 0 || ld.dir == 2){
            float x = ld.x;
            float bottomY = ld.y;
            float topY = ld.y;
            float count = 1;
            while (searchStraightLaserData(laserData, x, topY+1, ld.dir)) {
                count++;
                topY++;
            }
            while (searchStraightLaserData(laserData, x, bottomY-1, ld.dir)) {
                count++;
                bottomY--;
            }
            float centerY = bottomY + (topY-bottomY)/2;
            if(!searchStraightLaserData(optiLaserData, x, centerY, ld.dir))
                optiLaserData.add(new LaserData(x, centerY, false, count, ld.dir));
        } else {
            float y = ld.y;
            float leftX = ld.x;
            float rightX = ld.x;
            float count = 1;
            while (searchStraightLaserData(laserData, rightX+1, y, ld.dir)) {
                count++;
                rightX++;
            }
            while (searchStraightLaserData(laserData, leftX-1, y, ld.dir)) {
                count++;
                leftX--;
            }
            float centerX = leftX + (rightX-leftX)/2;
            if(!searchStraightLaserData(optiLaserData, centerX, y, ld.dir))
                optiLaserData.add(new LaserData(centerX, y, false, count, ld.dir));
        }
    }
    laserData = optiLaserData;
}

private static boolean searchStraightLaserData(List<LaserData> data, float x, float y, int dir) {
    for(LaserData ld : data)
        if(ld.x == x && ld.y == y && ld.dir == dir && !ld.cornerPiece)
            return true;
    return false;
}
</code>
These methods first create a boolean grid that is the size of the level edge bounds with a 1 square extra edge on each side. This is initialised to false to represent safe areas and the extra edge is set to true so that we have a kind of hollow box. The extra edge helps later by eliminating the need to check for incorrect indices on the laserField.
After the level extents are mapped to a grid individual cells are changed to true where ever is covered by a laser block.
Once the boolean grid is fully mapped it then iterates through each grid cell and when it finds a cell which is false it passes it grid coordinates to the next method which looks at 12 different neighbour patterns to determine if any lasers should be rendered around this cell. The LaserData constructor takes the following args (float x, float y, boolean cornerPiece, float length, int direction)
The last section does a brute force search to check if any adjacent straight pieces can be replaced by a single longer straight piece to save rendering extra sprites.
The renderer can then just read through the laserData list each frame and it has all the information it needs to render the correct texture, its position, length etc...
NOTE: The width and height of the Level bounds are 3 units smaller than the actual playing area to account for width of player outside the boundry. That's where the levelBounds.lowerleft+5, +2 and + 1.5f etc... come from. It's a little hacky I know but it's old code and I daren't touch it xD


Fill a HTML5 List with data from Android/Java Code

Question: i want to populate a List in an HTML5 File (displayed within a WebView) with data from Android Code (for exmaple from an ArrayList). Can anyone please tell me how or if this is possible.
Thanks in advance
Thommy
Answer: With a WebView you can simply:
webview.loadUrl("javascript:YOURJAVASCRIPTCODE");

Your javascript code could be something like:
document.getElementById('txtField1').value = "test";

Answer: Read this:
http://developer.android.com/guide/webapps/webview.html#BindingJavaScript
You can expose anything from your Android code. If you return some JSON (array or object), you can build your list (or anything else) using some javascript.


Data scraping a dynamic page and building a bell curve model

Question: There are a few layers to my question so please bear with me:

I'm trying to scrape data from a dynamic web page. This is the page

I'm attempting to scrape the number of traders that are long or short each currency pair. As shown in the below picture:

Now, I need the number of traders - not the percentages.

Here is what I have done:
<code># Load rvest package
library(rvest)

# Forex Factory

# EURUSD
# Read the url
eurusd <- read_html("http://www.forexfactory.com/#tradesPositions-sort=instruments&tradesPositions-sortOrder=asc&tradesPositions-details=0")

#Set up the nodes for EURUSD
#FF stands for 'Forex Factory'
FFeurusd<-eurusd%>%html_nodes(".label")%>%html_text()

#Scrape HTML page into a dataframe
shorteurusd_table<-data.frame(FFeurusd[1])
longeurusd_table<-data.frame(FFeurusd[2])

#This is where I attempt to merge the results from long and short traders and clean up the results (doesn't really work)
shorteurusd_table$FFeurusd.1.<-gsub("%","",shorteurusd_table$FFeurusd.1.)

#Adjust attributes of table
final<-merge(shorteurusd_table,longeurusd_table)
colnames(final) <-c("Short","Long")
rownames(final) <-c("EURUSD")
</code>

This is the output from the above code.
Problem: I only want the number in each column, i.e. 263 and 315.

I'm aware this is a highly inefficient way of setting up a data frame but I have limited experience in R.
I can't even get the other currency pairs to work because I can't get an accurate path. If I copy paste in the XPath, it never works.
I also want to be able to calculate the ratio between long and short - store that data, normalise the scores and model a distribution. So that one could compare the current ratio to historical data. Eventually I need to put the code on a server, scrape the info a few times a day so its automated. I understand that last task is considerable but that's the task I've set myself.
I'm confident with R when doing mathematical modeling and statistics - so Ill probably be okay once the data scraper is actually running and storing those data points. Sorry for text wall - it required detailed explanation.
Thanks
Comment: A bit of what @AammadUllah said: `data_list <- lapply(strsplit(FFeurusd, split = " "), as.numeric); sapply(data_list, FUN = function(x) x[!is.na(x)])`
Comment: just explode it on space and take the one you require.
Answer: Here is the start.
Please do the data cleaning and you will get plenty of help online.
<code>url<-"http://www.forexfactory.com/?flexId=flex_trades/positions_tradesPositionsCopy1&more=1"
pgsession<-html_session(url)
for(i in 1:10){
if(i == 1){
        table<-html_table(html_nodes(read_html(pgsession), xpath=paste0('//*[@id="flexBox_flex_trades/positions_tradesPositionsCopy1"]/div[',i,']/table')), fill= TRUE)[[1]]
}else{
        table<-rbind(t,html_table(html_nodes(read_html(pgsession), xpath=paste0('//*[@id="flexBox_flex_trades/positions_tradesPositionsCopy1"]/div[',i,']/table')), fill= TRUE)[[1]])
}
}
</code>
Comment: Would you recommend any documentation for me to learn how to do the data cleanup?


MySQL SUM all orders by distinct classification of order items

Question: I am sorry if my question is not very descriptive. Will update later when I get better idea.
I would like to create SQL that SUM's me order totals by classification of it's order items.
To make things simple I have made stripped down version of my schema which I have loaded here: http://sqlfiddle.com/#!9/8eb9a/1. My table structure:

orders: id, total
order_items: id, order_id, data

Each order item has a data field that classifies order item into certain category. Can be for example "Automotive", "DSA", ... or null. Now I would like to SUM(orders.total) by each of these classifiers. If order item fits into "Automotive" classifier I would like to add order's total into that classifier. If order has another item, for example "DSA" I would like to add order's total also into that classifier.
I tried running this SQL but this does not SUM right, because if order has more then one order item with the same classifier it add's multiple order's totals for that classifier (LEFT JOIN)...
select OI.data, SUM(O.total)
from order_items OI
left join orders O on O.id=OI.order_id
group by data

I would like to add order total only once for every order to the each of distinct order item classifiers.
You can see the example in this SQL Fiddle http://sqlfiddle.com/#!9/8eb9a/1
Comment: Could you post some sample data and the desired result?
Comment: Why do you need `LEFT JOIN`? Can an `order_item` refer to a nonexistent `order`?
Comment: @Barmar nope it cant... I have referred SQL fiddle with some data...
Comment: Then you should use `INNER JOIN`. But I don't think it makes a difference to your question.
Comment: sqlfiddle shows the data, it doesn't show the desired result.
Answer: You are looking to add distinct rows based on your description:
select OI.data, SUM(O.total)
from (SELECT DISTINCT order_id,data FROM order_items) OI
left join orders O on O.id=OI.order_id
group by data;


Github Sub-branches or Children of Branches?

Question: I am new to source control and am still touching up on all the features Github offers.
I have an app that works on mobile devices, and the entire project is on a repository with a single branch containing the entire project. I want to also support some other platforms (AR and VR), but I don't want any of the SDK's needed to run these in the mobile version as it would increase the file size of the app significantly.
Ideally, I would like to know the best way to use Github to take my main branch with the entire app for mobile, and create 2 sub-branches for AR and VR. These sub-branches would ideally be able to:

Receive any updates that the main (mobile) branch gets automatically. This way each branch has the same 'game' and the only differences are the platform-specific SDK's that are needed to build it to a specific platform.
Prevent updates to the main (mobile) branch in the case of an update to an SDK or other feature unrelated to the main branch.

I understand the concepts of pull/push/merge, but I wanted to know if there were any additional features that Github offers that make the process I want to do easier. I also want to ensure that if I push updates from the main branch to sub-branches, none of the platform specific SDK's are removed because they won't be present in the branch I am modifying.
Let me know if I am on the right track or if I missed something when researching Github's features. Thank you for your help.
Answer: The idea of a "sub-branch" does not really exist in Git. A branch must contain all of the files in a repo (unless you're deleting/creating them in that branch.) However, the problem you're trying to solve is a pretty common one -- the monorepo pattern seems like it would help here.
The idea is that you have a folder for each project within your repo, and you can also have a folder for any shared code. So in your case, you could have a folder for mobile, a folder for AR, a folder for VR, and a folder for the shared game code.
In this way, you can update the components separately while still keeping them in the same repo -- if the VR SDK needs an update, you can branch off of main, update the VR files that are strictly in the VR folder, and then merge that branch into main. This would leave the other folders untouched.
If this approach doesn't provide strict enough separation for your purposes, it would probably be a good idea to just create a separate repo for mobile, VR, AR, and the game code. Then, you can have the different implementations of the game git clone the game repo as part of their build process.
Generally speaking, the logic you're looking for of "if the game is updated, rebuild these sub-projects" is something you're going to need an automated pipeline for (or even just GitHub Actions), and git will just be the trigger for that pipeline. Git itself is not a build tool.
Comment: I had not heard of 'monorepo', but it seems like a better idea than my own. I will look into it more, thank you for the response!


How to validate multiple emails inside  using Javascript?

Question: I am trying to validate multiple email adresses but I can't seem to get it to work. I am new to Javascript and I searched the internet for solutions but to no avail.
I can print the email adresses but in the validation it always returns false what am I doing wrong?
The idea is that users can add email adresses to an  and a delete button when they want to remove an address. I am trying to validate the emails when a submit button gets pressed.
The if-statement doesn't work inside and outside the for loop
What I have:

function checkEmail() {
    // Get all nodes with querySelectorAll
        var elements = document.getElementById("ul-emaillist").getElementsByTagName("p");

    // Log values
        elements.forEach(element => console.log(element.innerText));

        for (let index = 0; index < elements.length; ++index) {
            const email = elements[index];
            validEmail(email);

        }

        if (!validEmail()){
            console.log("email klopt niet");
            return false;
        }else{
            return true;
        }
    }

    function validEmail(email) {
        var re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
        return re.test(email);
    };

firstname.lastname@example.com
<button class="delete">delete</button>

firstname.lastname@example.com
<button class="delete">delete</button>

       <button onclick="checkEmail()">Validate</button>

Comment: What about your if-statement isn't working? Does it throw an error?
Comment: it always returns false even when I am checking a correct email address
Answer: You need to set the output of validEmail(email) to a variable, and check that on the if(!validEmail()) line, like so:

function checkEmail() {
  // Get all nodes with querySelectorAll
  var elements = document.getElementById("ul-emaillist").getElementsByTagName("p");
  elements = [ ...elements ]

  // Log values
  // elements.forEach(element => console.log(element.innerText));
  let valid = false;
  let notvalid = false;

  for (let index = 0; index < elements.length; index++) {
    const email = elements[index].innerHTML;
    if (validEmail(email)) {
      valid = true;
    }

    if (!valid) {
      console.log("bad email: " + email);
      notvalid = true;
    } else {
      console.log("good email: " + email);
      valid = true;
    }
  }

  // use `valid` to check if ANY email is good
  // use `notvalid` to check if ALL email's are good
  if (valid) {
    return true;
  }
  return false;
}

function validEmail(email) {
  var re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
  return re.test(email);
};

email@example.com
<button class="delete">delete</button>

firstname.lastname@example.com
<button class="delete">delete</button>

<button onclick="checkEmail()">Validate</button>
Answer: // Validate if all emails in the list are valid
function checkEmails() {
  const elements = document.getElementById('ul-emaillist').getElementsByTagName('p');

  let isValidEmails = true;
  elements.forEach(element => {
    const email = element.innerText;
    // will result in false if at least one email is invalid
    isValidEmails = isValidEmails && validEmail(email);
  });

  return isValidEmails;
}

Answer: Use querySelectorAll to select all li elements, then you can loop through and retrieve the email text inside the p element. Like this:

function checkEmail() {
  const elements = document.querySelectorAll("li.delete");

  elements.forEach((element) => {
    const email = element.querySelector("p").textContent;
    if (isValidEmail(email)) {
      alert(`${email} VALID`)
    } else {
      alert(`${email} INVALID`)
    }
  })
}

function isValidEmail(email) {
  var re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
  return re.test(email);
};

email@example.com
<button class="delete">delete</button>

firstname.lastname@example.com
<button class="delete">delete</button>

testperson2.com
<button class="delete">delete</button>

<button onclick="checkEmail()">Validate</button>
Answer: Code was almost working, except you forgot to add an innerText in elements[index]

function checkEmail() {
    // Get all nodes with querySelectorAll
        var elements = document.getElementById("ul-emaillist").getElementsByTagName("p");

    // Log values

        for (let index = 0; index < elements.length; ++index) {
            const email = elements[index].innerText;
            validEmail(email);

        }

        if (!validEmail()){
            console.log("email klopt niet");
            return false;
        }else{
            return true;
        }
    }

    function validEmail(email) {
        var re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
        return re.test(email);
    };

email@example.com
<button class="delete">delete</button>

firstname.lastname@example.com
<button class="delete">delete</button>

<button onclick="checkEmail()">Validate</button>
Comment: This still does not work, see my answer.
Comment: And what is the difference between this and the change you done?
Comment: The `validEmail()` is run, but the output is not saved. He then just checks the existence of the function in his validation statement.
Comment: So the user wants to check all the mails at once and sent back if any of the email is wrong,, ok


Can I escape the `IO` in `catch`

Question: Here's a type-puzzle for you. So we have
catch
  :: Exception e
  => IO a
  -> (e -> IO a)
  -> IO a

Is it possible for me to safely escape IO in the handler. I'm interested in a function with a signature similar to the following:
catchM
  :: Exception e
  => MonadIO io
  => MonadError e io
  => IO a
  -> (e -> io a)
  -> io a

Is this sensible or am I looking at this wrong?
Some additional context: My problem is that I'm using a library that throws exceptions in IO. I've wrapped some of these functions and lifted them into my own monad (using liftIO). I want to be able to catch some of the functions that this library can throw in the places where I call the lifted version that I've provided. Also, when I catch the exceptions, I would like to re-throw them inside my own error-handling framework.
Comment: Did you consider using `catchError` instead?
Answer: -- Note that MonadError e io is unnecessary.
catchM :: (Exception e, MonadIO io) => IO a -> (e -> io a) -> io a
catchM m h = do
  r <- liftIO (try m)
  case r of
    Left e -> h e
    Right a -> pure a

Can I escape the `IO` in `catch`


Ruby Koans - Regex and .sub: Don't understand reason behind answer

Question: For clarification, here's the exact question in the about_regular_expressions.rb file that I'm having trouble with:
def test_sub_is_like_find_and_replace
    assert_equal __, "one two-three".sub(/(t\w*)/) { $1[0, 1] }
end

I know what the answer is to this, but I don't understand what's happening to get that answer. I'm pretty new to Ruby and to regex, and in particular I'm confused about the code between the braces and how that's coming into play.
Answer: The code inside the braces is a block that sub uses to replace the match:

In the block form [...] The value returned by the block will be substituted for the match on each call.

The block receives the match as an argument but the usual regex variables ($1, $2, ...) are also available.
In this specific case, the $1 inside the block is "two" and the array notation extracts the first character of $1 (which is "t" in this case). So, the block returns "t" and sub replaces the "two" in the original string with just "t".
Comment: @Dave: `sub` only does one match (unlike `gsub` which catches all matches). The regex matches a "t" followed by zero or more (`*`) word characters (`\w`, alphanumeric plus "_") and the parentheses put the match in group one (`$1`). The result is that the regex finds "two" and that ends up in `$1` inside the block.
Comment: So, for clarification in my head, /(t\w*)/ is creating an array of ["two", "three"], then the rest of the code is matching the first item in the array ("two") and extracting the "t". Yes?
Comment: Thank you much. That definitely clarifies for me what's going on.


How to play a video via drupal video ftp?

Question: I've installed the Video module (Drupal 6.2), and everything works fine. I also enabled the uploading of the video via FTP. I edited the video content type with the FTP CCK field.  The FTP field uploaded file is listed in the drop-down, and as I select it provides a file link to it. I need it to be displayed in a video player.
In other words, the video file is linked as an HTTP link, and it is not being played using the video player.
Do you have any suggestions?
Answer: You just need a player frontend for the CCK field in question to display the video. This is actually quite easy.
You'll first need a video player frontend of some sort. I would recommend the VideoJS module ,personally, but I'm sure there are others worth looking into as well.
On your video content type, go over to Display, and change the display widget of that cck field to a video player frontend of your choice after enabling the video module.
Answer: CCK fields offer a way to show his content. If you edit your content type, you will see a tab called 'Display fields'. In your CCK video field you will see dropdown menus to control how to show the video in Teaser and Full node modes. Then make test with the different display modes to your CCK field (I guess that, to this place, your module has included an option to show your video in a player video).
Also, sometimes the modules needs to locate the video player files in specific directories. so the video player will not call the video, if the player are misconfigured or not well located.


Como deixar o menu dropdown por cima de outros elementos?

Question:

html, body {
  height: 100%;
  width: 100%;
}

*{margin: 0; padding: 0;}

body{
font-family: arial, helvetica, sans-serif;
font-size: 12px;
background-image: img/fundosite.jpg;
}

.gif {
    text-align: center;
    padding: 5px;

}

body {
   background: url(img/fundosite.jpg) no-repeat center center fixed;
   -webkit-background-size: cover;
   -moz-background-size: cover;
   -o-background-size: cover;
   background-size: cover;

}

/*.efeito-vidro {
    background: rgba( 255, 255, 255, 0.35 );
    box-shadow: 0 8px 32px 0 rgba( 31, 38, 135, 0.37 );
    backdrop-filter: blur( 13.5px );
    -webkit-backdrop-filter: blur( 13.5px );
    border-radius: 10px;
    border: 5px solid rgba( 255, 255, 255, 0.18 );
  }

código html:

conteudo

*/

nav{
   display: flex;
   justify-content: center;
}

.menu ul li {
  background-color: #000000;
  float: left;
  width: 200px;
  height: 40px;
  display: inline-block;
  text-align: center;
  line-height: 40px;
  font-size: 20px;

}

.menu ul li:hover {
  background-color: #1916d4;
}

.menu ul {
  padding: 0%;
}

.menu ul ul{
  display: none;

  }

.menu ul li:hover > ul{
  display: block;
}

.menu a{
  color: white;
  text-decoration: none;

}

#site{
  /* Definimos a largura da página */
  width:1000px;
  /* Definirmos a altura da página*/
  height:700px;
  /* Aqui definiremos a posição que a página ocupará na tela, nesse caso estamos definindo que fique centralizado na tela*/
  /*top : posição de cima */
  margin-top:0;
  /* left: posição de esquerda*/
  margin-left:auto;
  /* bottom : posição de baixo */
  margin-bottom:0;
  /* right : posição de direita */
  margin-right:auto;
  /* Aqui definiremos a cor de fundo da página */
  background-color:
}

/*abaixo as linhas de codigo para edicao do footer*/
#footer{
  /* definindo a largura da div */
  width:100%;
  /* altura da div */
  height:40px;
  /* Cor de fundo da div */
  background-color:#000000;
  color: white;
  position: fixed;
  border-top: 1px solid #333;
  bottom: 0;
  left: 0;
  }

/*abaixo as linhas de codigo para posicionamento do buscador*/
.container {
  width: 50%; /* define a largura do campo */
  position: relative;  /* cria o contexto de posicionamento do botão */
}
label {
  display:block;
}

/* define a largura do campo igual a largura do container */
input {
  width: 100%;
}

input,  button {
  padding: 10px;

}

/* posiciona o botão em relação ao container, mas
  como o campo está exatamente contido no container
  o posicionamento se dá também em relação ao campo */
button {
  position: absolute;
  top: 0;
  right: 0;

}
<!DOCTYPE HTML>

  <meta charset="UTF-8">
  <title>Minha Mídia</title>
  <link rel="stylesheet" type="text/css"  href="homepage.css" />

Home

Downloads

Mídias

Músicas

Vídeos

Livros

Letras

Links

Instagram

Linkedin

Github

Contato

  <form action=" " method="post"></form>

    <input type="search" id="busca" placeholder="Busque músicas, letras ou o que quiser..." name="q">
    <button type="submit">OK</button>

  rodapé

Eu estou com uma dúvida que é: Como fazer com que o menu dropdown fique por cima de outros elementos da página. Por enquanto, quando posiciono o mouse em cima para que o menu "desça", ele fica por baixo de um buscador que eu coloquei na página.
Answer: Você só precisa adicionar a propriedade "z-index: 1" na sua ul
//inline

...

//linkado

...

//css
.nav { z-index: 1;}

A propriedade z-index define a prioridade sobre os elementos, imagine uma pilha de livros contendo 10 livros, o que estiver embaixo terá uma prioridade 0 (zero), e o que estiver em cima terá a prioridade 10 (dez), quanto maior a prioridade mais em cima ele ficará.
Obs: Você pode colocar valores negativos também para a z-index, ex.:  z-index: -1;
Comment: Meu amigo muito obrigado. Fiz como você me disse e deu muito certo!!!