text:
Q: API to detect if code completion popup is active? I'm only in my first hour of using VS Code, trying to get the environment just right, in this case, being able to tab out of quotes and brackets. I found this extention, but it breaks the native 'tab-to-complete' code completion. I set out to fix the extension, thinking there must be a way to tell if the code completion popup is active in the editor and defer the first tab to it - but I have been unable to glean any useful information from the VS Code API.
My coding skills are hobbyist at best, so I'm hoping a simple 'if' statement somewhere will fix it, but any information will help.


text:
Q: find total integer solutions for $(x-2)(x-10)=3^y$ I found this questions from past year maths competition in my country, I've tried any possible way to find it, but it is just way too hard.

How many integer solutions ($x$, $y$) are there of the equation $(x-2)(x-10)=3^y$?
(A)1 (B)2 (C)3 (D)4 (E)5

If let $y=0$, we had
$$x^2 - 12x + 20 = 1$$
$$x^2 - 12x + 19 = 0$$
no integer solution for x
let $y=1$, we had $x^2 - 12x + 17 = 0$, no integer solution too.
let $y=2$, we had $x^2 - 12x + 11 = 0$, we had $x = 1, 11$.
let $y=3$, we had $x^2 - 12x - 7 = 0$, no integer solution.
let $y=4$, we had $x^2 - 12x - 61 = 0$, no integer solution.
and going on....
is there any other efficient way to find it? "brute-forcing" it will wasting a lot of time.

A: Since their product is a power of $3$, both $x-2$ and $x-10$ must be powers of $3$, perhaps with minus signs (as Andre Nicolas pointed out). Note, however, that $x-2$ and $x-10$ cannot simultaneously be divisible by $3$. The only power of $3$ which is not divisible by $3$ is $1$, hence we must have that $x-2 = \pm 1$ or $x-10 = \pm 1$.
With this in mind, there are four values of $x$ to try: $1, 3, 9,$ and $11$. Two of these give you integer solutions to the equation.

A: By the Fundamental Theorem of Arithmetic, $x-2$ and $x-10$ must be powers of $3$, so we may write $$x-2= \pm 3^a $$ and $$x-10 = \pm 3^b.$$ Substracting the latter from the former we get $$8=\pm 3^a\mp3^b \\ 2^3 =3^a(\mp3^{b-a}\pm1)= 3^b (\pm3^{a-b} \mp1),$$ whence, again by FTA, $(a,b)= (0,2),( 2,0)$ and thus $(x,y)= (1,2),(11,2)$ are the only pairs of integer solutions.

A: Just as  Bob1123 commented, compute the discriminant for the equation $$x^2-12 x+(20-3^y)=0$$ and the roots $$x_{1,2}=6\pm\sqrt{3^y+16}$$ So $(3^y+16)$ must be a perfect square.
I only see one which is possible what you already found ($y=2$).
Now, to prove that this is the unique solution is beyond my skills. Fortunately, you have Alex G.'s nice answer.

redpajama_set_name: RedPajamaStackExchange


text:
Q: PdfPCell text horizontal alignment center - iText5 Java I am trying to generate report using iText Java. I could not able to align my text content into center it always aligned into left. My code sample is,
PdfPTable report= new PdfPTable(1);
PdfPCell pdfCell = new PdfPCell();
pdfCell.addElement(new Paragraph("key"));
pdfCell.setHorizontalAlignment(Element.ALIGN_CENTER);
report.addCell(pdfCell);

Also tried with chunk, this also returned left alignment.
PdfPTable report= new PdfPTable(1);
PdfPCell pdfCell = new PdfPCell();

Chunk contentChunk = new Chunk("key");
Paragraph para = new Paragraph(contentChunk);
pdfCell.addElement(para );

pdfCell.setHorizontalAlignment(Element.ALIGN_CENTER);
report.addCell(pdfCell);

Can you help on this?

A: You can go with following approach:
PdfPCell pdfPCell = new PdfPCell();
pdfPCell.setPhrase(new Phrase(title);
pdfPCell.setBackgroundColor(BaseColor.LIGHT_GRAY);
pdfPCell.setHorizontalAlignment(1);
pdfPCell.setVerticalAlignment(1);
table.addCell(pdfPCell);


text:
Q: Any good tools to automate js script combining? I use visual studio 2010 for writing javascript and jquery. Are there any fast and easy ways to automate script combining? It doesn't have to be tied to Visual studio, any method that is simple and easy to setup will do.
THanks

A: SquishIt
The Friendly ASP.NET JavaScript and CSS Squisher

A: Try require.js. The nicest feature is that you can combine your dependency scripts at any point in your project lifecycle without any modifications required to your includes.

A: Give chirpy a try, lot's of nice visual studio integration.  It will minify, uglify and mash them.  It also handle css, less and coffeescript.  Hopefully sass will be supported sometime soon ;-)


text:
Q: Struts2 - getting 404 Resource Unavailable error from request page I'm trying to write a login example that takes the user to a success.jsp if username equals password and an error message if it doesn't. The error message works but success (username=password) results in a 404 (HTTP Status 404 - /Struts2Ch4/success.jsp)
I experienced a similar problem in a previous post. I had not declared the RESULT parameter in the class. I was advised to use annotations in the class file and this solved the problem. In this case both the success and result parameters seem to be declared by the class so I'm not sure why I'm getting 404.
alias.jsp
<%@ page language="java" pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="s" uri="/struts-tags" %>

    <title><s:text name="app.title"/></title>
    <link rel="stylesheet" href="mystyle.css" type="text/css" />

<s:actionerror/>

Enter Login ID and Password

    <s:form action="aliasing" method="post">
    <s:textfield name="uname" key="app.loginid"/>
    <s:password name="pwd" key="app.password"/>
    <s:submit value="Enter"/>
    </s:form>

B a c k

struts.xml
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">

   <struts>
 <package name="default" extends="struts-default">
 <global-exception-mappings>
    <exception-mapping exception="java.lang.Exception" result="exception"/>
 </global-exception-mappings>

 <action name="aliasing" class="com.manaar.action.AliasAction">
    <param name="aliases">#{ 'uname' : 'loginid','pwd' : 'password' }</param>
    <interceptor-ref name="alias"/>
    <interceptor-ref name="basicStack"/>
    <result name="success">/success.jsp</result>
    <result name="error">/alias.jsp</result>
    <result name="input">/alias.jsp</result>
</action>

</package>

</struts>

AliasAction.java
package com.manaar.action;
import com.opensymphony.xwork2.ActionSupport;
public class AliasAction extends ActionSupport {
private String loginid;
private String password;

public String getLoginid() {
    return loginid;
}
public void setLoginid(String loginid) {
    this.loginid = loginid;
}
public String getPassword() {
    return password;
}
public void setPassword(String password) {
    this.password = password;
}

public String execute() throws Exception {
    System.out.println("Login Id: "+getLoginid());
    System.out.println("Password: "+getPassword());
    if(loginid.equals(password))
        return SUCCESS;
    else{
        this.addActionError(getText("app.invalid"));
        return ERROR;
    }
}
}

success.jsp
 <%@ page language="java" pageEncoding="ISO-8859-1"%>
 <%@ taglib prefix="s" uri="/struts-tags" %>
 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

 <title><s:text name="app.title"/></title>
 <link rel="stylesheet" href="mystyle.css" type="text/css" />

<s:text name="app.success"/>

 The action has returned SUCCESS as result code.

 Back to Index

web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee"xmlns:xsi="http://www.w3.org    /2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com    /xml/ns/javaee  http://java.sun.com/xml/ns/javaee    /web-app_3_0.xsd">
<filter>
    <filter-name>struts2</filter-name>
    <filter-class>org.apache.struts2.dispatcher.FilterDispatcher</filter-class>
</filter>
<filter-mapping>
    <filter-name>struts2</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>
<session-config>
    <session-timeout>
        30
    </session-timeout>
</session-config>
<welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>

index.jsp
<%@ page language="java" pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="s" uri="/struts-tags" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"/>

<title><s:text name="app.title"/></title>
<link rel="stylesheet" href="mystyle.css" type="text/css" />

Sruts 2 Interceptors

<s:a href="alias.jsp">Interceptor Example 1</s:a>

alias, basicStack

<s:a href="model.jsp">Interceptor Example 2</s:a>

exception, prepare, debugging, model-driven, params, conversionError, workflow

<s:a href="servletAction.action">Interceptor Example 3</s:a>

servlet-config, scoped-model-driven

<s:a href="longAction.action">Interceptor Example 4</s:a>

completeStack, execAndWait

<s:a href="login.jsp">Interceptor Example 5</s:a>

basicStack, validation, workflow, scope


text:
Q: Windows Service - ERROR [IM002] [Microsoft][ODBC Driver Manager] Nome da fonte de dados não encontrado e nenhum driver padrão especificado Eu tenho 2 projetos (WebForms e Windows Services) em .NetFramework 4 que se conecta a base Oracle através do ObdcConnection.
No projeto Web eu consigo abrir a conexão com sucesso...
Porém no Windows Services é lançado o seguinte erro:
ERROR [IM002] [Microsoft][ODBC Driver Manager] Nome da fonte de dados não encontrado e nenhum driver padrão especificado
Em Inglês: ERROR [IM002] [Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified.
Nos dois projetos eu estou usando o seguinte método:
public void testConnectionObdc(string connectionString)
{
   OdbcConnection conn = new OdbcConnection(connectionString);
   conn.Open();
}

A: Tente mudar as permissões que seu Windows Service executa, pelo jeito parece que que o serviço não tem permissão para acessar as fontes de dados ODBC, você pode fazer isso através do gerenciador de serviço do Windows (pressione WinKey + R, digite services.msc e pressione enter). Na lista de serviços, procure o seu serviço, clique com o botão direito, na segunda aba (Log On), defina uma outra conta para executar este serviço preferencialmente com permissões administrativas para ter certeza que o problema será resolvido caso seja permissão. Após isso, basta reiniciar o serviço.


text:
Q: NameError: name 'BeautifulSoup' is not defined when I try to use a parser I have a problem with my code when I want to use BeautifulSoup:

import requests
from bs4 import BeautifulSoup as bs
import webbrowser
import datetime
import time

for i in range(len(link_website)):
    page = requests.get(link_website[i])
    parser = BeautifulSoup(page.content,'html.parser')
    shoes_name[i] = (parser.find(class_="title")).h1.text

Here's what I get as error :
parser = BeautifulSoup(page.content,'html.parser')
NameError: name 'BeautifulSoup' is not defined

How do I solve this? Thanks

A: You need to import package
import requests
from bs4 import BeautifulSoup as soup
shoes_name={}
for i in range(len(link_website)):
    page = requests.get(link_website[i])
    parser = soup(page.content,'html.parser')
    shoes_name[i] = (parser.find(class_="title")).h1.text


text:
Q: Switching DC-DC Buck converter voltage feedback When using 2 PSs for redundancy purposes we connect positive outputs through diodes, as I understand. Is it possible to connect voltage feedback network of the buck converter to diodes cathode, to let the IC compensate diodes voltage drop?

A: If you need a switch without voltage drop, you need to use ICs that implement so-called "ideal diodes", look at "intelliMAX" line of switches from Fairchild/ONsemi, like FPF1320. See a bit longer answer here.


text:
Q: problem with firebase in node.js and gulp after i included my credentials to for firebase in the app.js file i get this error when i enter gulp watch.
can someone help me out ? not sure how to fiks it
example:
var admin = require('firebase-admin');

var serviceAccount = require('path/to/serviceAccountKey.json');

admin.initializeApp({
  credential: admin.credential.cert(serviceAccount),
  databaseURL: 'https://<DATABASE_NAME>.firebaseio.com'
});

I have change all off they above data with whats in my firebase project
this is the error i get
ERROR in ./node_modules/request/node_modules/tunnel-agent/index.js
Module not found: Error: Can't resolve 'tls' in 'node_modules/request/node_modules/tunnel-agent'
 @ ./node_modules/request/node_modules/tunnel-agent/index.js 4:10-24
 @ ./node_modules/request/lib/tunnel.js
 @ ./node_modules/request/request.js
 @ ./node_modules/request/index.js
 @ ./node_modules/@google-cloud/storage/src/bucket.js
 @ ./node_modules/@google-cloud/storage/src/index.js
 @ ./node_modules/firebase-admin/lib/storage/storage.js
 @ ./node_modules/firebase-admin/lib/firebase-namespace.js
 @ ./node_modules/firebase-admin/lib/default-namespace.js
 @ ./node_modules/firebase-admin/lib/index.js
 @ ./app/src/assets/js/app.js
 @ multi ./app/src/assets/js/app.js

package.json file:
{
  "name": "paper-panel",
  "version": "1.0.9",
  "slug": "paper-panel",
  "description": "A Multipuprpose Bootstrap4 HTML Admin Panel Template",
  "main": "app/dist/index.html",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "Nomi <naumanahmed19@gmail.com> (http//xvelopers.com)",
  "license": "ISC",
  "devDependencies": {
    "browser-sync": "^2.24.7",
    "del": "^3.0.0",
    "flush-cache": "^1.0.1",
    "friendly-errors-webpack-plugin": "^1.7.0",
    "fs-extra": "^4.0.1",
    "gulp": "^4.0.0",
    "gulp-cached": "^1.1.1",
    "gulp-changed": "^3.1.0",
    "gulp-clean-css": "^3.4.2",
    "gulp-concat": "^2.6.1",
    "gulp-gm": "0.0.9",
    "gulp-htmlclean": "^2.7.14",
    "gulp-imagemin": "^4.1.0",
    "gulp-inject-partials": "0.0.3",
    "gulp-minify-inline": "^1.0.0",
    "gulp-notify": "^3.2.0",
    "gulp-plumber": "^1.2.0",
    "gulp-sass": "^4.0.1",
    "gulp-sourcemaps": "^2.4.1",
    "gulp-uglify": "^1.5.4",
    "gulp-uglifycss": "^1.1.0",
    "gulp-util": "^3.0.8",
    "gulp-zip": "^4.0.0",
    "vinyl-ftp": "^0.6.0",
    "vinyl-named": "^1.1.0",
    "webpack-stream": "^4.0.3"
  },
  "dependencies": {
    "bootstrap": "^4.1.1",
    "bootstrap-colorpicker": "^2.5.2",
    "bootstrap-tagsinput": "^0.7.1",
    "chart.js": "^2.5.0",
    "datatables.net": "^1.10.19",
    "datatables.net-bs4": "^1.10.19",
    "dropzone": "^5.4.0",
    "easy-pie-chart": "github:rendro/easy-pie-chart",
    "echarts": "^4.0.4",
    "firebase-admin": "^6.0.0",
    "flot-charts": "^0.8.3",
    "fullcalendar": "^3.9.0",
    "gmaps": "^0.4.24",
    "google-maps": "^3.2.1",
    "gulp-shell": "^0.6.5",
    "inputmask": "^3.3.11",
    "ion-rangeslider": "^2.2.0",
    "isotope-layout": "^3.0.3",
    "jquery": "^3.1.1",
    "jquery-countdown": "^2.2.0",
    "jquery-datetimepicker": "^2.5.20",
    "jquery-knob": "github:aterrien/jQuery-Knob",
    "jquery-sparkline": "^2.4.0",
    "jquery-tabledit": "^1.0.0",
    "jquery-ui-dist": "^1.12.1",
    "jquery-validation": "^1.18.0",
    "jquery.easing": "^1.4.1",
    "jqvmap": "^1.5.1",
    "lightslider": "^1.1.6",
    "load-google-maps-api": "0.0.2",
    "masonry-layout": "^4.2.0",
    "morris-js-module": "^1.2.1",
    "nprogress": "^0.2.0",
    "pipe-error-stop": "0.0.11",
    "popper.js": "^1.12.5",
    "raphael": "^2.2.7",
    "scrollreveal": "^3.3.6",
    "select2": "^4.0.3",
    "smartwizard": "^4.3.1",
    "sweetalert": "^2.1.0",
    "toastr": "^2.1.4",
    "trumbowyg": "^2.11.0"
  },
  "optionalDependencies": {},
  "keywords": []
}

i forgot to post this so i added this later sorry for that.
maby this way someone can help me with it.


text:
Q: How filter out content from html element with the same name HTML Code:

   Position
   City & Province
   Country
   Salary

...

...

content1

...

...

content2

I am trying to filter an array of 'tr' elements and only access the content that falls under the 'tr' element that has a 'valign' attribute, I want all the other  elements to be ignored.
Puppeteer code:
const options = await page.$$eval('table tbody tr', (trArray) =>
  trArray.map((tr) => tr.valign)
);

//current results = ,,,,,,,,,,,,,,
//expected results = content1,content2

Any help would be greatly appreciated.

A: You can get only needed tr by selector 'table tbody tr[valign]'. To get the content, try tr.innerText:
const options = await page.$$eval('table tbody tr[valign]', (trArray) =>
  trArray.map((tr) => tr.innerText)
);


text:
Q: Filtering items in a Listview I am trying to filter items in a ListView by using a TextBox.
I've managed to make something, but it can only delete items from my listview, not bring them back. Here is a little example of my code:
private void textBox1_TextChanged(object sender, EventArgs e)
{
    string value = textBox1.Text.ToLower();
    for (int i = listView1.Items.Count - 1; -1 < i; i--)
    {
        if
        (listView1.Items[i].Text.ToLower().StartsWith(value) == false)
        {
            listView1.Items[i].Remove();
        }
    }
}

Does anybody has an idea on how to retrieve the deleted items? I can't seem to figure it out >:...

A: You can change your logic and first search the items to delete, them delete they.
IList<Object> itemsToDelete = new List<Object>( listView1.find(delegate(string text){
     return !text.ToLower().StartsWith(value);
}));

listView1.Remove(itemsToDelete);
return itemsToDelete;

But you have to return another list. When you delete the items form the original list, you cant recovery It. You have to store it in another list.

A: check below sample app
using System;
using System.Windows.Forms;
using System.Collections.Generic;
using System.Linq;
public partial class Form1 : Form
{
    // keep list of listview items
    List<Data> Items = new List<Data>();

    public Form1()
    {
        InitializeComponent();
        // get initial data
        Items = new List<Data>(){
            new Data(){ Id =1, Name ="A"},
            new Data(){ Id =2, Name ="B"},
            new Data(){ Id =3, Name ="C"}
        };

        // adding initial data
        listView1.Items.AddRange(Items.Select(c => new ListViewItem(c.Name)).ToArray());
    }

    private void textBox1_TextChanged(object sender, EventArgs e)
    {
        listView1.Items.Clear(); // clear list items before adding
        // filter the items match with search key and add result to list view
        listView1.Items.AddRange(Items.Where(i=>string.IsNullOrEmpty(textBox1.Text)||i.Name.StartsWith(textBox1.Text))
            .Select(c => new ListViewItem(c.Name)).ToArray());
    }

}

class Data
{
    public int Id { get; set; }
    public string Name { get; set; }
}

A: listBox1.Items.AddRange(listBox1.Items.Cast<String>    ().Where(X=>X.StartsWith(textBox1.Text)).ToArray());

Link
Works the same way with ListView.
Hope it helps

A: After trying to find a solution and giving up on searching I created this simple method and it worked for me.
    public static void FilterList(ListView list, string text)
    {
        if (text.Length > 0)
        {
            foreach (ListViewItem item in list.Items)
            {
                if (!item.ToString().ToLower().Contains(text.ToLower()))
                {
                    list.Items.Remove(item);
                }
            }
        }
        else
        {
            UpdateList(list);
        }
    }


text:
Q: Create list of dates given list of date ranges in Excel In Excel, I have a column of start dates and a corresponding column of end dates like so:
Start Date        End Date
6/26/06           7/2/06
7/1/06            7/8/06
8/17/06           8/21/06
8/17/06           8/20/06
9/3/06            9/9/06
9/6/06            9/8/06

How do I get a new column with all dates within these start/end date ranges, inclusive of start date and end date?  So I'd want a new column that looks like this:
New Column
6/27/06
6/28/06
6/29/06
6/30/06
7/1/06
7/2/06
7/1/06
7/2/06
7/3/06
7/4/06
7/5/06
7/6/06
7/7/06
7/8/06
8/17/06
8/18/06
8/19/06
8/20/06
8/21/06
8/17/06
8/18/06
8/19/06
8/20/06
9/3/06
9/4/06
9/5/06
9/6/06
9/7/06
9/8/06
9/9/06
9/6/06
9/7/06
9/8/06

I have tried the tutorial here: https://www.extendoffice.com/documents/excel/2659-excel-list-all-dates-between-two-dates.html, but I'm not sure how to replicate it with more than 1 row of Start Date/End Dates.

A: Let's assume that you have your data starting in column A1, with the word Start in A1 and 9/8/2006 in B7.
Further assume that you want your output in Column D.  Make A helper column, called Index in column E.
Put =A2 into Cell D2.  Put 1 in Cell E2.
In Cell D3 put:
=IF(E2=0,"",IF(E2=E3,D2+1,OFFSET($A$1,E3,0)))

In Cell E3 put:
=IF(D2=OFFSET($A$1,E2,1), IF(OFFSET($A$1,E2+1,0) = 0, 0,E2+1), E2)

Then just copy D3 and E3 down.  Once you have reached the last row, column E will show 0 and column D will be blank.


text:
Q: Two glassfish applications deployed with one war file, operating on different databases I have a Netbeans project, from which I build a .war file. I now deploy two instances of that war file on my glassfish server, each with a different context root, e.g. mydomain.com/abc and mydomain.com/def
This works fine but they are still operating on the same database, since I declare the persistence unit in the persistence.xml and the glassfish-resources.xml.
My glassfish-resources.xml file:
...
<jdbc-resource  enabled="true"
                jndi-name="jdbc/abc"
                object-type="user"
                pool-name="abcPool">
    <description/>
</jdbc-resource>

<jdbc-connection-pool
    ...
    name="abcPool"
    ...
    <property name="URL" value="jdbc:mysql://localhost:3306/abc"/>
    ...
</jdbc-connection-pool>

My persistence.xml file:
...
<persistence-unit name="abcPU" transaction-type="JTA">
    <jta-data-source>jdbc/abc</jta-data-source>
    ...
</persistence-unit>
...

Does anybody have a solution on how to have two instances of one war file, operating on two different databases?
Is there maybe a way to upload a different glassfish-resources.xml and persistence.xml to each application, overwriting the packaged one?
It would be acceptable to change the module descriptors in the glassfish domain admin console once the application is deployed, if that is possible.
If screenshots from the glassfish domain admin console are needed, please write in the comments, I will add them.
Thank you in advance!

A: At server level setup two Data sources pointing to different databases and go to the application instance and modify  Resource reference pointing specific data source.

A: Easiest approach in my opinion would be to have two different builds.
Basically you may create two different .war files. Each one with a different persistence.xml file in it. One pointing to the JDBC resource ABC and the other one pointing to the JDBS resource DEF.
Build tools like gradle+Jenkins may support you with this.
You will find lots of information about similar tasks, if you search for how to create builds with a different configuration for testing vs. productive system. This is a very common task.
Here might be a starting point for what you are looking for:
Create multiple .WAR files with different dependencies in Gradle


text:
Q: Performance for delete query in sql I have a table with 200,000 records. I want delete some data like below :
DELETE FROM Table Where IdColumn IN ( SelectedID )

SelectedID fill with my desirable data identities that contains 5000 records. there are 2 approach:
1- I insert 20,000 identity as SelectedID that contains identities of desired 5000 records.
2- I insert only identities of that 5000 records.
question is that what is the difference between two approach? (performance)

A: The performance of a large IN clause is horrible, this is mainly due to query compile time.  So if you have say a List<int> containing the IDs then this:
List<int> myIDs = GetIDs(); //20,000
var inList = myIDs.Distinct(); //5,000 distinct IDs
//pass inList to SQL

would be much faster than:
List<int> inList = GetIDS(); //20,000
//pass inList to SQL

If joining is an alternative, if you can get the list of IDs you want to delete by querying, it's better to do a subquery with that, something like this, using a query in the Where:
DELETE FROM Table
Where IdColumn IN (Select ID
                   From OtherTable
                   Where Name Like '%DeleteMe%')

I'm not sure if your list comes from an external source and can't be determined like this...but if it can, your delete will be extremely faster.

A: I'm not really sure, if I understand you completely, but I would go for #2 as it seems to be a waste of resources to generate 20.000 rows of which you only need 5.000 instead of inserting only the needed 5.000.
Also, 200.000 rows is a small table. Really!


text:
Q: Symfony2 is not displaying the error when using createNotFoundException() I am using Symfony2 and it is not displaying an error when createNotFoundException() is called.
It is just showing a blank white page.
Here is my code that is throwing an exception:
if(!$product){
     throw $this->createNotFoundException('The product does not exist');
}

The header of my class uses the following:
 <?php

 namespace WIC\ProductBundle\Controller;
 use WIC\SecurityBundle\Controller\AuthorizationController;
 use WIC\ProductBundle\Entity\Product;

 use Doctrine\Tests\Common\Annotations\Null;
 use Symfony\Component\HttpFoundation\Request;
 use Symfony\Bundle\FrameworkBundle\Controller\Controller;
 use Symfony\Component\Validator\Constraints as Assert;
 use Doctrine\ORM\Tools\Pagination\Paginator;

 use Symfony\Component\Security\Acl\Domain\ObjectIdentity;
 use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
 use Symfony\Component\Security\Core\Exception\AccessDeniedException;
 use Symfony\Component\HttpFoundation\JsonResponse;
 use Symfony\Component\HttpFoundation\Response;
 use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
 use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
 use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;

 class ProductController extends AuthorizationController
 {
     /**
      * @Route("/foo/", name="foo_bar")
      * @Template()
      */
     public function fooAction(Request $request)
     {
         $record = $em->getRepository('WICProductBundle:Product')->find(100000);
         if(!$record){
             throw new NotFoundHttpException("Test, This Is Not Valid");
         }
     }
 }

Now I am getting this error as well:

ClassNotFoundException: Attempted to load class "createNotFoundException" from namespace "WIC\ProductBundle\Controller" in /Applications/MAMP/htdocs/ffss/src/WIC/ProductBundle/Controller/ProductController.php line 43. Do you need to "use" it from another namespace?
[03-Oct-2014 04:11:32 Europe/Paris] PHP Fatal error:  Class 'WIC\ProductBundle\Controller\createNotFoundException' not found in /Applications/MAMP/htdocs/ffss/src/WIC/ProductBundle/Controller/ProductController.php on line 43
  [03-Oct-2014 04:12:50 Europe/Paris] PHP Fatal error:  Class 'WIC\ProductBundle\Controller\createNotFoundException' not found in /Applications/MAMP/htdocs/ffss/src/WIC/ProductBundle/Controller/ProductController.php on line 43

I switched out that namespace to this and everything works fine as far as that php log error goes, still not able to pull the symfony error page.
 use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;

All other errors are showing btw, just any exception error is not showing. Thanks for your help!

A: For your new error, instead of
throw new createNotFoundException("Test, This Is Not Valid");

you should use
throw new NotFoundHttpException("Test, This Is Not Valid");

I'm still not getting enough context for your original problem though.

A: When php fatal error occurs it does not create any event for symfony to handle. In order to make php fatal error on your page you need to enable debugging which enables symfony ro register a shutdown function. Which version of symfony you are using? if you are using symfony version above 2.2 to enable debug simply putting $kernel = new AppKernel('dev', true); is not enough. Put the below line above it to properly display any php errors (most possible reason of blank page) too. \Symfony\Component\Debug\Debug::enable(1);
 Hope this helps

A: Encountered a similar problem when trying out the tutorial from the Symfony website (http://symfony.com/doc/current/book/controller.html#managing-errors-and-404-pages).
But then i noticed i forgot to extend my class with Controller
class HelloController extends Controller

after which i was able to display the custom 404 error.


text: Q: How to break pinia store into individual files? I am using pinia to manage state into my Vue3 app. There has been thorough discussion here to break pinia store into individual files like state, getters, actions. But I am looking for a more 'stable' and 'elegant' solution to break the pinia store into individual files.


text:
Q: Sum of Square decomposition Question about the Total, Explained, and Residual Sum of Squares. I am in the simple linear regression model.
Could you help me clarify why the residual sum of squares (SSE where E stands for errors)
$$SSE = \sum_{i=1}^n (\hat{Y}_{i}-Y_{i})^{2} $$
is the amount in variance of Y which is not explained by the model and why the explained sum of squares (SSR where R stands for regression)
$$SSR = \sum_{i=1}^n (\hat{Y}_{i}-\bar{Y})^{2} $$
is the amount in variance of Y which is explained by the model, where $Y_{i}$ are the observations, $\bar{y}$ is the esperance and $\hat{Y}_{i}$ are the predicted values in the model.

A: If you take a normal regression model,
$$Y_i|X_i\sim\mathcal{N}(X_i^\text{T}\beta,\sigma^2),$$
the density of the data $(Y_1,\ldots,Y_n)$ writes as follows:
\begin{align*}&\exp\left\{
-\frac{1}{2\sigma^2}\sum_{i=1}^n (Y_i-X_i^\text{T}\beta)^2
\right\}\\
&\qquad=\exp\left\{-\frac{1}{2\sigma^2}\sum_{i=1}^n [(Y_i-X_i^\text{T}\hat{\beta})^2
+(X_i^\text{T}\hat{\beta}-X_i^\text{T}\beta)^2]\right\}\\
&\qquad=\exp\left\{-\frac{1}{2\sigma^2}[\text{SSR}+\text{SSE}]\right\}\\
&\qquad=\exp\left\{-\frac{1}{2\sigma^2}\text{SSE}\right\}\times\exp\left\{-\frac{1}{2\sigma^2}\text{SSR}\right\}\end{align*}
and only the first term depends on the parameter $\beta$ and hence characterises the model fit, while the second term is about the residual variability of the $Y_i$'s around their best prediction or projection, $X_i^\text{T}\hat{\beta}$.


text:
Q: How do I bootstrap an async event in angularjs? I wish to use indexeddb in my angularjs app. However loading indexeddb and setting op the stores is async; and my route's resolve method already starts querying the db for data on page load.
As the db isn't set up yet, the query fails.
What is the best way to handle this?
Is there a way in angularjs to wait for my indexeddb to load before starting the app?

A: You could do manual bootstrap of your modules instead of angular doing it. I suppose indexeddb has a way to intimate when it's done loading.. In that callback, you could bootstrap angular. Refer http://docs.angularjs.org/guide/bootstrap for manual initialization.


text:
Q: Por que o código gera lixo no início do vetor? o seguinte código gera um resultado inesperado, no final do loop as primeiras posições do vetor estão com lixo armazenado, alguém sabe dizer porque isso está acontecendo, e onde está o erro?
OBS. O código tem o mesmo comportamento tanto em C como em C++ (compiladores gcc e g++)
Código:
    #include<stdio.h>
    #include<stdlib.h>

    int V = 10;
    int E = 20;

    int main() {
        double sol[3*E + V];
        int ind[3*E + V];
        double val[3*E + V];
        double ub[3*E + V];
        double obj[3*E + V];
        char **varname;
        char vtype[V];
        int erro;

        varname = (char**) malloc((3*E+V)*sizeof(char**));

        for (int i = 0; i < V; ++i) {
            obj[i] = 0;
            vtype[i] = 'B';
            ub[i] = 1;
            varname[i] = (char*) malloc(sizeof(char*)*10);
            sprintf(varname[i], "y_%i", i);
        }

        int k = 0;
        for (int i=V; i < (V+3*E); i+=3) {
            for(int j=0; j < 3; ++j) {
                obj[i+j] = 0;
                vtype[i+j] = 'B';
                ub[i+j] = 1;
                varname[i+j] = (char*) malloc(sizeof(char*)*15);
                sprintf(varname[i+j], "x_%i_%i_%i", 0, 0, j);
            }
            k++;
        }

        for (int i=0; i < (V+3*E); ++i) {
            printf(" obj[%d]: %.1f \t(%s), \t (%c) <= (%.1f)\n", i, obj[i], varname[i], vtype[i], ub[i]);
        }

        getchar();

    }

Saída:
    Success time: 0 memory: 2296 signal:0
     obj[0]: 156842099844.5     (y_0),   (B) <= (1.0)
     obj[1]: 156842099844.5     (y_1),   (B) <= (1.0)
     obj[2]: 156842099844.5     (y_2),   (B) <= (1.0)
     obj[3]: 156842099844.5     (y_3),   (B) <= (1.0)
     obj[4]: 156842099844.5     (y_4),   (B) <= (1.0)
     obj[5]: 156842099844.5     (y_5),   (B) <= (1.0)
     obj[6]: 0.0    (y_6),   (B) <= (1.0)
     obj[7]: 0.0    (y_7),   (B) <= (1.0)
     obj[8]: 0.0    (y_8),   (B) <= (1.0)
     obj[9]: 0.0    (y_9),   (B) <= (1.0)
     obj[10]: 0.0   (x_0_0_0),   (B) <= (1.0)
     obj[11]: 0.0   (x_0_0_1),   (B) <= (1.0)
     obj[12]: 0.0   (x_0_0_2),   (B) <= (1.0)
     obj[13]: 0.0   (x_0_0_0),   (B) <= (1.0)
     obj[14]: 0.0   (x_0_0_1),   (B) <= (1.0)
     obj[15]: 0.0   (x_0_0_2),   (B) <= (1.0)
     obj[16]: 0.0   (x_0_0_0),   (B) <= (1.0)
     obj[17]: 0.0   (x_0_0_1),   (B) <= (1.0)
     obj[18]: 0.0   (x_0_0_2),   (B) <= (1.0)
     obj[19]: 0.0   (x_0_0_0),   (B) <= (1.0)
     obj[20]: 0.0   (x_0_0_1),   (B) <= (1.0)
     obj[21]: 0.0   (x_0_0_2),   (B) <= (1.0)
     obj[22]: 0.0   (x_0_0_0),   (B) <= (1.0)
     obj[23]: 0.0   (x_0_0_1),   (B) <= (1.0)
     obj[24]: 0.0   (x_0_0_2),   (B) <= (1.0)
     obj[25]: 0.0   (x_0_0_0),   (B) <= (1.0)
     obj[26]: 0.0   (x_0_0_1),   (B) <= (1.0)
     obj[27]: 0.0   (x_0_0_2),   (B) <= (1.0)
     obj[28]: 0.0   (x_0_0_0),   (B) <= (1.0)
     obj[29]: 0.0   (x_0_0_1),   (B) <= (1.0)
     obj[30]: 0.0   (x_0_0_2),   (B) <= (1.0)
     obj[31]: 0.0   (x_0_0_0),   (B) <= (1.0)
     obj[32]: 0.0   (x_0_0_1),   (B) <= (1.0)
     obj[33]: 0.0   (x_0_0_2),   (B) <= (1.0)
     obj[34]: 0.0   (x_0_0_0),   (B) <= (1.0)
     obj[35]: 0.0   (x_0_0_1),   (B) <= (1.0)
     obj[36]: 0.0   (x_0_0_2),   (B) <= (1.0)
     obj[37]: 0.0   (x_0_0_0),   (B) <= (1.0)
     obj[38]: 0.0   (x_0_0_1),   (B) <= (1.0)
     obj[39]: 0.0   (x_0_0_2),   (B) <= (1.0)
     obj[40]: 0.0   (x_0_0_0),   (B) <= (1.0)
     obj[41]: 0.0   (x_0_0_1),   (B) <= (1.0)
     obj[42]: 0.0   (x_0_0_2),   (B) <= (1.0)
     obj[43]: 0.0   (x_0_0_0),   (B) <= (1.0)
     obj[44]: 0.0   (x_0_0_1),   (B) <= (1.0)
     obj[45]: 0.0   (x_0_0_2),   (B) <= (1.0)
     obj[46]: 0.0   (x_0_0_0),   (B) <= (1.0)
     obj[47]: 0.0   (x_0_0_1),   (B) <= (1.0)
     obj[48]: 0.0   (x_0_0_2),   (B) <= (1.0)
     obj[49]: 0.0   (x_0_0_0),   (B) <= (1.0)
     obj[50]: 0.0   (x_0_0_1),   (B) <= (1.0)
     obj[51]: 0.0   (x_0_0_2),   (B) <= (1.0)
     obj[52]: 0.0   (x_0_0_0),   (B) <= (1.0)
     obj[53]: 0.0   (x_0_0_1),   (B) <= (1.0)
     obj[54]: 0.0   (x_0_0_2),   (B) <= (1.0)
     obj[55]: 0.0   (x_0_0_0),   (B) <= (1.0)
     obj[56]: 0.0   (x_0_0_1),   (B) <= (1.0)
     obj[57]: 0.0   (x_0_0_2),   (B) <= (1.0)
     obj[58]: 0.0   (x_0_0_0),   (B) <= (1.0)
     obj[59]: 0.0   (x_0_0_1),   (B) <= (1.0)
     obj[60]: 0.0   (x_0_0_2),   (B) <= (1.0)
     obj[61]: 0.0   (x_0_0_0),   (B) <= (1.0)
     obj[62]: 0.0   (x_0_0_1),   (B) <= (1.0)
     obj[63]: 0.0   (x_0_0_2),   (B) <= (1.0)
     obj[64]: 0.0   (x_0_0_0),   (B) <= (1.0)
     obj[65]: 0.0   (x_0_0_1),   (B) <= (1.0)
     obj[66]: 0.0   (x_0_0_2),   (B) <= (1.0)
     obj[67]: 0.0   (x_0_0_0),   (B) <= (1.0)
     obj[68]: 0.0   (x_0_0_1),   (B) <= (1.0)
     obj[69]: 0.0   (x_0_0_2),   (B) <= (1.0)

Abraços!

A: Seu array vtype tem apenas tamanho 10, mas você escreve nele como se ele tivesse o mesmo tamanho dos outros. Da forma como as variáveis locais são estruturadas, você acaba escrevendo em cima da memória dos outros arrays. Neste caso você está escrevendo por cima do array obj, o que acaba gerando o lixo que você observou.


text:
Q: Handling ruby Float like java if i make a function that simply return a double value like this
double example ()
{
   double i =  999999999;
   return i;
}

the output will be:
example() => 9.99999999E8
i don't know how to obtain it with ruby.. can someone help me?

A: For your example, use a float literal instead of an integer literal. That is, type 999999999.0 or 9.99999999e8 instead of 999999999. If it's in a variable instead (e.g. x), use x.to_f:
def f()
    999999999.0
end

or
def f()
    (999999999).to_f
end

A: To just turn it into a float, you can use to_f, for displaying in scientific notation a format string will help:
>> 999999999.to_f #=> 999999999.0
>> "%E" % 999999999 #=> "1.000000E+09"


text:
Q: Number of arguments passed to thread in windows In C++/C#/Java we can start the thread with function that accepts some arguments. In WinAPI we start the thread with function that accepts only void*.
How many arguments are passed really to real windows threads? Maybe many arguments are turned into void* that points on some struct?

A: At the core of most threading APIs is a function pointer to execute and a void* parameter that lets you provide some data to the executing function.  The void* typically points to some object instance that the thread function then casts into the known object type to use.  This, however, is ripe for programmer error.
The higher level APIs that you mention (std::thread in C++, Thread in Java, etc) are doing this under the hood and providing you convenient, type-safe APIs to ensure you can't mess it up.


text:
Q: Not calculating exponential and log functions in Oracle I am having some challenges with exponential and log functions in Oracle in that I am not getting the expected answer to the formula below -I should be getting 10.97 bur rather I am getting 32.77
The formula is given as
M = exp(-8.758548 + 2.151173· ln(height) - 0.027927·ln (age) + Mspline)
Any assistance much appreciated -Code is as follows-
with samp as (select 1 as ID,178 as ht,30 as age, 0.101788 as MSPLINE
from dual)
select
exp(-7.664278+2.151173*ln(samp.ht)-0.027927*ln(samp.age)+Mspline) from samp;


text:
Q: Share storage between a sub vector and a matrix in R In R, one can create a matrix from a (whole) vector by using matrix or adding a dim attribute to the vector (dim(x)=c(2,2) for example). But as soon as the vector of the new matrix is modified, a copy is made and the matrix uses its own storage.
My problem is the following: I need to manage a list of matrices, of different dimensions, which, I interpret in my algorithm, either as a list of matrices or as a vector long vector made of all the matrices. The tranformation between a long vector and list and a list of matrices is using too much CPU time for what it is.
Is it possible to force a matrix to share its internal representation (its array) with a vector, such that if I modify the matrix or the vector, the modification is seen by the other object too.
Example:
x <- 1:10
y <- matrix(x[2:4],2,2)
y[1,1] <- 1234

print(x)
[1]  1  2  3  4  5  6  7  8  9 10

print(y)
     [,1] [,2]
[1,] 1234    3
[2,]    2    4

What I want, assuming there exists a matrix.by.reference function which would implement my question above:
x <- 1:10
y <- matrix.by.reference(x[1:4],2,2)
y[1,1] <- 1234

print(x)
[1]  1234  2  3  4  5  6  7  8  9 10

print(y)
     [,1] [,2]
[1,] 1234    3
[2,]    2    4


text:
Q: Manual swiping in view pager using Trinea/android-auto-scroll-view-pager is not working? I am using third party library for automatic scrolling and touch events in an image slider every thing is working fine except manual swiping of images in image slider. I am not able to swipe images manually.
Name of the library which I am using is
"Trinea/android-auto-scroll-view-pager"
Here is my code for fragment where Ii am using auto scroll view pager:
public class HomeFragment extends Fragment {
    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";
    TextView tv_slider, tv_button;
    AutoScrollViewPager mViewPager;

    private static int currentPage = 0;
    private static int NUM_PAGES = 0;
    private static final Integer[] IMAGES= {R.drawable.ecommerce, R.drawable.digital_marketing, R.drawable.explainer, R.drawable.it_services,
            R.drawable.mobile_app, R.drawable.seo, R.drawable.software, R.drawable.webdesign};
    private ArrayList<Integer> ImagesArray = new ArrayList<Integer>();

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;

    private OnFragmentInteractionListener mListener;

    public HomeFragment() {

    }

    public static HomeFragment newInstance(String param1, String param2) {
        HomeFragment fragment = new HomeFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);

        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View v = inflater.inflate(R.layout.fragment_home, container, false);

        tv_slider=(TextView)v.findViewById(R.id.tv_slider);
        tv_slider.setTypeface(EasyFonts.robotoLight(this.getActivity()));
        tv_button=(TextView)v.findViewById(R.id.tv_button);
        tv_button.setTypeface(EasyFonts.robotoLight(this.getActivity()));

        for(int i=0;i<IMAGES.length;i++)
            ImagesArray.add(IMAGES[i]);

        mViewPager = (AutoScrollViewPager) v.findViewById(R.id.pager);
        mViewPager.setAdapter(new SlidingImage_Adapter(getActivity(),ImagesArray));
        mViewPager.setOffscreenPageLimit(1);

        CirclePageIndicator indicator = (CirclePageIndicator)
                v.findViewById(R.id.indicator);

        indicator.setViewPager(mViewPager);

        final float density = getResources().getDisplayMetrics().density;

//Set circle indicator radius
        indicator.setRadius(3 * density);

        NUM_PAGES =IMAGES.length;

        mViewPager.startAutoScroll();
        mViewPager.setInterval(3000);

        mViewPager.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {

                switch(motionEvent.getAction())
                {
                    case MotionEvent.ACTION_DOWN:
                        Log.w("touched","down");
                        mViewPager.stopAutoScroll();
                        return true;
                    //break;

                    case MotionEvent.ACTION_UP:
                        Log.w("touched","up");
                        mViewPager.startAutoScroll();
                        return true;

                }

                return true;
            }
        });

        // Pager listener over indicator
        indicator.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {

            @Override
            public void onPageSelected(int position) {
                currentPage = position;

            }

            @Override
            public void onPageScrolled(int pos, float arg1, int arg2) {

                switch (pos){

                    case 0:
                        tv_slider.setText(getString(R.string.es_content));
                        break;

                    case 1:
                        tv_slider.setText(getString(R.string.dm_content));
                        break;

                    case 2:
                        tv_slider.setText(getString(R.string.ev_content));
                        break;

                    case 3:
                        tv_slider.setText(getString(R.string.it_content));
                        break;

                    case 4:
                        tv_slider.setText(getString(R.string.md_content));
                        break;

                    case 5:
                        tv_slider.setText(getString(R.string.seo_content));
                        break;

                    case 6:
                        tv_slider.setText(getString(R.string.sd_content));
                        break;

                    case 7:
                        tv_slider.setText(getString(R.string.wd_content));
                        break;

                }

            }

            @Override
            public void onPageScrollStateChanged(int pos) {

            }
        });

        return v;

    }

    // TODO: Rename method, update argument and hook method into UI event
    public void onButtonPressed(Uri uri) {
        if (mListener != null) {
            mListener.onFragmentInteraction(uri);
        }
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);

    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    public interface OnFragmentInteractionListener {
        // TODO: Update argument type and name
        void onFragmentInteraction(Uri uri);
    }

    @Override
    public void onResume() {
        super.onResume();
        mViewPager.startAutoScroll();
    }

    @Override
    public void onStop() {
        super.onStop();
        mViewPager.stopAutoScroll();
    }
}

This is my adapter class:
public  class SlidingImage_Adapter extends PagerAdapter {

    private ArrayList<Integer> IMAGES;
    private LayoutInflater inflater;
    private Context context;

    public SlidingImage_Adapter(Context context, ArrayList<Integer> IMAGES) {
        super();
        this.context = context;
        this.IMAGES=IMAGES;
        inflater = LayoutInflater.from(context);
    }

    @Override
    public void destroyItem(ViewGroup container, int position, Object object) {
        container.removeView((View) object);
    }

    @Override
    public int getCount() {
        return IMAGES.size();
    }

    @Override
    public Object instantiateItem(ViewGroup view, int position) {
        View imageLayout = inflater.inflate(R.layout.sliding_images, view, false);

        assert imageLayout != null;
        final ImageView imageView = (ImageView) imageLayout
                .findViewById(R.id.image);

        imageView.setImageResource(IMAGES.get(position));

        view.addView(imageLayout, 0);

        return imageLayout;
    }

    @Override
    public boolean isViewFromObject(View view, Object object) {
        return view.equals(object);
    }

    @Override
    public void restoreState(Parcelable state, ClassLoader loader) {
    }

    @Override
    public Parcelable saveState() {
        return null;
    }

}

This is homefragment.xml file
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:background="@color/background"
    tools:context="com.vamediabox.vamediaboxapp.activities.MainActivity">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="200dp"
        android:background="@color/colorPrimary">

    </RelativeLayout>

<ScrollView
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:layout_marginBottom="10dp"
       >

        <android.support.v7.widget.CardView

            android:layout_width="300dp"
            android:layout_height="wrap_content"
            android:id="@+id/rl_slider"
            android:gravity="center_horizontal"
            app:cardUseCompatPadding="true"
            app:cardElevation="4dp"
            app:cardCornerRadius="3dp"
            app:cardPreventCornerOverlap="false"
            android:layout_centerHorizontal="true">

            <RelativeLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="vertical"
                android:layout_margin="2dp"
                android:id="@+id/rl1">

            <cn.trinea.android.view.autoscrollviewpager.AutoScrollViewPager
                android:id="@+id/pager"
                android:layout_width="fill_parent"
                android:layout_height="200dp"
                android:layout_margin="2dp"
                android:layout_alignParentTop="true" />

                <com.viewpagerindicator.CirclePageIndicator
                    android:id="@+id/indicator"
                    android:layout_width="fill_parent"
                    android:layout_height="20dp"
                    android:layout_centerHorizontal="true"
                    android:layout_below="@+id/pager"
                    android:padding="5dip"
                    app:centered="true"
                    app:fillColor="@color/colorPrimary"
                    app:pageColor="@color/view_color"
                    app:snap="false" />

            <TextView
                android:layout_width="match_parent"
                android:layout_height="80dp"
                android:id="@+id/tv_slider"
                android:layout_marginTop="5dp"
                android:layout_marginLeft="10dp"
                android:layout_marginRight="10dp"
                android:layout_marginBottom="5dp"
                android:textSize="14sp"
                android:layout_below="@+id/indicator"
                android:textColor="@color/slider_text"

                />

            </RelativeLayout>

    </android.support.v7.widget.CardView>
  </RelativeLayout>

</ScrollView>
</RelativeLayout>

and last this is sliding_images.xml
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="1dip" >

<ImageView
    android:id="@+id/image"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:adjustViewBounds="true"
    android:layout_gravity="center"
    android:scaleType="fitXY" />
</FrameLayout>

A: not sure if you still looking for a way to fix this in case you do, check consumeTouch inside AutoScrollViewPager this is where your issue is.
You need to make sure that
getParent().requestDisallowInterceptTouchEvent(true)

is getting called.
hope this helps.
Cheers


text:
Q: What is the difference between [object main timeline], stage and root in as3? I want to know the difference between [object main timeline], stage and root in as3.

A: Here is a what seems to be a decent text covering the subject, it's linked to by several people:
How stage, root, and MainTimeline Fit Together


text:
Q: PHP Count search result from mysql database I have a php script doing a search record from mysql database, how can i add a count for total query return from mysql? eg. i search "ABC", total search results are 3, i want to display this after the search "total search found: 3". Have been trying below code so far and not making any good progress, anyone can can assist? Thanks
<?php
define('DB_HOST', 'localhost');
define('DB_NAME', 'stock');
define('DB_CHARSET', 'utf8mb4');
define('DB_USER', 'root');
define('DB_PASSWORD', '');

try
{
    $pdo = new PDO("mysql:host=" . DB_HOST . ";charset=" . DB_CHARSET . ";dbname=" . DB_NAME, DB_USER, DB_PASSWORD, [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC, PDO::ATTR_EMULATE_PREPARES => false]);
}
catch(Exception $ex)
{
    die($ex->getMessage());
}

$stmt = $pdo->prepare("SELECT * FROM `data` WHERE `Name` LIKE ? OR `shopfront_signage` LIKE ? ");

$stmt->execute(["%" . $_POST['search'] . "%", "%" . $_POST['search'] . "%"]);

$results = $stmt->fetchAll();
if (isset($_POST['ajax']))
{
    echo json_encode($results);
}

//$resultscount= $results[0];
//echo $resultscount;
$query = mysqli_query($stmt);
$resultrow = mysqli_num_rows($query);
echo 'Total search found: ' . $resultrow;

?>

A: $count = $stmt ->rowCount();

I'd put this directly under the execute.

A: Just use count(), e.g.
echo 'Total search found: ' . count($results);


text:
Q: Xdebug / Vim / getting it to work So I have tried following multiple tutorials to get xdebug to work on my development server. The best one I have found so far is this.
I have installed xdebug and it shows correctly in my phpinfo(). I have installed https://github.com/joonty/vdebug and when I hit F5 it works great. The problem is I then go to my dev server ip address like so "http:///?XDEBUG_SESSION_START=1" and it doesn't trip anything. My vim xdebug just times out.
I have set up my php.ini file the following way:
zend_extension=/usr/lib/php5/20090626/xdebug.so
xdebug.remote_enable=1
xdebug.remote_host=localhost
xdebug.remote_port=9000

I can't seem to figure out why this is happening. Any help would be appreciated.

A: I have these settings in my debug.ini
0 zend_extension=xdebug.so
1 xdebug.remote_enable=on
2 xdebug.remote_handler=dbgp
3 xdebug.remote_host=localhost
4 xdebug.remote_port=9000
5
6 xdebug.profiler_output_dir="/tmp"
7 xdebug.profiler_append=0
8 xdebug.profiler_enable_trigger=On
9 xdebug.profiler_output_name="%H-%u.trace"
10
11 xdebug.profiler_enable=0
12 xdebug.remote_autostart=1
13 xdebug.max_nesting_level=200

The profiler stuff is non-relevant, but remote_autostart might help you.


text:
Q: Background image not showing in nested divs I'm having an issue where I my background image isn't showing in a specific circumstance, and when it does there are some issues.

      content goes here

If I have the div ids swapped, the image shows as normal - the issue being it gets messed up when messing with the size of the page (the image reduces in size, but there is a growing margin like space above the image. The width remains 100%, but the height does not.) If I have it as it is in the above code, the background image does not show at all.
#indImg {
    background-image: url("../images/index_header.jpg");
    background-size: 100%;
    background-repeat: no-repeat;
    background-position: center bottom;
}

Would there be a way to have the background show in the indImg div, or to not have it move when adjusting the size of the page? If I remove the background-size style, it somewhat fixes it but then the image does not fit 100% of the browser width. Adjusting background-position changes where the height changes, e.g removing the current property makes the image go to the top, not the bottom.
Image sort of showing what I mean.


text:
Q: What is the interpretation of (panel data) Quantile Regression? I estimated a (panel data) quantile regression model using qregpd in Stata 13. It is not clear what is the interpretation of the estimate. Let's say that I choose the 50th quantile, and I find that the estimate of the main parameter of interest is -0.5.
What is the interpretation of the estimate -0.5? Let's say that -0.5 is the estimated parameter for the effect of random variable x on random variable y. Let's say that x increases by 1, so that y will decrease by (-0.5 * 1) = -0.5. Is this effect true only for the guy at the median, or for all individuals?

A: You can't really say much about the guy at the median or how individuals will respons to changes in X. What you may say is that the median of a population with X equal to x is estimated to be 0.5 lower than the median of a population with X equal to (x+1), all other things being equal.
See this answer for a thorough discussion of how to interpret the result: https://stats.stackexchange.com/a/159928


text:
Q: unfortunately has stopped error with ViewPager? I'm trying to create a an app that first show a ListView with many items, when the user click on a specific item then the next activity will open to show images with a ViewPager.
At the beginning I create the ViewPager and I was able to swipe between images, but then when I try to create a new other app that firstly shown the ListView and after clicking on its item show the ViewPager the app stops and show this message: "Unfortunately has stopped". App starts showing items on list but when user clicks on app stop working. I tried to find the error with the LogCat but it doesn't show any thing I don't know why!!!.
Main class
public class MainActivity extends Activity implements OnItemClickListener{

    ListView itemListView;
    String[] values;

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

        itemListView=(ListView)findViewById(R.id.itemListView);
        values=getResources().getStringArray(R.array.values);

        itemListView.setAdapter(new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,values));
        itemListView.setOnItemClickListener(this);
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position,
            long id) {

        Intent i=new Intent(MainActivity.this,SwipeActivity.class);

        switch(itemListView.getItemAtPosition(position).toString()){

        case "First":
            i.putExtra("nextActivity", 1);
            startActivity(i);
            break;

        case "Second":
            i.putExtra("nextActivity", 2);
            startActivity(i);
            break;

        }

    }
}

SwipeActivity" class
public class SwipeActivity extends Activity{

ViewPager vp;
Table_customSwipeAdapter adapter;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    //requestWindowFeature(Window.FEATURE_NO_TITLE);
    setContentView(R.layout.activity_main);

    vp=(ViewPager)findViewById(R.id.view_pager);
    adapter=new Table_customSwipeAdapter(this);
    vp.setAdapter(adapter);

}
}

Table_customSwipeAdapter" class
public class Table_customSwipeAdapter extends PagerAdapter{

private int[] image_resources={R.drawable.i1,R.drawable.i2,R.drawable.i3,R.drawable.i4,R.drawable.i5};
private Context ctx;
private LayoutInflater layoutInflater;

public Table_customSwipeAdapter(Context ctx) {
    this.ctx=ctx;
}

@Override
public int getCount() {
    return image_resources.length;
}

@Override
public boolean isViewFromObject(View arg0, Object arg1) {
    // TODO Auto-generated method stub
    return (arg0==(LinearLayout)arg1);
}

public Object instantiateItem(ViewGroup container, int position){

    layoutInflater=(LayoutInflater)ctx.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

    View item_view=layoutInflater.inflate(R.layout.activity_table_custom_swipe_adapter, container,false);

    ImageView imageView=(ImageView)item_view.findViewById(R.id.image_view);
    TextView textView=(TextView)item_view.findViewById(R.id.image_count);
    imageView.setImageResource(image_resources[position]);
    textView.setText("Image "+(position+1));
    container.addView(item_view);

    return item_view;

}

public void destroyItem(ViewGroup container, int position, Object object){
    container.removeView((LinearLayout)object);

}

}

I think that the exception is thrown when I call the Table_customSwipeAdapter class, but I don't know why the app works before adding ListView?


text:
Q: Failed to import large SQL file in centos 7 and Mariadb VPS Digitalocean Configuration is :

Centos 7 x64
MariaDB

I am getting this error while uploading 380MB database to MariaDB,
ERROR 2013 (HY000) at line 1013111: Lost connection to MySQL server during query
I used this command mysql -u root -p123456 --database=testdb < file.sql
How do I get MariaDB to accept this file?

A: Try running these before your import and then try again:
SET global net_buffer_length=10000000;
SET global max_allowed_packet=1000000000;
SET innodb_flush_log_at_trx_commit = 2;
SET global innodb_io_capacity = 6000;
SET global innodb_thread_concurrency = 0;
SET foreign_key_checks = 0;
SET UNIQUE_CHECKS = 0;
SET AUTOCOMMIT = 0;

These will increase some limits and turn off some processes that run during import. Make sure to restart your sql server afterwards to reset these values. Obviously there are some InnoDB variables in there. You can leave them as is or remove them. If you are not running InnoDB, it wont affect anything.
Side Note: You might want to do a little more searching on SO before posting a question as this is a very common issue and there are many answers and solutions here. That will prevent your questions from getting flagged as duplicate and closed before you can get an answer.


text:
Q: Plot different occurrences per date I have a dataset with many columns and two of them are:

Type of vaccine
Date

A
01-01-2021

A
01-01-2021

B
01-01-2021

C
02-01-2021

B
02-01-2021

D
03-01-2021

E
04-01-2021

...
...

I want to plot a line graph showing every type of vaccine and it's amount per date.
I have a plot like this
plot2 = df.value_counts('vacina_dataaplicacao').sort_values().plot(kind='line', cmap='plasma') but it only show one line and the totals per date. I need to separate it, one line for each type of vaccine.

A: You can do it in one line:
pd.crosstab(pd.to_datetime(df['Date']), df['Type of vaccine']).cumsum().plot()

Credit to @TrentonMcKinney for the idea of using pd.crosstab!
Initially, I was going with basic groupby:
df = df.assign(Date=pd.to_datetime(df['Date']))
tally = df.groupby(['Date', 'Type of vaccine']).size().unstack(fill_value=0)

tally.cumsum().plot()


text:
Q: jslint.js download link Can't find download link for jslint.js from http://www.jslint.com/.
I have downloaded http://jslint.com/webjslint.js, but it doesn't work well
Can anyone give me correct url to download it ?

A: Douglas Crockfords (author) Github:
https://github.com/douglascrockford/JSLint


text:
Q: Match digit optionally in string I would like to match something like (both):

*

*I have "arbitrary string"

*I have 50 "arbitrary string"
I came up with: /^I have (\d+)? "([^"]*)"$/ to match 2nd, but doesn't do with first one.
How to make the digit optional? I need the data in digit.
Thanks.

A: Put space + digits inside a  non-capturing group and make it as optional. If you want to capture digits then put capturing group ie, () around \d+
^I have(?: (\d+))? "([^"]*)"$

DEMO

A: Your regular expression doesn't match the first example string since it requires a total of two space characters between have and ".
Changing the expression to /^I have ?(\d+)? "([^"]*)"$/ fixes it (i.e, let the first space be optional).


text:
Q: Tensorflow with MNIST trained model always prints the wrong number I'm using Tensorflow and Python for text recognition, but when I'm trying to do some number recognition, training is fine, but when I restore the model and use it, no error but always the wrong prediction, here's my code for training and using model. Can someone point out what's the matter with this thing?
Training:
import input_data
import matplotlib.pyplot as plt
import tensorflow as tf
import numpy as np
mn = input_data.read_data_sets("tmp/data", one_hot=True)
training_epoch = 10000
learning_rate = 0.001
batch_size = 20000
display_step = 1
n_hidden1 = 512
n_hidden2 = 512
input_size = 784
n_class = 10
x = tf.placeholder("float", [None, input_size])
y = tf.placeholder("float", [None, n_class])
h = tf.Variable(tf.random_normal([input_size, n_hidden1]))
layer1_bias = tf.Variable(tf.random_normal([n_hidden1]))
layer_1 = tf.nn.sigmoid(tf.add(tf.matmul(x,h),layer1_bias))
w = tf.Variable(tf.random_normal([n_hidden1, n_hidden2]))
layer2_bias = tf.Variable(tf.random_normal([n_hidden2]))
layer_2 = tf.nn.sigmoid(tf.add(tf.matmul(layer_1,w),layer2_bias))
output = tf.Variable(tf.random_normal([n_hidden2, n_class]))
bias_output = tf.Variable(tf.random_normal([n_class]))
output_layer = tf.matmul(layer_2, output) + bias_output
cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=y,     logits=output_layer))
optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate).minimize(cost)
avg_set = []
epoch_set = []
init = tf.global_variables_initializer()
with tf.Session() as sess:
    sess.run(init)
    saver = tf.train.Saver()
    for epoch in range(training_epoch):
        avg_cost = 0.
        batch_total = int(mn.train.num_examples/batch_size)
        for i in range(batch_total):
            batch_x, batch_y = mn.train.next_batch(batch_size)
            print(batch_x.shape)
            sess.run(optimizer, feed_dict={x:batch_x, y:batch_y})
            avg_cost += sess.run(cost, feed_dict={x:batch_x, y:batch_y})/batch_total
        if(epoch % display_step == 0):
            print("Epoch:%d " % (epoch), "cost:", "{:.9f}".format(avg_cost))
        avg_set.append(avg_cost)
        epoch_set.append(epoch+1)
    print("Training finished")
    plt.plot(epoch_set,avg_set, 'o', label='MLP Training phase')
    plt.ylabel('cost')
    plt.xlabel('epoch')
    plt.legend()
    plt.show()
    correct_prediction = tf.equal(tf.argmax(output_layer, 1), tf.argmax(y, 1))
    accuracy = tf.reduce_mean(tf.cast(correct_prediction, "float"))
    print("Model Accuracy:", accuracy.eval({x: mn.test.images, y: mn.test.labels}))
    saver.save(sess, "model-batchsize-20000-epoch-10000-learningrate-0.001/tf_mlp_model.ckpt")

Testing:
import numpy as np
import tensorflow as tf
import input_data
import cv2
import os
dir = os.path.dirname(os.path.realpath(__file__))
img = cv2.imread('6-1.png')
img.astype("float")
img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
img = img.flatten()
img = np.expand_dims(img, axis=0)
n_hidden1 = 512
n_hidden2 = 512
input_size = 784
n_class = 10
x = tf.placeholder("float", [1, input_size])
y = tf.placeholder("float", [None, n_class])
h = tf.Variable(tf.random_normal([input_size, n_hidden1]))
layer1_bias = tf.Variable(tf.random_normal([n_hidden1]))
layer_1 = tf.nn.sigmoid(tf.add(tf.matmul(x,h),layer1_bias))
w = tf.Variable(tf.random_normal([n_hidden1, n_hidden2]))
layer2_bias = tf.Variable(tf.random_normal([n_hidden2]))
layer_2 = tf.nn.sigmoid(tf.add(tf.matmul(layer_1,w),layer2_bias))
output = tf.Variable(tf.random_normal([n_hidden2, n_class]))
bias_output = tf.Variable(tf.random_normal([n_class]))
output_layer = tf.matmul(layer_2, output) + bias_output
with tf.Session() as sess:
    tf.train.Saver()
    tf.train.Saver().restore(sess, dir + "/model-batchsize-20000-epoch-10000-   learningrate-0.001/tf_mlp_model.ckpt")
    pred = tf.argmax(sess.run(output_layer, feed_dict={x:img}), 1)
    print(pred.eval())

Testing output:
[2]

sess.run(output_layer, feed_dict={x:img}):
[[ -4.48937702e+00  -8.70745659e+00   2.27353687e+01   2.25894527e+01
1.72218680e-02   1.78360157e+01   2.39438486e+00   5.72816038e+00
-2.13753247e+00   4.05950975e+00]]

EDIT 1:
I forgot to say that the real value is 6, not 2, it's a 28x28 screenshot from my MacBook, link:6-1.png
EDIT 2:
Tried number 2, return:
[3]

A: Turned out that it is normal with MLP. I should use Convolutional Neural Network back then. Problem solved.


text:
Q: Access two ISP at once for failover Assumptions:

*

*Office locale with a dedicated leased line is literally a factor of 50x more expensive than broadband.

*I know nothing of office networking, but will hire appropriately if
this is possible

*This is a 'back office' for workload processing. There will not be any hosted services from this office location

Can I subscribe to two broadband ISPs in one office and allow the network to randomly select which ISP a computer will use when starting up, or only one if the other is failing?

A: You can connect your office to two different ISPs for redundancy but you need to configure your network to support this. Both ISPs will present your WAN router/firewall with a default gateway. It is up to you - or your network engineer/consultant - to configure it such that

*

*some traffic uses ISP1, and the other traffic uses ISP2, with both serving as a backup for the other;

*all traffic uses ISP1 primarily and ISP2 only as a backup;

*...

If both default gateways are valued equally, then the router/firewall at your enterprise edge will indeed randomly select one of the two gateways and thus access the internet via one or the other.
Given that your internal network (most likely) uses private IP addresses and the firewall will have to perform NAT, you should put some thought into your strategy, especially if you also host services, i.e. inbound access is required from the Internet.

A: If you are planning for 2 isp's and you want to consume bandwidth of both below is what you can do

*

*get one dual wan router preferably cisco rv042 it has inbuild vpn which can be useful at times, at very low cost

*plug both isp's configure them

*select Load Balance (Auto Mode) under Dual wan section, it will auto balance load between both isp and consume both

*use same dns servers on both isp, as using different dns may break connections or timeouts

or
You can get some cheap firewall boxes and configure it with dual wan
or
if your comfortable with opensource and have will to learn then you can use pfsense, still you will need one system any low config will do
Setup Pfsense


text:
Q: Qt QML click under the bounding box I'm trying to do the following.

So far the only solution I found is to create my button from C++ and to use setMask. Is there any other way in order to achieve the same results but just using QML?
My shape button:
import QtQuick 2.0
import QtQuick.Shapes 1.14

Item {
    id: sideButtonID
    property alias mouseX: mouseArea.mouseX
    property alias mouseY: mouseArea.mouseY
    readonly property bool pressed: containsMouse && mouseArea.pressed

    property point topLeftOffset: Qt.point(0, 0)
    property point topRightOffset: Qt.point(0, 0)
    property point bottomRightOffset: Qt.point(0, 0)
    property point bottomLeftOffset: Qt.point(0, 0)

    property var colorPressed: "green"
    property var colorSelected: "red"
    property var colorUnselected: "darkorange"

    signal clicked

    property var coordinate: generateButtonShapeCoordinates(x,y,width,height)
    property point topLeft: coordinate.topLeft
    property point topRight: coordinate.topRight
    property point bottomRight: coordinate.bottomRight
    property point bottomLeft: coordinate.bottomLeft

    function generateButtonShapeCoordinates(x, y, width, height){

        var topLeft = Qt.point(x-width/2 - topLeftOffset.x, y-height-topLeftOffset.y)
        var topRight = Qt.point(x+width/2-topRightOffset.x, y-height-topRightOffset.y)
        var bottomRight = Qt.point(x+width/2-bottomRightOffset.x, y-bottomRightOffset.y)
        var bottomLeft = Qt.point(x - width/2-bottomLeftOffset.x, y-bottomLeftOffset.y)

        return {
            topLeft : topLeft,
            topRight : topRight,
            bottomRight : bottomRight,
            bottomLeft : bottomLeft
        };
    }

    function inside(point, polygon) {
        // ray-casting algorithm based on
        // http://www.ecse.rpi.edu/Homepages/wrf/Research/Short_Notes/pnpoly.html
        var x = point[0], y = point[1];

        var inside = false;
        for (var i = 0, j = polygon.length - 1; i < polygon.length; j = i++) {
            var xi = polygon[i][0], yi = polygon[i][1];
            var xj = polygon[j][0], yj = polygon[j][1];

            var intersect = ((yi > y) != (yj > y))
                    && (x < (xj - xi) * (y - yi) / (yj - yi) + xi);
            if (intersect) inside = !inside;
        }

        return inside;
    }

    property bool containsMouse: {
        var topLeft = Qt.point(0-topLeftOffset.x, 0-topLeftOffset.y)
        var topRigh = Qt.point(width-topRightOffset.x, 0-topRightOffset.y)
        var bottomRight = Qt.point(width-bottomRightOffset.x, height-bottomRightOffset.y)
        var bottomLeft = Qt.point(0-bottomLeftOffset.x, height-bottomLeftOffset.y)

        var polygon = [[topLeft.x,topLeft.y],[topRigh.x,topRigh.y],[bottomRight.x,bottomRight.y],[bottomLeft.x,bottomLeft.y]]
        var point = [mouseX, mouseY]

        return inside(point, polygon)
    }

    MouseArea {
        id: mouseArea
        anchors.fill: parent
        hoverEnabled: true
        acceptedButtons: Qt.LeftButton | Qt.RightButton
        onClicked: if (sideButtonID.containsMouse) sideButtonID.clicked()
    }
    Shape {
        antialiasing: true
        vendorExtensionsEnabled: true
        asynchronous: true
        anchors.centerIn: parent

        ShapePath {
            id: shapepathId

            strokeWidth: -1
            fillColor: sideButtonID.pressed ? sideButtonID.colorPressed : (sideButtonID.containsMouse ? sideButtonID.colorSelected : sideButtonID.colorUnselected)
            startX: sideButtonID.topLeft.x; startY: sideButtonID.topLeft.y
            PathLine { x: sideButtonID.topRight.x; y: sideButtonID.topRight.y }
            PathLine { x: sideButtonID.bottomRight.x; y: sideButtonID.bottomRight.y }
            PathLine { x: sideButtonID.bottomLeft.x; y: sideButtonID.bottomLeft.y }
        }
        Component.onCompleted: {
            console.log("TopLeft: "+sideButtonID.topLeft)
            console.log("TopRight: "+sideButtonID.topRight)
            console.log("BottomLeft: "+sideButtonID.bottomLeft)
            console.log("BottomRight: "+sideButtonID.bottomRight)
        }
    }
}

The usage of my button:
SideButtons {
    z: 100
    id: sideButtonID
    width: 130
    height: 248
    anchors.verticalCenterOffset: 9
    anchors.horizontalCenterOffset: -255
    anchors.horizontalCenter: parent.horizontalCenter
    anchors.verticalCenter: parent.verticalCenter
    bottomRightOffset: Qt.point(100,0)
    onClicked: {
        print("X: "+mouseX)
        print("Y: "+mouseY)
        print("clicked")
    }
}

Some of the options that I've heard so far but there are not good in my case.

*

*using an image with a transparent background (sure but I'm going to have the same problem)

*creating a C++ class which will inherit QAbstractButton (I would prefer to avoid as much as I can usage of C++ in the Ui side)

*usage of a Shape in combination with MouseArea (I'm doing this already but I am encountering the bounding box problem.

Is there any other way which I don't know yet about?


text:
Q: How is Live Streaming of Audio or Video done? I am trying to understand how live audio streaming is accomplished as far as buffer management goes.
For the audio case: if you have a source capturing a frames at 44100hz +/- clock error, and a receiver with an audio card DAC consuming frames at 44100hz +/- clock error.
Because of the clock errors at each end the buffer at the receiver would (eventually) either grow out of control or under run.
For one source live streaming to many receivers a flow control stream is not possible.
My only guess at a solution would be to keep track of buffer fill at the receiver (over a longer period than network jitter effects) and either insert samples or drop samples.
Any insight on this would be greatly appreciated.
Thanks!

A: It does matter. Streaming continuous, long term, live audio over a network is often done in industry where it's no joking matter. It's too simplistic to assume that two oscillators will be within such a small deviation that it can be ignored.
(As an aside, it's OK to say it doesn't matter in some circumstances. Take, for instance, Pugsley Adam's question to his older sister, Wednesday Adams, when seeing two wicked adults fall into open graves. He asks "Are they dead?" and she answers, dryly, "Does it matter?")
Here are three possible approaches to coping with the problem and, if you can think of more or better solutions, please share:
1) Implement some kind of frequency lock loop, whereby the receivers' clocks are adjusted slightly to accommodate the input stream
2) Perform sample rate conversion at the receivers to correct the error
3) Monitor the number of samples in a buffer or queue so that, when underrun or overrun is imminent, a few samples are generated or dropped in order to avoid serious degradation in audio quality.
If you have control over the receivers' clocks, the first solution is best. I'm not sure how to do that with high-level audio software modules like ALSA or PulseAudio (any suggestions gratefully received!)
Performing sample rate conversion might be nice, philosophically, but would be far more CPU intensive than it's worth (and add unnecessary risk of failure)
So I'm in favour of monitoring buffer depth (as suggested by May) and slipping samples in or out inconspicuously.
Any more ideas?

A: It is definitely the case that the clocks fall out of sync.  The truth is, it doesn't matter.
Suppose a clock is off by as much as 5Hz (which is a few magnitude over what is normal).  Over the course of an hour, the clocks only drift by 0.4 seconds, which is less than the usual 2-5 seconds of buffer time.
Network issues often cause rebuffering far more often than clock sync issues.  In reality, the clocks usually differ by 1Hz or less, making this almost a non-issue.
Now if you want to synchronize playback, that is a whole 'nother problem.  Fortunately, listeners of streaming audio don't usually do this.


text:
Q: Manually construct SQL with binary data in Java I have a small program that manually creates queries. In pseudo code, it's basically done like this

string[] a = new string[x];
  a[0] = "data 1";
  a[1] = "data 2";
  a[2] = "data 3";
  string query = "insert into x (y) values(";
  for i {
      query += a[i] + ",";
  }
  query += ");";

I'm aware that this usage is sub-optimal and I should do a complete re-write at some point.
Now I need to add some binary data to the a-array.
Given a byte[] b, how can I add it to the query?
I haven't tried, but I'm assuming that b.toString() or just query+=b is gonna corrupt my data?

A: Don't put it in the SQL to start with. Use a parameterized query: it'll be a lot easier, and won't risk SQL injection attacks.


text:
Q: What option should be used to remove extra spaces using astyle? How can I remove extra spaces from my code using astyle? For example I want to convert the following code:
void foo (     int  a  ,  int   c )
{
d   = a+      c;
}

to this:
void foo (int a, int c)
{
    d = a + c;
}

But astyle is currently converting it to this:
void foo (int  a  ,  int   c)
{
    d   = a +      c;
}

A: There is currently no way to unpad the spaces around operators in astyle.                  If there had been a way to unpad the operators,
you could have first unpadded the spaces, and then again pad them using -p option.

--pad-oper / -p
Insert space padding around operators.
Any end of line comments will remain in the original column, if possible.
Note that there is no option to unpad. Once padded, they stay padded.

if (foo==2)
    a=bar((b-c)*a,d--);

becomes:

if (foo == 2)
    a = bar((b - c) * a, d--);

Source : http://astyle.sourceforge.net/astyle.html#_pad-oper

A: You can use --pad-header / -H to unpad.
Reference:http://astyle.sourceforge.net/astyle.html#_unpad-paren


text:
Q: .fadeIn() does not fire in IE version less than 9 My CSS:
#midC {
    display: none;
    background: transparent;
    -ms-filter: "progid:DXImageTransform.Microsoft.gradient(startColorstr=#00FFFFFF,endColorstr=#00FFFFFF)"; /* IE8 */
    filter: progid:DXImageTransform.Microsoft.gradient(startColorstr=#00FFFFFF,endColorstr=#00FFFFFF);   /* IE6 & 7 */
}

My JQuery:
$(document).ready(function() {
    $('#midC').load(function() {
        $('#midC').fadeIn('slow');
    });
});

HTML:
<img src="theImages/topLogo_temp.png" id=midC />

The above code work in CSS and IE > 9. Is there anyway to make it work less than version 9? The image sometime appears and sometime doesn't on IE8.

A: There are big caveats to using the load event with images.  From the jQuery docs:

Caveats of the load event when used with images
A common challenge developers attempt to solve using the .load()
  shortcut is to execute a function when an image (or collection of
  images) have completely loaded. There are several known caveats with
  this that should be noted. These are:
It doesn't work consistently nor reliably cross-browser
It doesn't fire correctly in WebKit if the image src is set to the same src as before
It doesn't correctly bubble up the DOM tree
Can cease to fire for images that already live in the browser's cache

The most common I have seen with IE 8 is the last point, where the image is already loaded in the browser cache.

A: In JavaScript, the window.onload event fires after all the images has been loaded, so, I think you may use following instead of document
$(window).load(function() {
    $('#midC').fadeIn('slow');
});

DEMO.
Don't have IE8 to test it but it should work.


text:
Q: Generating and downloading a text file on the fly in Laravel My data is stored in the database and I need to give it out of it in a text file. There is no point in creating a file on disk, but an attempt to generate a response with a file does not work. Found a way like this but it doesn't work ERR_INVALID_RESPONSE
 $contents = 'My data from db';

   $filename = 'example.txt';

   return response()->streamDownload(function () use ($contents) {
         echo $contents;
     }, $filename);

A: In your route name the route with something reasonable like:
Route::get('filename.txt', [FooController::class, 'foo']);

And in your controller at foo() action:
$headers = [
    'Content-Type' => 'application/plain',
    'Content-Description' => 'File name',
];

$contents = 'My data from db';

return \Response::make($contents, 200, $headers);


text:
Q: Compiling Scipy with Anaconda's free MKL libraries I am trying to install Scipy from its master branch on Github into an Anaconda environment in Windows 7. This requires compiling Scipy from source. Scipy can use MKL as its BLAS/LAPACK library and Anaconda comes with free MKL now. I get an error saying that no lapack/blas resources found. How do I tell Scipy setup to use the Anaconda MKL?
Fresh install instructions within Anaconda:
conda create --name scipy_master python=3.6 numpy cython
activate scipy_master
pip install https://github.com/scipy/scipy/tarball/master

Here is the relevent text from the error:
lapack_mkl_info:
    C:\Anaconda3\envs\scipy_master\lib\site-packages\numpy\distutils\system_info.py
        :655: UserWarning: Specified path C:/Anaconda3/envs/scipy_master\Library\lib is
        invalid.
    return self.get_paths(self.section, key)
    C:\Anaconda3\envs\scipy_master\lib\site-packages\numpy\distutils\system_info.py
        :664: UserWarning: Specified path C:/Anaconda3/envs/scipy_master\Library\include is
        invalid.
    return self.get_paths(self.section, key)
    libraries mkl_core_dll,mkl_intel_lp64_dll,mkl_intel_thread_dll not found in []
    NOT AVAILABLE

...

File "scipy\linalg\setup.py", line 20, in configuration
    raise NotFoundError('no lapack/blas resources found')
numpy.distutils.system_info.NotFoundError: no lapack/blas resources found


text:
Q: How to complete aggregation task with flink cep I need to count the number of times in a day that A happens and in 15 minutes that B happens。 The stream maybe  A1 ,A2,B1,B2,A3,B3,B4,B5,A4,A5,A6,A7,B6。
In my case the event results are A2,B1   A3,B3     A7,B6。 And I need receive realtime result when the matcher happen。
I've tired something。 I think it can be only true by use flink cep 。But flink-sql-cep not support aggregation. It only calculate event happened。 In this case ,how to accomplish this task with a single SQL.
I tired two step to do it.I use flink sql cep to matcher first,and then sink to kafka.  In step to I souce pre kafka and use over window to aggregation.
first step:
select pins as pin,'first-step' as result_id, cast(order_amount as varchar) as result_value,event_time as result_time
from stra_dtpipeline MATCH_RECOGNIZE
(   PARTITION BY pin
 ORDER BY event_time
 MEASURES
 t1.pin as pins,
 '1' as order_amount,
 LOCALTIMESTAMP as event_time
ONE ROW PER MATCH
AFTER MATCH SKIP to next row
 PATTERN (t1 t2) WITHIN  INTERVAL '30' SECOND
 DEFINE
t1 as t1.act_type='100001' ,
t2 as t2.act_type='100002' )
second step:
    select pin,'job5' as result_id,cast(sum(1) over (PARTITION BY pin,cast(DATE_FORMAT(event_time,'%Y%m%d') as VARCHAR) order by event_time ROWS BETWEEN INTERVAL '1' DAY PRECEDING AND CURRENT ROW ) as VARCHAR) as result_value,CURRENT_TIMESTAMP as result_time
from stra_dtpipeline_mid
where result_id='first-step' and  DAYOFMONTH(CURRENT_DATE)=DAYOFMONTH(event_time)
I expect  accomplish this task with a single SQL.

A: You can compose the two queries into a single query by using either a subquery or a view.
That would be something like
SELECT a, b OVER (...) ORDER BY event_time FROM (SELECT x, y MATCH_RECOGNIZE ...) WHERE ...

or
CREATE VIEW pattern AS SELECT x, y MATCH_RECOGNIZE ...
SELECT ... FROM pattern WHERE ...


text:
Q: P/Invoke and memory related intermittent crash I've implemented this APIs some time ago and everything was working quite well until some weeks ago when I noticed it, The intermittent crash, the famous Marshaling related in .NET "Attempted to read or write protected memory. This is often an indication that other memory is corrupt".  I noticed that there was also a certain pattern related to the number of opened applications that I have, so I assume its something related to the memory. But checking the available memory, it still pointing to a healthy state when it's crashing. Please see bellow the functions:
C++
__declspec(dllexport) char* xReadData(char *p_buffer, int offset, int size)
{
    // do nothing
    return p_buffer;
}

C#
[DllImport(PathToDll, CharSet = CharSet.Ansi, CallingConvention = CallingConvention.Cdecl)]
public static extern IntPtr xReadData([Out] IntPtr buffer, int offset, int size);

// SIZE = amount of bytes to read (2^13)
IntPtr pnt = Marshal.AllocHGlobal(SIZE);
...
try
{
    xReadData(pnt, 0, SIZE); >> crashing on [Managed to Native Transition]

}
catch
{
}
...
Marshal.FreeHGlobal(pnt);

According to my analysis it crashes in between the completion of the native function and the returning to the managed code again.
Thanks in advance.

A: if ((offset>-1) && (offset + size<= MAX_BYTES))
{
    memcpy(p_buffer, &(input_list[offset]), size);
}

That condition will definitely throw exception when offset is equal to MAX_BYTES and size is equal to zero.
input_list[MAX_BYTES] is out of bounds.
Also, I hope you deallocate the buffer :-')


text:
Q: ORMLite with MYSQL - how to detect if object is shallow or deep loaded? does ORMLite has some API call to to inspect the java objected created by ORMLite and decide if it was a shallow load (ID only) or full (all fields populated?).
I know about the refresh() method and having a custom wrapper about DOA loader, but Im hoping there is an easier way??

A:
does ORMLite has some API call to to inspect the java objected created by ORMLite and decide if it was a shallow load (ID only) or full (all fields populated?).

Unfortunately no it doesn't.  ORMLite is not returning some proxy object that it can investigate under the covers.
If you have a field that is always set can you test it yourself in your own code?  Or maybe store a boolean field as true all of the time or something?
Sorry to not be more helpful.


text:
Q: PySide2: How to prevent QFileDialog to close Sub-QMainWidget I have a superclass that inherits from QMainWindow, and its purpose is to call a function inside the Connection function instead of the normal CloseEvent (which would close my whole app) that displays the starter and kills the caller, and only if it sends Close, to actually close the app.
Anyway, I am now trying to call a QFileDialog in one of the derived classes inside a function, as soon as it closes (accepted, rejected alike), the CloseEvent is fired. The problem here is that my class is recognized as the caller and I don't see any way to distinguish the Close event from the dialog and the MainWindow. The event has no method or attribute "sender", and self of course always remains on the QMainWindow class (or its derived superclass)...
My Superclass:
#import 3rd-Party-Libs
from PySide2.QtWidgets import QMainWindow

class SuperMiniApp(QMainWindow):
    '''SuperApp for the common MiniApp-Functions'''
    def __init__(self, parent):
        '''initialize this class'''
        super(SuperMiniApp, self).__init__(parent)

    def closeEvent(self, event):
        '''Overwrite QMainWindow's closeEvent, to prevent it from closing the whole App'''
        #if not from starter catch the Close-Event
        if (self == self.parent()._starter):
            event.accept()
        else:
            self.parent().close_MiniApp(self, event)

calling of the QFileDialog:
def call_dialog(self):
    title = 'Choose One'
    datatypes = '*.*'
    dir = os.getcwd()
    return(QFileDialog.getOpenFileName(self, title, dir, datatypes)[0])


text:
Q: Python "requests" module truncating responses When I use the python requests module, calling requests.get(url), I have found that the response from the url is being truncated.
import requests

url = 'https://gtfsrt.api.translink.com.au/Feed/SEQ'
response = requests.get(url)
print response.text

The response I get from the URL is being truncated. Is there a way to get requests to retrieve the full set of data and not truncate it?
Note: The given URL is a public transport feed which puts out a huge quantity data during the peak of day.

A: I ran into the same issue. The problem is not your Python code. It might be PyCharm or Utility you are using - The console has a buffer limit. You may have to increase that to see your full response.
Refer to this article for more help:
Increase output buffer when running or debugging in PyCharm

A: Add "gzip":true to your request options.
That fixed the issue for me.


text:
Q: Will upgrading Ubuntu affect (data in) my local Subversion repositories? I have a Ubuntu 11.04 installation and I use it for a local Subversion repository. Since 11.04 is no longer supported, I am going to upgrade to a supported release soon, and if possible to the latest version. If I upgrade, will my Subversion data be hidden or lost in some way?

A: It's a good thing you are trying to upgrade to a supported release. Upgrades should run without issues as package maintainers are doing quite good at handling this. Also, packages should not touch user data directories. However, as is valid for all valuable data, make sure you have a backup!
Concerning Subversion repositories, you should have to worry about incompatibilities either, as 1.6.x is packages from Natty 11.04 until Quantal 12.10. Only if you decide to upgrade to 1.7 you should be diving into upgrade scenarios.


text:
Q: C# Web API to consume Azure SQL Server Data I would really appreciate it if you can point me to the right place or right idea. I have not done C# in ages and I am not sure what I am doing anymore.
Basically I have an Azure based MSSQL database that I need to read data from and return that data in JSON format for my iPhone app. Azure APIs do not allow you to read directly from the DB but you can build a .Net web API and use that - so that is where I went to.
I have gotten the first part to work. In that I can make a http request and Azure responds fine. I have also built the DB and tables and I have tested all that and it works. I have also tested the query and it runs well formatted JSON.
However, I need to pass the data in the data reader as an http response and I cannot figure that part out. Attached are the two vanilla files..one that makes the dummy http request and the other is the db connector file.
So in short, in the Function1.cs file I need to go from
:req.CreateResponse(HttpStatusCode.OK, "Hello" + name);   to
:req.CreateResponse(HttpStatusCode.OK, );
First File: Function1.cs
namespace getOutageAlerts

{
    public static class Function1
    {
        [FunctionName("Function1")]
        public static async Task Run([HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)]HttpRequestMessage req, TraceWriter log)
        {
            log.Info("C# HTTP trigger function processed a request.");
        // parse query parameter
        string name = req.GetQueryNameValuePairs()
            .FirstOrDefault(q => string.Compare(q.Key, "name", true) == 0)
            .Value;

        if (name == null)
        {
            // Get request body
            dynamic data = await req.Content.ReadAsAsync<object>();
            name = data?.name;
        }

        return name == null
            ? req.CreateResponse(HttpStatusCode.BadRequest, "Please pass a name on the query string or in the request body")
            **:req.CreateResponse(HttpStatusCode.OK, "Hello" + name);**

    }
}

}
Second File: DBConnector.cs
using System;
using System.Data.SqlClient;

public class DBConnector
{
    public DBConnector()
    {
        SqlConnection getalertsConnection = new SqlConnection("Server=tcp:xxxxxxxxx.database.windows.net,1433;Initial Catalog=mckMobileAppsDB;Persist Security Info=False;User ID=xxxxxxx;Password=xxxxxxxx;MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30;");
        SqlCommand cmd = new SqlCommand();
        SqlDataReader reader;

        cmd.CommandText = "SELECT Date_Created As Date, Incident_Number AS Incident, Flash_Summary AS Summary, Service, Business_Impact AS Impact, Incident_Status AS Status from OutagesMobileAppNotifications FOR JSON PATH, Root('Alerts')";
        cmd.CommandType = CommandType.Text;
        cmd.Connection = getalertsConnection;

        getalertsConnection.Open();

        reader = cmd.ExecuteReader();
        // Data is accessible through the DataReader object here.

        getalertsConnection.Close();
    }
}

A: You're question is phrased a little awkwardly, plus the bad formatting doesn't help.  However, it looks as though you want to return JSON from an Azure Serverless Function.  Based on this assumption I'll try to answer.
To return JSON you will want to add the Newtonsoft.Json package.  This is simple, at the top of your function add the following:
#r "Newtonsoft.Json"
using System.Net;
using System.Text;
using Newtonsoft.Json;
using System.Linq;

(Edit: Added using statement for System.Linq so the Select is available for the data reader.)
In the DBConnector you wrote I would convert the reader to an array of objects and then serialize that result to JSON. (I have truncated your list of fields to jsut 2 for brevity... you'll obviously need to add the whole list.)
var incidents = dataReader.Select(m => new { m.Date, m.Incident }).ToList();
var jsonResult = JsonConvert.SerializeObject(incidents, Formatting.Indented);

Then return the JSON.
return new HttpResponseMessage(HttpStatusCode.OK) {
    Content = new StringContent(jsonResult, Encoding.UTF8, "application/json")
};

(I am trying to do this from memory... and I haven't done Azure Functions in about a year... so the exact code may differ.)
Additionally... since you haven't worked with C# in a while and maybe never with Azure Functions, it might be more simple to keep everything in the same function.  By this I mean you don't have to have the second class/file... you can just put all the SQL work in your main method.  I would normally consider this a bad practice, but in the short term it might ease your efforts.


text:
Q: Cant get wifi drivers to work I'm trying to get the wifi drivers for my laptop to work on Ubuntu 18.04. I followed steps to install them, but the settings still say "No WiFi adapter found. Make sure you have a wifi driver turned on. Bluetooth does work though after installing the drivers.
Running dmesg | grep iwl returns me this:
dmesg | grep iwl
[   16.154000] iwlwifi 0000:00:14.3: loaded firmware version 38.c0e03d94.0 op_mode iwlmvm
[   16.166883] iwlwifi 0000:00:14.3: Detected Intel(R) Dual Band Wireless AC 9560, REV=0x318
[   16.217152] iwlwifi 0000:00:14.3: base HW address: 18:1d:ea:5e:58:94
[   16.286771] ieee80211 phy0: Selected rate control algorithm 'iwl-mvm-rs'
[   16.287614] iwlwifi 0000:00:14.3 wlp0s20f3: renamed from wlan0

and lspci -knn | grep Net -A3; rfkill list returns this
00:14.3 Network controller [0280]: Intel Corporation Wireless-AC 9560 [Jefferson Peak] [8086:a370] (rev 10)
    Subsystem: Intel Corporation Device [8086:0034]
    Kernel driver in use: iwlwifi
    Kernel modules: iwlwifi
0: hci0: Bluetooth
    Soft blocked: no
    Hard blocked: no
1: ideapad_wlan: Wireless LAN
    Soft blocked: yes
    Hard blocked: yes
2: ideapad_bluetooth: Bluetooth
    Soft blocked: no
    Hard blocked: yes
3: phy0: Wireless LAN
    Soft blocked: yes
    Hard blocked: no

Does anyone have a clue what I'm doing wrong? Thank you in advance!


text:
Q: mysqli_fetch_assoc error when trying to select WooCommerce values from database I am currently making a WordPress plugin and trying to select a few values from WooCommerce database and all I keep getting is the same error. What might be wrong?
My Code:
function prntPage()
{
    //Connect is defined somewhere else
    $query = "SELECT * FROM `wp_woocommerce_order_items`";
    $result = mysqli_query($conn,$query);
     while($row = $result->mysqli_fetch_assoc()) {
        echo "id: " . $row["order_item_id"]. " - Product Name: " . $row["order_item_name"]. " - Order_ID" . $row["order_id"]. "
";
    }
}

The Error:

Fatal error: Uncaught Error: Call to undefined method mysqli_result::mysqli_fetch_assoc() in C:\xampp\htdocs\ExamenProject\wp-content\plugins\drukkebaasjes-sizedata\drukkebaasjes-sizedata.php:54 Stack trace: #0 C:\xampp\htdocs\ExamenProject\wp-includes\class-wp-hook.php(286): prntPage('') #1 C:\xampp\htdocs\ExamenProject\wp-includes\class-wp-hook.php(310): WP_Hook->apply_filters('', Array) #2 C:\xampp\htdocs\ExamenProject\wp-includes\plugin.php(453): WP_Hook->do_action(Array) #3 C:\xampp\htdocs\ExamenProject\wp-admin\admin.php(224): do_action('toplevel_page_p...') #4 {main} thrown in C:\xampp\htdocs\ExamenProject\wp-content\plugins\drukkebaasjes-sizedata\drukkebaasjes-sizedata.php on line 54

A: With Wordpress there is the WPDB class and methods for that purpose. Try the following instead:
function prntPage() {
    global $wpdb;

    // The SQL query
    $results = $wpdb->get_results("SELECT * FROM {$wpdb->prefix}woocommerce_order_items");

    // Loop though rows data
    foreach( $results as $row ){
        echo "id: " . $row->order_item_id . " - Product Name: " . $row->order_item_name . " - Order_ID" . $row->order_id . "
";
    }
}

This function code works without error now.