text:
Q: Python Gurobi MIP for location routing problem I am trying to program a location routing problem in Python using Gurobi. Somehow the solution is always zero - do you see what is wrong with my code? Help is much appreciated
Situation: I have a set of depot locations, a set of depot capacitites, a set of vehicles and a set of customers. At each location, I need to decide whether to open a depot or not, and if yes, which capacity should I choose. Each customer has to be visited by a vehicle tour.
Mathematical modell
import gurobipy as gp
from gurobipy import GRB
from scipy.spatial import distance_matrix
import numpy as np
import pandas as pd
import time
# input parameters

depots_fixedCost = pd.read_excel("Depots_Parameters.xlsx", sheet_name="Fixed_cost", index_col=0) #opening cost
depots_fixedCost = depots_fixedCost.to_numpy()

depots_inboundCost = pd.read_excel("Depots_Parameters.xlsx", sheet_name="Inbound_cost", index_col=0) #inbound cost
depots_inboundCost = depots_inboundCost.to_numpy()

depots_ordercost = pd.read_excel("Depots_Parameters.xlsx", sheet_name="Picking_cost", index_col=0) #processing cost per order at each location
depots_ordercost = depots_ordercost.to_numpy()

depots_capacity = pd.read_excel("Depots_Parameters.xlsx", sheet_name="Capacity", index_col=0) #number of customers per facility
num_capacity = len(depots_capacity.columns)
depots_capacity = depots_capacity.to_numpy()

depots_coords = pd.read_excel("Depots_Parameters.xlsx", sheet_name="Coords", index_col=0)
num_locations = len(depots_coords)

customers = pd.read_excel("Coordinates_Customers.xlsx", sheet_name="Exact_5",index_col=0)
num_customers = len(customers)

vehicles = len(customers)
vehicle_capacity = 5

all_coords = np.vstack((depots_coords, customers))
num_coords = len(all_coords)
distance = distance_matrix(all_coords, all_coords) #distance matrix with Euclidean distances
cost_per_distance = 1

shipping_cost =cost_per_distance*distance

start_time_total = time.process_time()

m = gp.Model("LRP_exact")

# Create variables
y = {} #if depot j and location i is open or not
for i in range(num_locations):
    for j in range(num_capacity):
        y[i,j] = m.addVar(vtype=GRB.BINARY, obj=depots_fixedCost[i][j]+depots_inboundCost[i][j], name='y(' + str(i) + ',' + str(j) + ')')

z = {} #if customer k is assigned to location j or not
for i in range(num_locations, num_locations+num_customers):
    for j in range(num_locations):
        for k in range(num_capacity):
            z[i,j,k] = m.addVar(vtype=GRB.BINARY, obj=depots_ordercost[j][k], name='z(' + str(i) + ',' + str(j)  + ',' + str(k)+ ')')

x = {} #if vehicle k travels from i to j
for i in range(num_customers + num_locations):
    for j in range(num_customers + num_locations):
        for k in range(vehicles):
            x[i,j,k] = m.addVar(vtype=GRB.BINARY, obj=shipping_cost[i][j], name='x(' + str(i) + ',' + str(j)  + ',' + str(k)+ ')')

s = {} #for subtour elimination
for i in range(num_locations, num_locations+num_customers):
    s[i] = m.addVar()

# each customer is assigned to 1 tour
for i in range(num_locations, num_locations+num_customers):
    m.addConstr(sum(x[i,j,k] for j in range(num_locations+num_customers) for k in range(vehicles)) == 1)

# at each location only 1 depot can be built
for i in range(num_locations):
    m.addConstr(sum(y[i,j] for j in range(num_capacity)) <= 1)

#each vehicle starts at most from one depot (single tour)
for k in range(vehicles):
    m.addConstr(sum(x[i,j,k] for i in range(num_locations) for j in range(num_locations, num_locations+num_customers)) <= 1)

#each vehicle tour includes a depot
m.addConstr(sum(x[i,j,k] for i in range(num_locations) for j in range(num_locations+num_customers) for k in range(vehicles)) >= 1)

#each vehicle that delivers to a customer/depot also leaves the customer/depot
for i in range(num_locations+num_customers):
    for k in range(vehicles):
        m.addConstr(sum(x[i,j,k] for j in range(num_locations+num_customers)) == sum(x[j,i,k] for j in range(num_locations+num_customers)))

#depot and customer have to be on the same route if customer allocated to depot
for i in range(num_locations, num_locations+num_customers):
    for j in range(num_locations):
        for k in range(vehicles):
            m.addConstr((sum(x[i,h,k] for h in range(num_locations+num_customers)) + sum(x[j,h,k] for h in range(num_locations+num_customers))) <= (1 + sum(z[i,j,n] for n in range(num_capacity))))

#customer demand allocated to each depot is less or equal to the capacity of the depot and customer can only be allocated to an open depot
for j in range(num_locations):
    for k in range(num_capacity):
        m.addConstr(sum(z[i,j,k] for i in range(num_locations, num_locations+num_customers)) <= depots_capacity[j][k] * y[j,k])

#max tour stops
for k in range(vehicles):
    m.addConstr(sum(x[i,j,k] for i in range(num_locations, num_locations+num_customers) for j in range(num_customers + num_locations)) <= vehicle_capacity)
    # m.addConstr(sum(distance[i, j] * x[i, j, k] for i in range(num_customers) for j in range(num_customers)) <= time)

#Subtourelimination
for i in range(num_locations, num_locations+num_customers):
    for j in range(num_locations, num_locations+num_customers):
        if i != j:
            m.addConstr(s[i] - s[j] + num_customers * sum(x[i, j, k] for k in range(vehicles)) <= num_customers - 1)

# only 1 depot can be built
#m.addConstr(sum(y[i,j] for i in range(num_locations) for j in range(num_capacity)) <= 1)

# m.Params.TimeLimit=60
# m.Params.MIPGap=0.1

m.optimize()

end_time_total = time.process_time()
timer_total = end_time_total - start_time_total

print("Objective: " + str(m.objVal))


text:
Q: People Search not updating Job Title? I ran an incremental User Profile Synchronization which correctly updated the user's Job Title (verified in Manage User Profiles). I then ran an incremental search crawl on the MySite (sps3://mysite). However, People Search results still show the old job title. I then ran a full search crawl on the MySite and the old job title is still shown.
What could be going wrong here?

A: Stupidly, I was crawling the old SharePoint 2010 MySite, not the new 2013 MySite.

redpajama_set_name: RedPajamaStackExchange


text:
Q: JavaFX WebView prevent redirects I have a webview loaded a URL, and I want to user dont be able to redirect from there, when they click in a link, "a href", it should just ignores it.
Already tried every single listener on the webengine, and nothing seems to work.
Tried with the DOM hook, but it doesnt seems to work, also tried this code:
sectionWebView3.getEngine().locationProperty().addListener(new ChangeListener<String>() {
               @Override public void changed(ObservableValue<? extends String> prop, final String before, final String after) {
                    Platform.runLater(new Runnable() {
                         @Override public void run() {
                              WebEngine vEngine = sectionWebView3.getEngine();
                              if (after == null || vEngine.getLocation().contains("editor.html")) {
                                   //System.out.println("BrowserPane.ChangeListener cancelling " + vEngine.getLocation());
                                   vEngine.getLoadWorker().cancel();
                              }
                         }
                    });
               }
          });

the cancel(); get called, but doesnt work, it just keeps loading...

A: You might try to wait for the load finished event, and then get the document from the WebEngine by calling sectionWebview3.getEngine().getDocument(). Once you have this, get all the anchor tags by calling doc.getElementsByTagName('a').
Once you have that list, you can iterate over it and set the href attribute of the anchor nodes to "#".


text:
Q: Tesseract.js hangs in console Problem: I have a very simple script using tesseract.js locally (which getting to work was a pain of its own), and when i run the function, it logs my text and hangs without ever moving onto anything after the tesseract function.
var Tesseract   = require('tesseract.js');
Tesseract.workerOptions.langPath = './eng.traineddata';

function parseImg(img){
  Tesseract.recognize(img)
.then(result => console.log(result.text))
};

parseImg('./undefined.jpeg')

The function does work, and it does log the text from my image, but i cant figure out how to break from the function. Any guidance would be greatly appreciated!

A: /*
For anyone else who may have this problem...
I found the answer to my own question in the github
examples
for Tesseract.js
*/

var Tesseract   = require('tesseract.js');
Tesseract.workerOptions.langPath = './eng.traineddata';

function parseImg(img){
  Tesseract.recognize(img)
    .then(result =>{
        console.log(result.text)
        //This guy right here
        process.exit()
    })
};

parseImg('./undefined.jpeg')

/*
Years later, but with new knowledge comes new solutions.
Figured i would update this the way i would have done it
now.
*/

import Tesseract from 'tesseract'
Tesseract.workerOptions.langPath = './eng.traineddata';

async function parseImg(){
    const result = await Tesseract.recognize(img);
    console.log(result)
    return result
}parseImg().catch(e){console.error(e.stack)}

A: In your then (or better yet a finally) block you just need to add Tesseract.terminate();


text:
Q: Linear Dependence Lemma This is out of my textbook, Axler's "Linear Algebra Done Right" which I am self-studying from. (I organized my thoughts in which I would like some sort of response with Roman Numerals).
Linear Dependence Lemma: If $(v_{1},\ldots,v_{m})$ is linearly dependent in $V$ and $v_{1} \neq 0$, then there exists $j \in \{2,\ldots,m\}$ such that the following hold:
(a) $v_{j} \in span(v_{1},\ldots,v_{j-1})$;
(I. Why does this need to be justified? Is it because $v_{j}$ is an "extra" vector, which would make this arbitrary set of linear combinations dependent?).
(b) If the $j^{th}$ term is removed from $(v_{1},\ldots,v_{m})$, the span of the remaining list equal $span(v_{1},\ldots,v_{m})$.
(II. My assumption is that this basically means that if we remove this extra vector, then we still have the same list of linear combinations).
(I also found the following proof a bit confusing and need some clarification).
PROOF: Suppose $(v_{1},\ldots,v_{m})$ is linearly dependent in $V$ and $v_{1} \neq 0$. Then there exists $a_{1},\ldots,a_{m} \in \mathbb{F}$, not all $0$ such that $$a_{1}v_{1}+\cdots+a_{m}v_{m} = 0$$.
(So far so good, from what I know, this is just stating the opposite of Linear Independence, where the only choice of $a_{1},\ldots,a_{m} \in \mathbb{F}$ that satisfies $a_{1}v_{1}+\cdots+a_{m}v_{m} = 0$  is $a_1 =\cdots= a_{m} = 0$)
CONT: Not all of $a_{2},a_{3},\ldots,a_{m}$ can be $0$ (because $v_1 \neq 0)$. Let $j$ be the largest element of $\{2,\ldots.,m\}$ such that $a_{j} \neq 0$. Then  $$ v_{j} = -\frac{a_1}{a_j}v_1 - \cdots - \frac{a_{j-1}}{a_j}v_{j-1} ,$$
proving (a).
(III. I will fill in the extra steps here because I feel that I may have the right idea).
$Span(v_{1},\ldots,v_{m}) = 0$ for $j \in \{2,\ldots,m\} = a_{1}v_{1} + \cdots + a_{j}v_{j} = 0$.
Here I just solved for $v_j$, and got the result  $v_{j} = -\frac{a_1}{a_j}v_1 - \cdots - \frac{a_{j-1}}{a_j}v_{j-1} ,$ which corresponds to the above. $a_{j} \neq 0$ because we have $a_j^{-1}$ for each term, and $v_1 \neq 0$ because if we have $a_{1}v_{1}+\cdots+a_{j}v_{j} = 0$ then all the scalars $a_{2},\ldots,a_{m} \in \mathbb{F}$ could be equal to $0$, if that was the case. I think I have an idea, but how exactly does this prove that $v_j$ is contained in the span of $(v_{1},\ldots,v_{j-1})$? Is it because $ -\frac{a_1}{a_j}v_1 - \cdots - \frac{a_{j-1}}{a_j}v_{j-1}$, is just a linear combination of vectors that is equal to $v_j$?
CONT: to prove (b), suppose that $u \in span(v_{1},\ldots,v_{m})$. Then there exists $c_{1},\ldots,c_m \in \mathbb{F}$ such that $$u = c_1v_1 + \cdots + c_mv_m$$.
In the equation above, we replace $v_j$ with the right side of 2.5, which shows that $u$ is in the span of the list obtained by removing the $j^{th}$ term from $(v_1,\ldots,v_m)$. Thus (b) holds. $\Box$
(IV. So how exactly does this work? I find this part the most confusing).
Sorry that this is such a long list, but I really want to fully understand everything I am learning, and I am pretty new to proving stuff, so I want to make sure that I improve that skill as well.

A:
I. Why does (a) need to be justified

Because every claim made needs to be. The essence of (a) is that if there is a linear dependence, then there is a specific index $j$ such that the blame of linear dependence can be given to $v_j$, for its failing to be independent of its predecessors. A different way to prove this is to consider the list of sequences $()$, $(v_1)$, $(v_1,v_2)$, $\ldots$, $(v_1,v_2,\ldots,v_m)$; since the first one is linearly independent and the last one is linearly dependent (by assumption) there must be a first one in the list the is linearly dependent; if this is $(v_1,\ldots,v_j)$ then one can show $v_j\in span(v_1,\ldots,v_{-1})$. The argument is similar to the proof given in the text (a linear dependence relation among $(v_1,\ldots,v_j)$ must involve $v_j$ with nonzero coefficient). An advantage of this approach is that it does not depend essentially on any choice (the linear dependency taken is unique up to a scalar multiple) and it puts the blame on the very first $v_j$ that causes linear dependence.

II. My assumption is that (b) basically means that if we remove this extra vector, then we still have the same list of linear combinations.

More precisely, the removal of $v_j$ does not affect the set of vectors that can be written as linear combinations, even though the linear combinations themselves look different (since $v_j$ is no longer allowed to appear).

III. I will fill in... $span(v_{1},\ldots,v_{m}) = 0$ for $j \in \{2,\ldots,m\} = a_{1}v_{1} + \cdots + a_{j}v_{j} = 0$.
  Here I just solved for $v_j$, and got the result  $v_j = -\frac{a_1}{a_j}v_1 - \cdots - \frac{a_{j-1}}{a_j}v_{j-1} ,$ which corresponds to the above. $a_{j} \neq 0$ because we have $a_j^{-1}$ for each term,

You've got that a bit backwards. You could only solve for $v_j$ under the assumption $a_j\neq0$; you cannot conclude that from the fact that you just solved for $v_j$.

and $v_1 \neq 0$ because if we have $a_{1}v_{1}+\cdots+a_{j}v_{j} = 0$ then all the scalars $a_{2},\ldots,a_{m} \in \mathbb{F}$ could be equal to $0$, if that was the case.

This is doubly beside the point. $v_1\neq0$ is given, you don't need to prove that. On the other hand there is nothing absurd in the scalars $a_{2},\ldots,a_{m} \in \mathbb{F}$ all being equal to $0$, except that the text had just proved it is not the case using the fact that $v_1\neq0$. But the author could have avoided the whole mess about $v_1$ by observing that $span()=\{0\}$.

I think I have an idea, but how exactly does this prove that $v_j$ is contained in the span of $(v_{1},\ldots,v_{j-1})$? Is it because $ -\frac{a_1}{a_j}v_1 - \cdots - \frac{a_{j-1}}{a_j}v_{j-1}$, is just a linear combination of vectors that is equal to $v_j$?

Precisely.

In the equation above, we replace $v_j$ with the right side of 2.5, which shows that $u$ is in the span of the list obtained by removing the $j^{th}$ term from $(v_1,\ldots,v_m)$. Thus (b) holds. $\Box$
IV. So how exactly does this work?

If you write down a linear combination of $v_1,\ldots,v_m$ it contains a single occurrence of $v_j$. If you replace that occurrence (within parentheses, as it gets multiplied by a scalar) by the right hand side of 2.5, then there is no longer any occurrence of $v_j$. You don't directly get a linear combination of the remaining $v_i$, but once you work out the multiplication and collect like terms, you do get such a linear combination. For instance if $v_3=-5v_1+\frac32v_2$ then
$$\begin{align}
  av_1+bv_2+cv_3+dv_4
&= av_1+bv_2+c(-5v_1+\frac32v_2)+dv_4
\\&= av_1+bv_2-5cv_1+\frac32cv_2+dv_4
\\&= (a-5c)v_1+(b+\frac32c)v_2+dv_4.
\end{align}
$$


text:
Q: Could not locate the assembly "Microsoft.Expression.Drawing" in a WPF solution I attempt to open and build a WPF solution in Visual Studio 2022. However, I get this build error:

Could not resolve this reference. Could not locate the assembly "Microsoft.Expression.Drawing". Check to make sure the assembly exists on disk. If this reference is required by your code, you may get compilation errors.

A similar issue has been posted before regarding Microsoft.Expression.Interactions here. However, how can I resolve the issue for Microsoft.Expression.Drawing? I've installed the Microsoft.Xaml.Behaviors.Wpf NuGet package.

A: The new Microsoft.Xaml.Behaviors.Wpf NuGet package replaces the System.Windows.Interactivity types that were shipped as part of Blend. It does not provide Microsoft.Expression.Drawing types.
The expression blend assemblies are deprecated and not shipped anymore. The Blend for Visual Studio SDK for .NET could be installed until Visual Studio 2017 and found here:
C:\Program Files (x86)\Microsoft SDKs\Expression\Blend\.NETFramework\v4.0\Libraries
C:\Program Files (x86)\Microsoft SDKs\Expression\Blend\.NETFramework\v4.5\Libraries

You could download Visual Studio 2017 (Community is sufficient) and install it from there.
The original Blend SDK was still provided by Microsoft for download as standalone about a year or two ago, but now all the links are dead. Fortunately, there is a snapshot on Wayback Machine where you can reach the original download.
Other than that there are only unofficial sources like these NuGet packages:

*

*Expression.Blend.Sdk.WPF

*Microsoft.SDK.Expression.Blend
If you can, please stick to the original SDK, since unofficial packages may contain any code, including malware. They might impose a security risk or contain assemblies not allowed for redistribution.


text:
Q: Is there a way to save a list using Windows.Storage.ApplicationData with a foreach loop in a UWP app? I am making a UWP app where I want to save the contents of a listbox when the user closes the application. I believe (although I may be wrong) that the best way to do this is by adding the contents of a listbox to a     list    .  However, given the constraints of UWP, I can't use StreamWriter to save whatever variables I wish to save, which would allow me to do so easily.  So, I am using     StorageFolder.GetFileAsync.
While this is all well and good for saving a few variables, when the amount of variables I would like to save is not predetermined (i.e; a list) I'm not sure how to go about doing so.
private async void btnAdd_Click(object sender, RoutedEventArgs e)
        {
            Windows.Storage.StorageFolder storageFolder =
            Windows.Storage.ApplicationData.Current.LocalFolder;
            Windows.Storage.StorageFile databaseFile = await
            storageFolder.CreateFileAsync("database.txt",
            Windows.Storage.CreationCollisionOption.ReplaceExisting);

            string databaseItem;
            string databaseName;
            double databaseFat;
            double databaseCarbs;
            double databaseProtein;
            string servingSize;

            txtNameDatabase.Text = txtCaloriesDatabase.Text = txtFatDatabase.Text = txtCarbsDatabase.Text = txtProteinDatabase.Text = txtServingSize.Text = "";
            int databaseCalories;

            ContentDialogResult databaseResult = await databaseContentDialog.ShowAsync();
            bool contentDialogError = false;

            if (databaseResult == ContentDialogResult.Primary)
            {
                try
                {
                    databaseName = txtNameDatabase.Text;
                    databaseCalories = Convert.ToInt32(txtCaloriesDatabase.Text);
                    databaseFat = Convert.ToDouble(txtFatDatabase.Text);
                    databaseCarbs = Convert.ToDouble(txtCarbsDatabase.Text);
                    databaseProtein = Convert.ToDouble(txtProteinDatabase.Text);
                    servingSize = txtServingSize.Text;

                    if (contentDialogError == false)
                    {

                        databaseItem = databaseName + ": " + databaseCalories + " Calories, " + databaseFat + "g Fat, " + databaseCarbs + "g Carbs, " + databaseProtein + "g Protein, Serving Size: " + databaseProtein;
                        foodDatabaseList.Add(databaseItem);
                        lstFoodDatabase.Items.Add(foodDatabaseList[0]);
                    }
                }
                catch
                {
                    var msgContentDialogError = new MessageDialog("Please only enter whole numbers into the calories field and decimal numbers into the macronutrient fields.");
                    await msgContentDialogError.ShowAsync();
                }
                foreach (string line in lstFoodDatabase.Items)
                {
                    await Windows.Storage.FileIO.WriteTextAsync(databaseFile, line);
                }
            }
        }

private async void Page_Loaded(object sender, RoutedEventArgs e)
        {
            Windows.Storage.StorageFolder storageFolder = Windows.Storage.ApplicationData.Current.LocalFolder;
            Windows.Storage.StorageFile databaseFile = await storageFolder.GetFileAsync("database.txt");

            string test = await Windows.Storage.FileIO.ReadTextAsync(databaseFile);
            lstFoodDatabase.Items.Add(test);

        }

I tried using a foreach loop to save each item in the listbox, but when I try to read it off, I only get the last item that was saved.

A: When you want to save some structured data, there are usually two ways.
The first one is the database, but this method may not be suitable for your situation.
The second is to store the data as serializable text, such as JSON.
As you can see from your code, your foodDatabaseList is a List<string>, we will start here.
Before that, you need to install the Newtonsoft.Json nuget package.
StorageFolder storageFolder = ApplicationData.Current.LocalFolder;
StorageFile databaseFile = await storageFolder.CreateFileAsync("database.txt", CreationCollisionOption.ReplaceExisting);

// Data loading

// List serialization
string serialization = JsonConvert.SerializeObject(foodDatabaseList);
// Save them
await FileIO.WriteTextAsync(databaseFile, serialization);

If you need to read them
Windows.Storage.StorageFolder storageFolder = Windows.Storage.ApplicationData.Current.LocalFolder;
Windows.Storage.StorageFile databaseFile = await storageFolder.CreateFileAsync("database.txt", CreationCollisionOption.OpenIfExists);

string test = await FileIO.ReadTextAsync(databaseFile);

List<string> localItems = JsonConvert.DeserializeObject<List<string>>(test);

foreach (var item in localItems)
{
    lstFoodDatabase.Items.Add(item);
}

Best regards.


text:
Q: Term for realistic fictional documentation, artifacts, tools I'm imagining contextual details in a fantasy fiction setting like technical drawings of alien plants, diagrams of demon physiology, guidelines for communicating with inter dimensional beings. I suppose you see it a lot with occult fiction (finding information in dense intricate tomes,performing precise rituals, etc) and in fantasy where the author establishes realism by conceiving of the types of things you might find in a scholar's library in that setting.
Is there a general term for that type of documentation of a certain lore, mythos, or any body of knowledge (whether or not connoting fictional contents)? "Marginalia" has the spirit of what I'm imagining.

A: Generally "world" or "universe" is suffixed to another word in your case scenario. e.g. "alien-world", "world-of-warcraft", "JRR Tolkien Universe", "MCU(Marvel comic universe)".
I am imagining you are searching for a term which is a general term for these fictional worlds/universes. Supposing XXXX is such a word, and you can say the following sentences

*

*JRR Tolkien created XXXX

*Marvel franchise created XXXX

A few candidate words are out there

*

*Altverse(Verse and Dimensions Wikia) (Alternate Universe)(Even in a created world universe, it may be an alternate version of the canonical (so to say) version and can be used for both)

*Converse(Converse Wiki) (Constructed Universe)(It does not help that 1. converse is an actual word with a different meaning, 2. Converse is a well known apparel, sports brand)(Hyphenated Con-Verse may be usable)

*Conworld or Con-world(Wiktionary) (Constructed World)(Has entered dictionaries)

*paracosm(Wiktionary) (May not serve your purpose)

*Fiction/al world/universe are also acceptable.

Conlang(Wiktionary) is constructed language, conculture(Wiktionary) is constructed culture.


text:
Q: Typescript Decorators and Arrow Function I'm trying to implement a Typescript method decorator as follows.
function dataMethod(name: string, options: any) {
    return (target: any, propertyKey: string, descriptor: TypedPropertyDescriptor<any>) => {

    }
}

And its used as below.
class HelloWidgetExtesion {
    @dataMethod("getData", {})
    public getData(name: any, cb: any) {
        cb(null, "");
    }
}

But I'm trying to figure out how to use decorators with Arrow function implementation as below.
class HelloWidgetExtesion {
    @dataMethod("getData", {})
    public getData = (name: any, cb: any) => {
       cb(null, "Greetings from Loopback!");
    }
}

But the above implementation shows the following error when compiling.

error TS2322: Type '(target: any, propertyKey: string, descriptor:
  TypedPropertyDescriptor) => void' is not assignable to type
  '(target: Object, propertyKey: string | symbol) => void'.

Demo of the issues.

A: In the last case field getData is considered by compiler as property (not pure method).
This means that the descriptor arguments would not be passed in compiled javascript file.
All that you need it is modify your decorator and make descriptor field optional. Consider this example:
function dataMethod(name: string, options: any) {
    return (target: any, propertyKey: string, descriptor?: TypedPropertyDescriptor<any>) => {

    }
}

I have modified your example here
Good Luck
Related Resources (thanks for it @David Sherret)

*

*Decorators signature


text:
Q: c# ?. conditional operator I have a condition
if (driver?.VistrackId == 555)

it equivalent (in IL code, not C# code):
if (driver != null && driver.VistrackId == 555)

right?

A: Not exactly

It's better Since this notation is thread safe

See Null-conditional Operators on MSDN.

A: That's correct. The "?" checks for null, and if it's not null, the "." continues the interrogation of the object

A: This code generates the following IL
var driver = new {VistrackId = 1};

if (driver?.VistrackId == 555)
{
    Console.WriteLine("?. operator");
}

IL:
IL_0000:  nop
IL_0001:  ldc.i4.1
IL_0002:  newobj      <>f__AnonymousType0<System.Int32>..ctor
IL_0007:  stloc.0     // driver
IL_0008:  ldloc.0     // driver
IL_0009:  brtrue.s    IL_000E
IL_000B:  ldc.i4.0
IL_000C:  br.s        IL_001B
IL_000E:  ldloc.0     // driver
IL_000F:  call        <>f__AnonymousType0<System.Int32>.get_VistrackId
IL_0014:  ldc.i4      2B 02 00 00
IL_0019:  ceq
IL_001B:  stloc.1
IL_001C:  ldloc.1
IL_001D:  brfalse.s   IL_002C
IL_001F:  nop
IL_0020:  ldstr       "?. operator"
IL_0025:  call        System.Console.WriteLine
IL_002A:  nop
IL_002B:  nop
IL_002C:  ret

Code with == null
var driver = new {VistrackId = 1};

if (driver != null && driver.VistrackId == 555)
{
    Console.WriteLine("== null");
}

IL
IL_0000:  nop
IL_0001:  ldc.i4.1
IL_0002:  newobj      <>f__AnonymousType0<System.Int32>..ctor
IL_0007:  stloc.0     // driver
IL_0008:  ldloc.0     // driver
IL_0009:  brfalse.s   IL_001A
IL_000B:  ldloc.0     // driver
IL_000C:  callvirt    <>f__AnonymousType0<System.Int32>.get_VistrackId
IL_0011:  ldc.i4      2B 02 00 00
IL_0016:  ceq
IL_0018:  br.s        IL_001B
IL_001A:  ldc.i4.0
IL_001B:  stloc.1
IL_001C:  ldloc.1
IL_001D:  brfalse.s   IL_002C
IL_001F:  nop
IL_0020:  ldstr       "== null"
IL_0025:  call        System.Console.WriteLine
IL_002A:  nop
IL_002B:  nop
IL_002C:  ret

They are slightly different


text:
Q: error con DataReader (sql server y c#) muy buenas, estoy creando una aplicacion la cual necesita una coneccion con una base de datos sql server.
al  compilar mi codigo la conección con sql server funciona, pero cuando llega al sqldatareader sale un error (must declare the scalar variable)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Data.SqlClient;
using System.Data.SqlTypes;
using Ins_Med_WPF.pages;
using System.Data;

namespace Ins_Med_WPF.pages
{
    /// <summary>
    /// Lógica de interacción para admin_login.xaml
    /// </summary>
    public partial class admin_login : Page
    {
        public admin_login()
        {
            InitializeComponent();
        }

        public string id_admin { get; set; }
        public string contraseña { get; set; }
        private void btniniciosesion_Click(object sender, RoutedEventArgs e)
        {
            SqlConnection conexion = new SqlConnection("server=DESKTOP-5REI37J ;database=insmed2.0;integrated security =true");
            conexion.Open();
            MessageBox.Show("funciono");
            string cadena = "select id_admin, contraseña from ADMINISTRADOR where id_admin= + @idusuario";
            SqlCommand comando = new SqlCommand(cadena, conexion);
            comando.Parameters.Add("@id_admin", SqlDbType.Int);
            comando.Parameters["@id_admin"].Value = int.Parse(idusuario.Text);
            SqlDataReader registros = comando.ExecuteReader();

            string cadena2 = "select  contraseña from ADMINISTRADOR where id_admin=" + contraseñal;
            SqlCommand comando2 = new SqlCommand(cadena, conexion);
            SqlDataReader registro2 = comando.ExecuteReader();

            if (registros.Read() && registro2.Read())
            {
                NavigationService.Navigate(new admin_panel());
            }
            else
            {
                MessageBox.Show("error");
            }

        }
    }
}

este es el error

quien me pueda ayudar se lo agradeceria muchisimo.
no se que mas escribir, la pagina me pide que añada mas detalles pero creo que eso es todo asi que este parrafo solo es para rellenar.

A: En la consulta el parámetro es @idusuario, ese mismo se debe asignar con Parameters.Add()
string cadena = "select id_admin, contraseña from ADMINISTRADOR where id_admin =  @idusuario";
// el parámetro es @idusuario y su valor es idusuario.Text
comando.Parameters.Add("@idusuario", idusuario.Text);


text:
Q: i3wm floating windows won't automatically center When using pycharm the floating windows for "Commit" or "Push" spawn a bit off-screen, so I have to manually center them. I tried to automatically center them with the directive for_window; however, I wasn't able to match the windows. Here are the configs I tried:
# These don't work
for_window [window_type="DIALOG"] move position center
for_window [floating] move position center
for_window [window_type="dialog"] move position center
for_window [name="Commit Changes"] move position center

# This works
bindsym $mod+c move position center

Also, the relevant output of xprop:
_NET_WM_DESKTOP(CARDINAL) = 3
WM_STATE(WM_STATE):
        window state: Normal
        icon window: 0x0
I3_FLOATING_WINDOW(CARDINAL) = 1
_NET_WM_USER_TIME(CARDINAL) = 5048004
_NET_WM_WINDOW_TYPE(ATOM) = _NET_WM_WINDOW_TYPE_DIALOG

WM_PROTOCOLS(ATOM): protocols  WM_DELETE_WINDOW, WM_TAKE_FOCUS
WM_CLASS(STRING) = "jetbrains-pycharm", "jetbrains-pycharm"
WM_CLIENT_LEADER(WINDOW): window id # 0x2c00008
_NET_WM_ICON_NAME(UTF8_STRING) = "Commit Changes"
WM_ICON_NAME(STRING) = "Commit Changes"
_NET_WM_NAME(UTF8_STRING) = "Commit Changes"
WM_NAME(STRING) = "Commit Changes"

Update:
Following a hint from reddit, I updated i3 to version 4.19.1-non-git. Though, the floating window still doesn't spawn centered. However, when I restart i3 (bindsym $mod+Shift+r restart), the window is centered.


text:
Q: Laravel logging email Is it possible to somehow see the email log from my Laravel application? I have a contact form and some emails might be lost since the wrong email-address was set for a while, so I want to know if I can see who tried to email me?

A: The logs are found in application/storage/logs and the file is called:

laravel.log

A: For the wrong or invalid email the laravel Email class throw an error, so you have to catch it by using error handling methods i.e. try and catch like:
try
{
    // Email sending logic here
}
catch (Exception $e) {
    // Exception is catched here
    Log::info('save all the required data here so that you can check it later');    // This will log all the detail that you have passed here
}

Later on you can check the log to get all such entries for which email is failed.
Laravel logs are found in application/storage/logs


text:
Q: Magento 2.0.0, very slow, paths not good I installed magento 2.0.0 on my computer. OS: Windows 10
I downloaded ZIP archive with sample data from:   https://www.magentocommerce.com/download. Also, followed installation instructions from their documentation, I ran composer install, and after that, the installation was complete, successfully.
Firstly, it is very, very slow. Is this common behaviour for my OS, and similar?
Also, there are lots of files, images, etc for which the path is not good, and GET returns HTTP 404. Am I missing something important here?

A: Problem solved, after running:
php bin/magento setup:static-content:deploy


text:
Q: Convert Doctrine 2 result object (entity) to array? I know that it is possible to specify that you want array type instead of object type when you run query with Doctrine. However, I happen to be working with the code that I can't edit which returns to me the result from a query as an object and I want to be able to convert that to array somehow. It seems like in the older version doctrine used to have something like toArray() which can be used.
Is there something similar to that now which I can use?

A: No, doctrine 2 uses the data mapper pattern and doesn't make any assumptions about the PHP class. If the class doesn't provide a toArray() method explicitly, then you'd need to create the array manually with the object's getter methods.


text:
Q: Millisecond time difference from Calendar too big I'm trying to compare two millisecond values in Java. One from a calendar, and one from System.currentTimeMillis(). However, it seems the value from the calendar is always far larger than the one from System.currentTimeMillis() at the correct time.
To build the calendar, I'm parsing a date string in the format dd/MM/yyyy HH:mm and putting it's consitutuent parts in to a calendar (try-catch omitted for brevity).
Calendar obCal = null;

//Exception here shows invalid format
DateFormat DF = new SimpleDateFormat("dd/MM/yyyy HH:mm");
DF.parse(Date);

//Example string: 29/11/2011 16:30
String[] parts = Date.split("/");

obCal = Calendar.getInstance();
int Y = Integer.parseInt(parts[2].split(" ")[0]);
int m = Integer.parseInt(parts[1]);
int d = Integer.parseInt(parts[0]);
int H = Integer.parseInt(parts[2].split(" ")[1].split(":")[0]);
int M = Integer.parseInt(parts[2].split(" ")[1].split(":")[1]);

obCal.set(Calendar.YEAR, Y);
obCal.set(Calendar.MONTH, m);
obCal.set(Calendar.DAY_OF_MONTH, d);
obCal.set(Calendar.HOUR_OF_DAY, H);
obCal.set(Calendar.MINUTE, M);
obCal.set(Calendar.SECOND, 0);
obCal.set(Calendar.MILLISECOND, 0);

Inspecting the calendar after this shows me it is receiving the correct date and time. I then get the millisecond value since the epoch from obCal.getTimeInMillis() and store it as a number of seconds as a long
long stamp = obCal.getTimeInMillis() / 1000L;

When I reach the time represented by the date string, and compare the timestamp from the calendar to timestamp System.currentTimeMillis(), I find the former is far larger. The difference between the current time and the calendar time (curTime-calTime) is, usually, somewhere in the region of -2,500,000
What could be causing this?
Thanks

A: Month is 0-based so when you do obCal.set(Calendar.MONTH, m); you're off by 1 month.

A: Most likely you missed that the Calendar API defines MONTH to be in range 0 to 11, while you parse it as 1 to 12. That makes a 30 * 86400 Second difference...


text:
Q: How to reference an excel sheet by variable I'm working on a code to reference an excel sheet by variable, however i'm stuck on the last step which is selecting the sheet according to the variable text which is the month abbreviation
It was the only way i could proceed to select the desired sheet based on the month index, any other help could be welcomed
    Dim DestWS1 As Worksheet
    Dim InputValue As Integer
    InputValue = InputBox("Please enter your month index number", "Selecting month index to generate your report")

    ' Print the name of the airport to the Immediate Window(Ctrl + G)

        Dim MonthIndexResult As String

        MonthIndexResult = _
        "=LOOKUP(" & InputValue & ",InputData!R3C17:R14C17,InputData!R3C16:R14C16)"

Set DestWS1 = ThisWorkbook.Sheets(" & MonthIndexResult & ")
DestWS1.Select

it was the only way i could proceed to select the desired sheet based on the month index, any other help could be welcomed

A: Look like you want to evaluate the formula in your code and read the output of that into a variable, then use that variable as the sheet name? If so then try the following:
    Dim DestWS1 As Worksheet
    Dim InputValue As Integer
    InputValue = InputBox("Please enter your month index number", "Selecting month index to generate your report")

    ' Print the name of the airport to the Immediate Window(Ctrl + G)

        Dim MonthIndexResult As String

        ' MonthIndexResult = _
        ' "=LOOKUP(" & InputValue & ",InputData!R3C17:R14C17,InputData!R3C16:R14C16)"
        MonthIndexResult = Application.Evaluate("=LOOKUP(" & InputValue & ",InputData!R3C17:R14C17,InputData!R3C16:R14C16)")

Set DestWS1 = ThisWorkbook.Sheets(MonthIndexResult)
DestWS1.Select

You can find out more about this method here: Application.Evaluate method (Excel)

A: Identify Worksheet By Partial Name
Sub SelectByMonth()

    Dim InputString As String
    InputString = InputBox("Please enter your month index number", _
        "Selecting month index to generate your report")
    If Len(InputString) = 0 Then Exit Sub ' no input

    Dim wb As Workbook: Set wb = ThisWorkbook ' workbook containing this code
    Dim sws As Worksheet: Set sws = wb.Sheets("InputData")
    Dim slrg As Range: Set slrg = sws.Range("Q3:Q14")
    Dim srrg As Range: Set srrg = sws.Range("P3:P14")

    Dim srIndex As Variant
    srIndex = Application.Match(CLng(InputString), slrg, 0)
    If IsError(srIndex) Then Exit Sub ' month (number) not found
    Dim sMonth As String: sMonth = srrg.Cells(srIndex)

    Dim dws As Worksheet

    For Each dws In wb.Worksheets
        If InStr(1, dws.Name, sMonth, vbTextCompare) > 0 Then Exit For
    Next dws

    If dws Is Nothing Then Exit Sub ' worksheet not foundd

    If Not wb Is ActiveWorkbook Then wb.Activate

    dws.Select

End Sub


text:
Q: Как эмулировать зажатие кнопки Ctrl? Сабж.
Делаю кликер, мне надо нажимать Ctrl+LMB.
Клик мышкой делаю так:
public void leftClick(Point p)
{
    Cursor.Position = p;
    Thread.Sleep(350);
    mouse_event((int)(MouseEventFlags.LEFTDOWN), 0, 0, 0, 0);
    mouse_event((int)(MouseEventFlags.LEFTUP), 0, 0, 0, 0);
}

A: Попробуй так
[DllImport("user32.dll")]
static extern bool SetCursorPos(int x, int y);

[DllImport("user32.dll")]
public static extern void mouse_event(int dwFlags, int dx, int dy, int cButtons, int dwExtraInfo);

[DllImport("user32.dll")]
public static extern void keybd_event(byte bVk, byte bScan, uint dwFlags, int dwExtraInfo);

private const int KEYEVENTF_KEYDOWN = 0x0000; // New definition
private const int KEYEVENTF_KEYUP = 0x0002; //Key up flag

public const int VK_LCONTROL = 0xA2;
public const int MOUSEEVENTF_LEFTDOWN = 0x02;
public const int MOUSEEVENTF_LEFTUP = 0x04;

    // This simulates a left mouse click
    public static void Ctrl_MouseLeft(int xpos, int ypos)
    {
        // Key Ctrl + Mouse Left
        keybd_event(VK_LCONTROL, 0, KEYEVENTF_KEYDOWN, 0);
        SetCursorPos(xpos, ypos);
        mouse_event(MOUSEEVENTF_LEFTDOWN, xpos, ypos, 0, 0);
        Thread.Sleep(100);
        mouse_event(MOUSEEVENTF_LEFTUP, xpos, ypos, 0, 0);
        keybd_event(VK_LCONTROL, 0, KEYEVENTF_KEYUP, 0);
    }

    static void Main(string[] args)
    {
        Thread.Sleep(3000);
        Ctrl_MouseLeft(x,y); // x, y Position mouse
    }


text:
Q: Is it possible to extraxt information about HOW a user defined function is being called? Or is it possible to capture the function call itself in any way (describe which values are assigned to the different arguments)?
Sorry for the poor phrasing of the question. Let me explain with some reproducible code:
import pandas as pd
import numpy as np
import matplotlib.dates as mdates
import inspect

# 1. Here is Dataframe with some random numbers
np.random.seed(123)
rows = 10
df = pd.DataFrame(np.random.randint(90,110,size=(rows, 2)), columns=list('AB'))
datelist = pd.date_range(pd.datetime(2017, 1, 1).strftime('%Y-%m-%d'), periods=rows).tolist()
df['dates'] = datelist
df = df.set_index(['dates'])
df.index = pd.to_datetime(df.index)
#print(df)

# 2. And here is a very basic function to do something with the dataframe
def manipulate(df, factor):
    df = df * factor
    return df

# 3. Now I can describe the function using:
print(inspect.getargspec(manipulate))

# And get:
# ArgSpec(args=['df', 'factor'], varargs=None, keywords=None,
# defaults=None)
# __main__:1: DeprecationWarning: inspect.getargspec() is
# deprecated, use inspect.signature() or inspect.getfullargspec()

# 4. But what I'm really looking for is a way to
# extract or store the function AND the variables
# used when the function is called, like this:
df2 = manipulate(df = df, factor = 20)

# So in the example using Inspect, the desired output could be:
# ArgSpec(args=['df = df', 'factor = 10'], varargs=None,
# and so on...

I realize that this may seem a bit peculiar, but it would actually be of great use to me to be able to do something like this. If anyone is interested, I'd be happy to explain everything in more detail, including how this would fit in in mye data science work-flow.
Thank you for any suggestions!

A: You can bind the parameters to the function and create a new callable
import functools
func = functools.partial(manipulate, df=df, factor=20)

the resulting partial object allows argument inspection and modification using the attributes args and keywords:
func.keywords  # {'df': <pandas dataframe>, 'factor': 20}

and and can finally be called using
func()


text:
Q: How to replace empty string with null value in oracle using nvl function INSERT INTO books(book_id, title, author_last_name, author_first_name, classify)
VALUES (1000, 'The Picture of Dorian Gray', 'Wilde', 'Oscar', 'fiction');
INSERT INTO books(book_id, title, author_last_name, author_first_name, classify)
VALUES (1001, 'Think Big', 'Carson', 'Dr. Ben', 'non - fiction');
INSERT INTO books(book_id, title, author_last_name, author_first_name, classify)
VALUES (1003, 'Mathematical Scandals', 'Pappas', ' ', 'non - fiction');
INSERT INTO books(book_id, title, author_last_name, author_first_name, classify)
VALUES (1004, 'SQL', 'Harris', 'Andy', 'non - fiction');
INSERT INTO books(book_id, title, author_last_name, author_first_name, classify)
VALUES (1010, 'Excel 2016', 'Chan', ' ', 'non - fiction');
commit;

here is the value of my table. in some records i have inserted empty string ''.
how to replace that empty string with NULL values using nvl function

A: This will replace the single whitespace strings with a NULL value:
UPDATE books
SET    author_first_name = NULL
WHERE  author_first_name = ' ';

Or, this will trim all the whitespace from the start and end of the names (and if an empty string is left then that is the same as a NULL value)
UPDATE books
SET    author_first_name = TRIM( author_first_name );

The NVL function is used to conditionally replace NULL values with another value - not the other way round so it is inappropriate to use it for this purpose.

A: The NVL function is used to replace NULL with some other value, not the reverse.
If you had actually entered an empty string, your question would be irrelevant.  In Oracle, there is no distinction between NULL and the empty string ''.
But it appears you've entered strings containing a single space, which is not the same as an empty string.
A simple update to replace these strings with NULL would be:
UPDATE books SET
  author_first_name = NULL
WHERE
  author_first_name = ' '


text:
Q: strcat with char from array in c This may be a silly question, but I'm struggling to solve this problem.
I know that to append a char to a string I can do something like this:
char c;
char string[10] = "";
strcat(string, &c);

Now, this works well for char variables, but the problem is that when I try to append a char from an array:
char array[5];
char string[10] = "";
strcat(string, &array[0]); //&array[0] returns the entire array, not just array[0]

Question: How can I append a single char from an array to a string?

A: You can use strncat().Here length is the number of characters you want to append to string
strncat(string, array, length);

For appending single character, use length = 1


text:
Q: Drag Composable only inside given boundries with Jetpack Compose so I have a black box (rectangle) inside another box (boundary) and the rectangle is set as draggable
But now I can drag the rectangle around the whole window, but I want that if the rectangle "leaves" the boundary it should disappear behind it.
Is there another modifier I can use for it?
Here a bit context:
My code looks like this:
MaterialTheme {
        Box(modifier = Modifier
            .size(500f.dp)
            .border(2f.dp, Color.Black, RectangleShape)
        ){
            Box(modifier = Modifier
                .offset { IntOffset(offsetX.roundToInt(), 0) }
                .draggable(
                    orientation = Orientation.Horizontal,
                    state = rememberDraggableState { delta ->
                        offsetX += delta
                    }
                )
                .background(Color.Blue)
                .size(100f.dp)
            ){
                Text("Hello")
            }
        }
    }

When I drag the rectangle outside the boundary it looks like this:

But it should more like this:

A: On the composable whose contents you want to clip add the clipToBounds() modifier.
Box(modifier = Modifier
    .size(500f.dp)
    .border(2f.dp, Color.Black, RectangleShape)
    .clipToBounds()
)


text:
Q: Will a failed WD external hard drive deteriorate further by sitting around? Sorry if this is not the right place to ask this - if anyone knows a better place kindly direct me.
My external hard drive is already failed: it spins up, my machine tries for 20-30 seconds to recognize it, then it clicks and the light goes out.
Past what period of time from initial failure would you guess that my chances of recovering my data (however good or slim to begin with) will drop significantly?

A: Years. No further harm will be done to your data unless you do one of the following:

*

*Connect power to the hard drive.

*Subject it to shock or vibration, e.g. in transport.

*Expose the drive to harmful environmental conditions such as extreme heat, moisture, humidity, electromagnetic fields.

*Disclose the drive's location to a hungry Seinfeld.

If the drive is stored safely, your data will deteriorate no more rapidly on a malfunctioning drive's platters than it would on an intact drive stored in the same way.

A: The second law of thermodynamics indicates that if you leave the drive sitting and do absolutely nothing with it, the signal on the platter will eventually degrade as the magnetic forces fade toward equilibrium. That process takes an unknown amount of time, but experience suggests that the longevity of the data tends to outlast its relevance.
That said, non-passive environmental factors such as heat and vibration can have a devastating  effect on data recoverability, particularly in the drive's current state where something may already be physically wrong with the drive, the situation tends to deteriorate more quickly. And more importantly, the data will not become easier to recover on its own than it is right now.
If the data is important enough to warrant the cost, then I would recommend sending the drive to a center where they can work around broken components to recover the data.


text:
Q: Can I mark a SD Card as permanent storage? I own a PNY - StorEDGE 128GB and I remember that it was initially recognized as a fixed/permanent disk like a hard disk.
I reformatted it to add encryption but now the disk is shown as a removable device. This keeps tools like SkyDrive from using it as a target.
Can I set the volume type somehow?

A: Yes! You can change the volume from a removable device to a fixed disk by flipping the removable bit. Lexar made an application for Windows called 'Lexar BootIt', a well known application for this task.
I found a solution involving DD, but I have not tested it and I'd severely recommend backing up your card before doing anything with DD/Terminal. I created these instructions quickly. If you aren't comfortable with Terminal, use Windows! I am not responsible if your SD card is permenantly damaged in this operation. dd is exceedingly dangerous!
Use diskutil list in a Terminal instance to list all volumes. I found my hard drive under /dev/disk1. Remember to substitute disk1 in the later commands with your own disk name.
Don't forget to unmount the disk:
hdiutil eject disk1

And now the command:
dd if=/dev/zero of=/dev/disk1 bs=1 count=1

Again, back up EVERYTHING before doing anything with dd!


text:
Q: Querying a database with oop I have connected to a database for the first time with oop and stright away come up with an issue, below is my code which i'm struggling with:
$q = 'SELECT * FROM test';
       $sqli->query($q);

       if($sqli->query($q)){
           echo "worked";
       }

       if($sqli->error){
           echo $sqli->error;
       }

I have checked for errors when connecting to the db and that works fine, but when I run this query I get no output, why? I expected an error or "worked", but have got neither.
Whats happening?

A: I have put some comments in the source code to help:
   $q = 'SELECT * FROM test';
   //$sqli is the result of a
   //new mysqli("localhost", "user", "password", "database");
   $resource = $sqli->query($q); // this returns a resource or false

   if(!$resource) {
       echo $sqli->error;
       die; // do not process further
   }

   // process the results
   $rows = $resource->fetch_all();
   if ($rows) {  // check if there are rows
     echo "worked";
   }
   else {
     echo "query is ok, but there are no rows";
   }

A: You could also use $resource->fetch_object() which returns an object for output.  Therefore if you wanted to print specific data from the result set,  you would do something like
//table test.Name and test.Country
while ($rowobj = $resource->fetch_object()){
          printf ("%s (%s)\n", $rowobj->Name, $rowobj->Country);
        }

Good luck,

A: You could use this method, I hope it's what you are looking for. You will need to define the DB first. Then you can connect in OOP and test the connection is true or exit();
Let me know if this works for you. You can also define the DB in an external file and just do an include(); towards the top of your script for any pages needing connection to the DB.
define("SERVER","IP Address");
define("USER","DB USERNAME");
define("PASSWORD","DB PASSWORD");
define("DATABASE","DB NAME");

// This is for connection
$mysqli = new mysqli(SERVER, USER, PASSWORD, DATABASE);
if ($mysqli->connect_errno) {
    echo "Connection to MySQL failed: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
    exit();
}


text:
Q: How to make the below condition fail by giving inputs through stdin void main()
{
   float x;
   while(scanf("%f",&x) != 0)
   printf("%f\n",x);
}

The above code takes input from stdin and keeps repeating it but how to end this? I know scanf can return EOF so if I add a check like
while(scanf("%f",&x) != EOF)

Which input from stdin can cause any of the above two condition to fail?
ctrl+d will make the program end but I want to know is there any specific input which can make this condition fail?

A: scanf function  returns  the  number  of  input items successfully scanned.
The  value  EOF  is  returned if the end of input is reached before either the  first  successful  conversion  or  a  matching  failure occurs.
In your program always it return 1. To prove see the code..
        #include<stdio.h>

          main()
          {
            int a;float x;
            while((a=scanf("%f",&x)) != 0)
            printf("%f %d\n",x,a);
          }

In this program a is always 1. Be cause only one value is scanned successfully.
a gets 2 for , if you scan two values.

A: Looking at linux manual pages:

scanf: These functions return the number of input items successfully matched and assigned, which can be fewer than provided for, or even zero in the  event of an early matching failure.

So, using your original program:
void main()
{
   float x;
   while(scanf("%f",&x) != 0)
   printf("%f\n",x);
}

That means that if you enter anything that is not convertible, will end your program. Try it and enter any letter and hit enter

A: Ctrl + D or Ctrl + Z,
Similar questions already asked before:
End of File(EOF) of Standard input stream (stdin)


text:
Q: What programming language is the most English-like? I'm mainly a Python programmer, and it is often described as being "executable pseudo-code".  I have used a little bit of AppleScript, which seems to be the most English-like programming language I have ever seen, because almost operators can be words, and it lets you use "the" anywhere (for example, this stupid example I just came up with:
set the firstnumber to 1
set the secondnumber to 2
if the firstnumber is equal to the secondnumber then
    set the sum to 5
end if

is a valid AppleScript program.  Are there any programming languages that are even more English-like than these?

A: At the risk of being a raging finger-wagger: I claim that natural-language-like is a bad goal for programming languages.  Specifically, the goal of a natural language utterance is to influence the world so that other human beings want to kiss you rather than punch you; this is very different from the goal of a programming language utterance, which is intended as an unambiguous statement in a well-defined domain that a computer or another person can evaluate.  A better question might be: which programming language makes it most difficult to accidentally shoot yourself in the foot?
... which is not at all what you asked, of course.

A: COBOL was always considered pretty "natural language". Here's an extract from the 99 bottles of beer page:
move spaces to buffer bb1
move 1 to j
divide i by 10 giving k remainder l
string bb8(k + 1) delimited space into bb1 pointer j
if j > 1
   then move bb7(l + 1) to bb1(j + 1:)
   else move bb7(i + 1) to bb1
end-if

Of course, "natural language" is not always (often?) a virtue amoung programming languages, where preciseness is the order of the day (and natural language is almost always ambiguous - adding the preciseness required by a programming languages just makes it verbose).

A: How about the Shakesspeare programming language. Here's a part of the "hello world" source, out of wikipedia:
               Act I: Hamlet's insults and flattery.
               Scene I: The insulting of Romeo.

[Enter Hamlet and Romeo]
Hamlet:
You lying stupid fatherless big smelly half-witted coward! You are as
stupid as the difference between a handsome rich brave hero and thyself!
Speak your mind!
You are as brave as the sum of your fat little stuffed misused dusty
old rotten codpiece and a beautiful fair warm peaceful sunny summer's
day. You are as healthy as the difference between the sum of the
sweetest reddest rose and my father and yourself! Speak your mind!
You are as cowardly as the sum of yourself and the difference
between a big mighty proud kingdom and a horse. Speak your mind.
Speak your mind!
[Exit Romeo]

Seems like code highlighting doesn't work here. :/

A: VB.NET (though your AppleScript example beats VB.NET), SQL or COBOL (the source of this style). Lolcode is "language"-like but I'm glad English isn't like it.
VB.NET
If MsgBox("The process will be started", MsgBoxStyle.OkCancel, "Title") = DialogResult.OK Then
   'ok was clicked
Else
  'cancel was clicked
 End If

COBOL
IDENTIFICATION DIVISION.
PROGRAM-ID. HELLO-WORLD.
PROCEDURE DIVISION.
    RECORD CONTAINS 55 CHARACTERS
    DISPLAY 'Hello, world'.
    STOP RUN.

SQL
SELECT *
    FROM Book
    WHERE price > 100.00
    ORDER BY title;

Lolcode
ON CATURDAY
    IM IN YR BED
        I IZ SLEEPIN!!10
        VISIBLE "Z!"
    KTHX
KTHXBYE

A: After reviewing all the answers, I'm convinced that AppleScript actually is the most natural language like.

A: If you mean inconsistent in application of rules with lots of bizarre edge cases and sharp corners to injure the learner, there's very few programming languages more English-like than C++.

A: The Shakespeare answer reminded me of Inform 7, which is a serious programming language for writing interactive fiction. It's probably the language most closest to English that exists and has a well-defined semantics.
Here is a sample from Wikipedia:
"Hello Deductible" by "I.F. Author"

The story headline is "An Interactive Example".

The Living Room is a room. "A comfortably furnished living room."
The Kitchen is north of the Living Room.
The Front Door is south of the Living Room.
The Front Door is a door. The Front Door is closed and locked.

The insurance salesman is a man in the Living Room. "An insurance salesman in a tacky polyester suit. He seems eager to speak to you." Understand "man" as the insurance salesman.

A briefcase is carried by the insurance salesman. The description is "A slightly worn, black briefcase." Understand "case" as the briefcase.

The insurance paperwork is in the briefcase. The description is "Page after page of small legalese." Understand "papers" or "documents" or "forms" as the paperwork.

Instead of listening to the insurance salesman for the first time:

    say "The salesman bores you with a discussion of life insurance policies. From his briefcase he pulls some paperwork which he hands to you.";
    move the insurance paperwork to the player.

The sample uses an extensive library of objects which is available for user. But the language itself is in fact Turing complete, and you can define objects with any behaviour in it.

A: Have you heard about Supernova. It's a natural programming language. Even you can create a window in Supernova by just saying I want window and the window title is hello.

A: I hate to plug my own stuff (well not really) but 7Basic has a pretty english-like syntax:
BEGIN FUNCTION (variable AS INTEGER) AS STRING
    PRINT "Hello!"

    RETURN "return value!"
END FUNCTION

A: I think a discussion of where Dijkstra-like programmatic precision is necessary vs where it is not would be interesting. In lower level programming where detail is needed, so is precision. As programming primitives are higher level, perhaps not so much ...

A: Maybe Common Lisp? Macros in Lisp allow you to define abstractions as "new words". That's as close to pseudocode or English as you want to get (because when describing program in our thoughts or discussions, we use a lot of abstractions from the mechanics of particular language).
An interesting example are anaphoric macros, which Paul Graham describes in his book On Lisp. Anaphoric macro is a macro that binds some expression to the symbol "it" inside it's body, so we can easily refer to it:
(aif (get-data) (do-something it))

In this line, the get-data is function which either returs some object or nil. If it returns the data, they are bind to "it" variable, which is the processed by "do-something" function. If the data returned are nil, the condition is not satisfied and the clause is not executed.
There are many other examples of anaphoric macros, like for loops, that bind the loop variable, and so on. In fact, you can even have macros that generate anaphoric macros for you.


text:
Q: Rails index.html.erb delete item - not working Trying to delete an item from index.html.erb with following code:
<%= link_to 'Delete', method: :delete, id: product.id, data: { confirm: 'Are you sure?' } %>

however all it does is try to show the index again.  How can I be more specific, I.e. - if this is a product from a category, how to I reference the path to this object in the database to delete it?

A: Define your action for delete and implement deleting a product in there.


text:
Q: Why does Timespan.TryParseExact not parsing input as expected? I have this code:
var test = TimeSpan.MinValue;
var t = TimeSpan.TryParseExact(
    "03:01 PM",
    "hh:mm tt",
    CultureInfo.InvariantCulture, out test);

t is showing as false. I'm sure I am missing something, I just can't figure it out!

A: It's the AM/PM designator in your string. It shoudn't be there.
TimeSpan represents a duration.

A: Change it to DateTime and it'll work, timespan is for duration, not parsing of dates
var test = DateTime.MinValue;
var t = DateTime.TryParseExact("03:01 PM", "hh:mm tt", CultureInfo.CurrentCulture, DateTimeStyles.AssumeLocal, out test);

A: Time span measures an amount of time. So AM/PM has no meaning, and is not supported in the input or the format string.
This MSDN page details the valid custom format specifiers:
Custom TimeSpan Format Strings
As @Austin Salonen suggested in his comment, since you are trying to obtain a date and time, you should parse your input as DateTime instead of TimeSpan.


text:
Q: How can I count an arbitrary amount of linked child objects? I apologize if my direct question is unclear, I only know how to explain this through the following example.
I'm trying to calculate the amount of child objects connected to an object.
Each object only holds the children that are connected directly
I have the following classes:
class Question
{
    public int ID { get; set; } //Primary key
    public string Text { get; set; }
    public string[] Options { get; set; }
    public string Answer { get; set; }

    public List<Link> Links { get; set; }
}

class Link
{
    public int ID { get; set; }
    public string Answer { get; set; }
    public int QuestionID { get; set; } //Foreign key
}

I use these classes to generate the following dialog editor (see image).

Example:
If I'm at node AB, how can I figure out how many questions are linked underneath it? Which in this case is ABA and ABAA? So the correct answer would be 2. All nodes connected to port Answer B and Answer C should be counted too, should they exist.
I've had little success in coming up with idea's.
I use something like the following function to get all direct children of a single question:
public List<Question> GetDirectChildren(Question question)
{
    var directChildren = new List<Question>();

    foreach(Link link in question.Links)
        directChildren.Add(myQuestions.FirstOrDefault(f => f.ID == link.QuestionID));

    return directChildren;
}

To get all child-child objects, I would create a nested loop, and another nested loop for each children underneath that. But the problem I can't solve is that there can be an infinite amount of linked objects.
Is there a structural way to iterate through or count all linked objects of an object in this scenario? With the purpose of retrieving the count of linked objects.

A: You have a tree there which is a very common data structure. Since in trees, every child of a node is also a tree, you usually use recursion to navigate through the tree. This is also called tree traversal.
In your case, when you just want to count the nodes in your tree, you just have to break it down to a simpler problem (in general, that's a very common approach when solving difficult problems):
When you have a tree, which has no children, then the number of nodes is very clearly defined: It's one. Now, when you add one level, how many nodes do you have? One for the parent, and one for every child.
Since a child is also a tree, you can now generalize this: For any tree, the number of nodes in the tree is one plus the number of nodes for every child tree.
That is your recursive definition, which you can then use to create a recursive function to calculate the total number of nodes in any tree:
public int CountNodes(Node tree)
{
    int count = 1; // current node

    foreach (var child in tree.Children)
    {
        count += CountNodes(child);
    }

    return count;
}

Once you understand this, it's also not a lot more complicated to do different things while traversing the tree. For example, instead of counting the nodes, you could collect them all in a list; or e.g. print a visual representation of your tree.

A: You can recursively call your method GetDirectChildren on all the Link inside your question.
public List<Question> GetDirectChildren(Question question)
{
    var children = new List<Question>();

    if (question.Links.Count > 0)
    {
        foreach(Link link in question.Links)
        {
            Question curQuestion = myQuestions.FirstOrDefault(f => f.ID == link.QuestionID);
            children.Add(curQuestion);
            children.AddRange(GetDirectChildren(curQuestion));
        }
    }
    else
        return children;
}

But if there's at least one cyclical structure, this code will not work.


text:
Q: Images in full width and fade in when fade out I am trying to create a script using JQUERY that changes background images every 5 seconds. The problem is, I can't get the images to be full screen. Other problem I am having is that one image fades out, so that other image can fade in but there is a white space between the two of them. Is there any way to start the fade in at the same time as the fade out?
$(window).load(function() {
  var i = 0;
  var images = ['geral2.jpg','geral3.jpg','geral4.jpg','geral5.jpg','geral6.jpg'];
  var image = $('#slideit');
  image.css('background', 'url(geral1.jpg) no-repeat center center fixed');
  setInterval(function(){
    image.fadeOut(1000, function () {
      image.css('background', 'url(' + images [i++] +') no-repeat center center fixed');
      image.fadeIn(1000);
    });
    if(i == images.length)
      i = 0;
  }, 5000);
});

http://codepen.io/Ryuh/pen/dXYzoM

A: See this resource: https://vegas.jaysalvat.com/ It's a background slider that stretches fullscreen (whether it's width or length) and has exactly the fade effect you're looking for.
Access all settings you're looking to change/alter here: http://vegas.jaysalvat.com/documentation/settings/
Easy to setup and looks great when it is. All code available to be downloaded.
Code will look as simple as:
$elmt.vegas({
    slides: [
        { src: '/img/slide1.jpg' },
        { src: '/img/slide2.jpg' },
        { src: '/img/slide3.jpg' }
    ],
    transition: 'fade'
});

Just in case any links above rot, you can always fork/download from github at this link: https://github.com/jaysalvat/vegas/


text:
Q: Informatica : Can not rename workflow log file I all
I have a job schudled by tivoli for an Informatica workflow.
i have checked property to save workflow logs for 5 runs.
Job is running fine through informatica but if u try to run is from tivoli using pmcmd it fails to rename the workflow log file .
pLease help , i am getting this error :
Cannot rename workflow log file [E:\Informatica\etl_d\WorkflowLogs\wf_T.log.bin] to [E:\Informatica\etl_d\WorkflowLogs\wf_T.log.4.bin].  Please check the Integration Service log for more information.
Disconnecting from Integration Service

A: Check the log file name in Workflow Edit options. Possibly you have same workflow log file name for multiple workflows.
HTH
Irfan


text:
Q: Fedora 17 laptop shuts off due to overheating I've got a Toshiba Satellite A665-S6094 that I've just installed Fedora 17 onto.  When I have a process that utilizes 100% of the cpu for more than 15 minutes or so, the computer force shuts down due to overheating.
Back when I had windows 7 and I overused the processor the fan speed would go into "jet engine" mode while it made a dreadful sound, however it never shut down due to overheating.  Fedora 17 doesn't seem to have this feature.  I go into the BIOS and there is no option for fan speed.
What are the steps to attempt to remedy this situation?

A: Toshiba has always been a company to attempt to either maintain complete control over laptop power usage through their own software (Anyone with a Satellite that came with XP should know what I'm talking about), or through the TVAP (Toshiba Value Package) which alters the standard Vista/Windows 7 power functionality.  In short, unfortunately... if you want the laptop cooling system to operate at peak functionality, you are expected to..

*

*Use Windows.

*Download and install all of the relevant Toshiba Software.

Is this a good thing?  As you can see... not really.  It's kind of Toshiba's way of saying softly that they don't really support Linux.
The advice in Eric Leschinski's answer is very relevant.  The leading edges of the heat sink on the end of the cooling tubes (it's an assembly to shunt the heat off the motherboard completely) work like a lint trap in a clothes dryer.  All it takes is time... every laptop will eventually build up a layer of lint between the fan and the heat sink.  All temporary solutions aside, the only real way to clean a laptop cooling channel properly is to remove the fan, and remove the debris.  Otherwise, blowing air into the exhaust just breaks the debris into chunks, which sits in the fan until it is turned on... which pushes the chunks back against the heat sink.
So... have the laptop cleaned out, and cross your fingers.  It might be enough to stave off the overheating.

A: How to troubleshoot and overheating laptop that shuts down due to overheating:
Your laptop processor generates heat, and if it gets too hot, it will damage the CPU and thus a shut down is required to prevent damage.  Laptops have temperature sensors and BIOS settings to send a signal to the operating system to shut down when the heat passes a certain threshold.  With these steps you can determine what the problem is:
Inadequate Ventilation:
If you have inadequate ventilation to the laptop, the CPU/Video card will overheat and the BIOS sends a signal to the OS to shut down.  Make sure there is adequate ventilation to the CPU and video card.  One way is to feel the keys on the surface keyboard, are they hot?  If your laptop is kept on a soft surface which does not promote airflow underneath the laptop, then the laptop is more likely to overheat.
Dust bunnies:
Do not underestimate the clogging power of unseen dust bunnies.  If the laptop is more than a year old or kept in dusty environment, then your ventilation system may be completely stopped.  Dust bunnies coat the fan blades and metal heat exchange ducts.  Don't take apart the laptop unless you are an expert.  You can determine if this is your problem by sending a quick strong puff of air in the opposite direction that the fan blows.  You can do this with your mouth, but don't spit.  When you do this, a cloud of dust/smoke should come out the bottom of the laptop.
DON'T USE A VACUUM TO GET DUST BUNNIES OUT OF THE LAPTOP OR COMPUTER.
Your standard vacuum cleaner you get at walmart generates enough static electricity to destroy computers with a single touch.  If you do use a vacuum cleaner, don't have its plastic touch the computer case.  Use a vacuum specially designed for computers, or use canned air.
BIOS settings not up to date
The BIOS may not be updated as much as it can be.  Go to the manufacturer or your laptop's website (in my case toshiba.com) and go to the download section for the relevant BIOS updates.  You may get some new options to set the fan speed to go into "full power" mode at a lower temperature.  This may be easier if you have dual booted your laptop with windows, you can download an EXE to flash the BIOS.
Damaged fans in the laptop
Do you feel air blowing out the exhaust port when the laptop fan is on high?  If not, the fan may not be spinning at all or spinning at half speed.
Install a cracked/unlocked laptop BIOS to fiddle with fan settings
A cracked or "unlocked" laptop BIOS (found on overclocking websites) can give you options to custom set your fan temperature thresholds and settings.  So you can tell your fan to go max speed all the time.  As always, be careful with your BIOS options as this gives you the power to brick your CPU if it overheats and the OS doesn't respond by shutting down to prevent damage.
CPU/Video card Heat sensor failures
If the heat sensors are sending faulty readings to the BIOS, the a signal to shutdown the OS may be happening without reason.
Operating system problems
The reason the laptop is shutting down could have nothing to do with the heat generated.  Depending on your operating system, there may be error logs you can find which log the error message.

A: As always, all the posts blame the cleanliness of your fans, etc. The problem is not with your laptop. I experienced the same problems running Windows all day long, and not so much as a degree in rise of temperature-run Fedora or any other Linux flavor and your laptop overheats instantly and shuts down.
I ended up trying and staying with Linux Mint, using Jupiter as as a control for the heat generated. This works on Ubuntu as well, but please don't let anyone con you into thinking that a dirty fan or dust is causing the overheat. These factors MAY contribute to the cause, but if the software is not written properly, or takes account your specific machines specs, then that's another story...try
http://techhamlet.com/2011/11/your-laptop-gets-overheated-while-using-linux-lets-see-how-to-fix-it/


text:
Q: How can i "compile" ESModule from a string? I have a string variable with some code which is essentially ESModule:
let name = "test_snippet";
let injectedCode =
`const callback = (environment, ..._) => {
  function ${name}() {
    const global = (0,eval)("this");
    global.works = true;
    console.info("${name} works!");
  }
  const injectedSnippetsList = ["${name}"];
  const injectedSnippetsCallbacks = [${name}];
  const snippets = {};
  for (let e = 0, { length: t} = injectedSnippetsList; e < t; e++)
    snippets[injectedSnippetsList[e]] = injectedSnippetsCallbacks[e];
  for (let [name, ...args] of _) {
    if (snippets.hasOwnProperty(name)) {
      try {
        snippets[name](...args);
      } catch (error) {
        console.error(error);
      }
    }
  }
};
callback.has = snippet => [
  "${name}"
].includes(snippet);
export default callback;
`;

How can i "compile" it into ESModule to call it's has for example?
I have the following:
async function compileModule(code)
{
  let moduleData = "data:text/javascript;base64," + btoa(code);
  return await import(moduleData);
}

but it interprets moduleData as module path, not as a "content", resulting in "failed to load".
Any suggestions?


text:
Q: c++ opencv/qt method to get width/height of character/word in pixels Basically what I need to do is fit text perfectly within an area and for that I need to be able to get the 'size' of a word (or character). Note that this project needs to be compiled on both linux and windows. I believe TextRenderer::MeasureTextMethod can solve my problem but apparently it is windows specific. Need a way to do this in linux.
Thanks in advance.

A: Use QFontMetrics class. You can find size of characters or strings. Also this class has many another useful methods.
Example:
 QFont font("times", 24);
 QFontMetrics fm(font);
 int pixelsWide = fm.width("What's the width of this text?");
 int pixelsHigh = fm.height();

Link: http://qt-project.org/doc/qt-4.8/qfontmetrics.html
Of course, it is cross-platform.


text:
Q: how to test a function which calls 2 other functions with jest and enzyme I'm using react-dates component in my react project and onDatesChange is a function which is dispatching actions to redux store two times, can someone help me in testing this function with jest and enzyme..
This is DateRangeComponent imported from react-dates.
<DateRangePicker
   startDate={this.props.filters.startDate}
   startDateId={this.state.startDateId}
   endDate={this.props.filters.endDate}
   endDateId={this.state.endDateId}
   onDatesChange={this.onDatesChange}
   focusedInput={this.state.calenderFocused}
   onFocusChange={this.onFocusChange}
   showClearDates={true}
   numberOfMonths={1}
   isOutsideRange={() => false}
/>

And this is my function which is dispatching two actions to the redux store.
onDatesChange = ({ startDate, endDate }) => {
  this.props.dispatch(setStartDate(startDate));
  this.props.dispatch(setEndDate(endDate));
};

How can I test this function in this form. I know, I can test it easily if I refactor it to mapDispatchToProps, which I don't wanna do. thanks


text:
Q: Updating QStackedWidget content at Runtime I'm creating a GUI in PyQT5 that should provide multiple views on data from multiple related SQLite tables. I have implemented these views to be displayed via a QStackedWidget.
Now, some of these views are for overview purposes, others for more detailled views on a subset of the data displayed in the overviews. I want to access the detailled views from the overviews via rightclick.
I have included a minimal example with cars below. (Sorry, it's a bit long, but that was needed to provide a full working example. I have reduced it as much as I could.) The goal is to show the DetailledView with the cars of the company selected in the Overview.
This already provides access from the Overview to the DetailledView on Rightclick, but the company information is not passed along. So even when accessing the DetailledView from 'VW', self.mycompany gets updated but car_widget doesn't, so the DetailledView shows the info about 'Honda' cars (the default).
Is there a way to update car_widgit with the right company? Or do I need to create the DetailledView at runtime? (Does that even work? But I would prefer not to, anyway, as it could make the index of the Stack unreliable...)
How can I update the QTableModel of one view in a QStackedWidget according to what was selected in another view?
Here's the code:
#!/usr/bin/python3

from PyQt5 import QtSql
from PyQt5.QtWidgets import (QMainWindow, QWidget, QApplication, QGridLayout,
                             QStackedWidget, QTableView, QMenu)
from PyQt5.QtCore import Qt, QModelIndex
import sys

class MainGUI(QMainWindow):
    def __init__(self):
        super().__init__()
        self.mycompany = "Honda"
        self.create_connection()
        self.fill_tables()

        self.init_UI()

    def create_connection(self):
        self.db = QtSql.QSqlDatabase.addDatabase("QSQLITE")
        self.db.setDatabaseName("test.db")
        if not self.db.open():
            print("Cannot establish a database connection to {}!".format(self.db_file))
            return False

    def fill_tables(self):
        self.db.transaction()
        q = QtSql.QSqlQuery()
        q.exec_("DROP TABLE IF EXISTS Manufacturers;")
        q.exec_("CREATE TABLE Manufacturers (CompanyId INT PRIMARY KEY, Name TEXT, Country TEXT);")
        q.exec_("INSERT INTO Manufacturers VALUES (1, 'VW', 'Germany');")
        q.exec_("INSERT INTO Manufacturers VALUES (2, 'Honda' , 'Japan');")

        q.exec_("DROP TABLE IF EXISTS Cars;")
        q.exec_("CREATE TABLE Cars (Model TEXT, Year INT, Company INT);")
        q.exec_("INSERT INTO Cars VALUES ('Civic', 2009, 'Honda');")
        q.exec_("INSERT INTO Cars VALUES ('Golf', 2013, 'VW');")
        q.exec_("INSERT INTO Cars VALUES ('Polo', 1999, 'VW');")
        self.db.commit()

    def init_UI(self):
        self.central_widget = QWidget()
        self.setCentralWidget(self.central_widget)
        self.grid = QGridLayout()
        self.central_widget.setLayout(self.grid)
        self.setLayout(self.grid)
        self.make_stack()
        self.show()

    def make_stack(self):
        self.Stack = QStackedWidget(self)

        company_view = QWidget()
        layout = QGridLayout()
        company_view.setLayout(layout)
        self.company_widget = Overview()
        layout.addWidget(self.company_widget, 0, 0)
        self.company_widget.table.customContextMenuRequested.connect(self.open_menu)
        self.Stack.addWidget(company_view)

        car_view = QWidget()
        layout2 = QGridLayout()
        car_view.setLayout(layout2)
        car_widget = DetailedView(self.mycompany)
        layout2.addWidget(car_widget, 0, 0)
        self.Stack.addWidget(car_view)

        self.grid.addWidget(self.Stack, 0,1)

    def open_menu(self, pos):
        menu = QMenu()
        show_act = menu.addAction("Show cars")
        action = menu.exec_(self.company_widget.table.mapToGlobal(pos))
        if action == show_act:
            row = self.company_widget.table.indexAt(pos).row()
            myindex = self.company_widget.model.index(row, 1, QModelIndex())
            company = self.company_widget.model.data(myindex)
            self.mycompany = company
            self.Stack.setCurrentIndex(1)

class MyTable(QWidget):
    def __init__(self):
        super().__init__()
        self.create_connection()
        self.create_model()
        self.init_UI()

    def create_connection(self):
        self.db = QtSql.QSqlDatabase.addDatabase("QSQLITE")
        self.db.setDatabaseName("test.db")
        if not self.db.open():
            print("Cannot establish a database connection to {}!".format(self.db_file))
            return False

    def create_model(self):
        self.model = None

    def init_UI(self):
        self.grid = QGridLayout()
        self.setLayout(self.grid)
        self.table = QTableView()
        self.table.setModel(self.model)
        self.table.setContextMenuPolicy(Qt.CustomContextMenu)

        self.grid.addWidget(self.table, 0, 0)

    def closeEvent(self, e):
        if (self.db.open()):
            self.db.close()

    def check_error(self, q):
        lasterr = q.lastError()
        if lasterr.isValid():
            print(lasterr.text())
            self.db.close()
            exit(1)

class Overview(MyTable):
    def __init__(self):
        super().__init__()

    def create_model(self):
        self.model = QtSql.QSqlTableModel()
        q = QtSql.QSqlQuery()
        query = "SELECT * from Manufacturers"
        q.exec_(query)
        self.model.setQuery(q)

class DetailedView(MyTable):
    def __init__(self, company):
        self.company = company
        super().__init__()

    def create_model(self):
        self.model = QtSql.QSqlTableModel()
        q = QtSql.QSqlQuery()
        query = "SELECT * from cars where company = '{}'".format(self.company)
        q.exec_(query)
        self.model.setQuery(q)

def main():
    app = QApplication(sys.argv)
    ex = MainGUI()
    ex.show()

    result = app.exec_()
    sys.exit(result)

if __name__ == '__main__':
    main()

A: One of the objectives of the inheritance is that the class implements the common tasks that the children can do, and in your case you do not observe those tasks, for example the creation of the model must be done in the father since all the children will do it.
On the other hand the goal of using QSqlTableModel is not to use the QSqlQuery but more friendly requests like setTable(), select() and setFilter(), but it is simply a waste because you could use QSqlQueryModel.
On the other hand I see that you are assuming that the self.mycompany of MainGui is the same as the self.company of DetailedView for what you are going through in the creation of the DetailView object, and the truth is that they are not the same, in the creation of the object only the value of that moment has been copied, so if you change the self.company of MainGui it will not change the self.company of DetailView.
Restructuring your project you get the following:
#!/usr/bin/python3

from PyQt5.QtSql import QSqlDatabase, QSqlQuery, QSqlTableModel
from PyQt5.QtWidgets import (QMainWindow, QWidget, QApplication, QVBoxLayout,
                             QStackedWidget, QTableView, QMenu)
from PyQt5.QtCore import Qt, QModelIndex, pyqtSignal
import sys

DB_PATH = "test.db"

def create_connection():
    db = QSqlDatabase.addDatabase("QSQLITE")
    db.setDatabaseName(DB_PATH)
    if not db.open():
        print("Cannot establish a database connection to {}!".format(DB_PATH))
        return False
    return True

def fill_tables():
    q = QSqlQuery()
    q.exec_("DROP TABLE IF EXISTS Manufacturers;")
    q.exec_("CREATE TABLE Manufacturers (CompanyId INT PRIMARY KEY, Name TEXT, Country TEXT);")
    q.exec_("INSERT INTO Manufacturers VALUES (1, 'VW', 'Germany');")
    q.exec_("INSERT INTO Manufacturers VALUES (2, 'Honda' , 'Japan');")

    q.exec_("DROP TABLE IF EXISTS Cars;")
    q.exec_("CREATE TABLE Cars (Model TEXT, Year INT, Company INT);")
    q.exec_("INSERT INTO Cars VALUES ('Civic', 2009, 'Honda');")
    q.exec_("INSERT INTO Cars VALUES ('Golf', 2013, 'VW');")
    q.exec_("INSERT INTO Cars VALUES ('Polo', 1999, 'VW');")

class MainGUI(QMainWindow):
    def __init__(self):
        super().__init__()
        self.init_UI()

    def init_UI(self):
        self.central_widget = QWidget()
        self.setCentralWidget(self.central_widget)
        self.lay = QVBoxLayout(self.central_widget)
        self.make_stack()

    def make_stack(self):
        self.stack = QStackedWidget()
        self.lay.addWidget(self.stack)

        self.company_widget = Overview()
        self.car_widget = DetailedView()
        self.stack.addWidget(self.company_widget)
        self.stack.addWidget(self.car_widget)
        self.company_widget.changedCompany.connect(self.changedCompany)
        self.car_widget.backSignal.connect(lambda: self.stack.setCurrentIndex(0))

    def changedCompany(self, company):
        self.car_widget.filter(company)
        self.stack.setCurrentIndex(1)

class SQLTable(QTableView):
    def __init__(self, table):
        super().__init__()
        self.init_UI()
        self.create_model(table)

    def create_model(self, table):
        self.model.setTable(table)
        self.model.select()

    def init_UI(self):
        self.model = QSqlTableModel()
        self.setModel(self.model)
        self.setContextMenuPolicy(Qt.CustomContextMenu)

class Overview(SQLTable):
    changedCompany = pyqtSignal(str)
    def __init__(self):
        SQLTable.__init__(self, "Manufacturers")
        self.customContextMenuRequested.connect(self.open_menu)

    def open_menu(self, pos):
        menu = QMenu()
        show_act = menu.addAction("Show cars")
        action = menu.exec_(self.mapToGlobal(pos))
        if action == show_act:
            row = self.indexAt(pos).row()
            ix = myindex = self.model.index(row, 1)
            company = self.model.data(ix)
            self.changedCompany.emit(company)

class DetailedView(SQLTable):
    backSignal = pyqtSignal()
    def __init__(self):
        SQLTable.__init__(self, "cars")
        self.customContextMenuRequested.connect(self.open_menu)

    def open_menu(self, pos):
        menu = QMenu()
        back_act = menu.addAction("Show Manufacturers")
        action = menu.exec_(self.mapToGlobal(pos))
        if action == back_act:
            self.backSignal.emit()

    def filter(self, company):
        self.model.setFilter("company='{}'".format(company))

def main():
    app = QApplication(sys.argv)
    if not create_connection():
        sys.exit(-1)
    fill_tables()
    ex = MainGUI()
    ex.show()

    result = app.exec_()
    sys.exit(result)

if __name__ == '__main__':
    main()


text:
Q: QGIS does not react when using large expression in the Expression Dialog QGIS does not respond when pasting a large expression in QGIS with If-statements following each other:
If("A", 'B',
  If("C", 'D',
    If("E", 'F',
      etc)))

I have checked my statement, it is correct and it works in QGIS 3.4 or lower. I have done some testing, and it seems that with each extra bracket the system takes longer to process or evaluate the expression. After about 10 repeating If-statements the waiting time becomes multiple minutes.

A: Instead of nesting if statements, use case to avoid augmenting complexity.
CASE
  WHEN "mycol" = 'A' THEN 'B'
  WHEN "mycol" = 'C' THEN 'D'
  WHEN "mycol" = 'E' THEN 'F'
  ELSE 'G'
END

If you are using database as a source, you may change the source to make your expression in the SELECT statement instead of QGIS expression level


text:
Q: How to change the order in new commands Being quite an amateur to LaTeX, I am sorry, I don't know how to ask my question without telling the whole story:
In a large document, I made a rather simple command for citing (Classical Latin) authors following other conventions than I use for citing modern authors (where I use BibTeX, etc.). This is the command I use:
\newcommand{\citeCL}[3]{#1, \emph{#2}, \textbf{#3}}
%\citeCL{author}{text}{chapter}

As the first two arguments I use yet other commands from a list of author names and text titles (as I use every name several times and may be inconsistent if writing it in full every time), e.g.,
\newcommand{\Per}{N. Per.}
\newcommand{\PerRud}{Rud. gram.}

Within the document, I could call the cite command thus:
\citeCL{\Per}{\PerRud}{1117}

This cite command I use both in footnotes and in this quotation environment:
\newcommand{\QuoteCL}[4]{
\vspace{5pt}
\begin{quote}\itemsep1pt\parskip0pt\parsep0pt\begin{spacing}{1}
#4 \par\hspace*{\fill}\footnotesize{\citeCL{#1}{#2}{#3}}
\end{spacing}
\end{quote}
\vspace{-20pt}
}

In the document I call the command with the same three arguments as for the \citeCL, and additionally the text to quote, e.g.,
\QuoteCL{\Per}{\PerRud}{§ 1119}{Quis maxime proponendus est quem studeant adolescentes imitari? Marcus Cicero.}

All this works fine, and I have used it throughout my thesis. Now I wish to differ between the ways the author names and titles are written in footnotes and in quotations, using the abbreviated form in footnotes and a new, long form in quotations. My intuitive, naive approach was this:
\newcommand{\citeCL}[3]{#1, \emph{#2}, \textbf{#3}}
% Original command now used for footnotes

\newcommand{\citeCLLong}[3]{#1Long, \emph{#2Long}, \textbf{#3}}
% New command to be called by the \quoteCL command.

\newcommand{\Per}{N. Per.}
\newcommand{\PerLong}{Niccolò Perotti}
\newcommand{\PerRud}{Rud. gram.}
\newcommand{\PerRudLong}{Rudimenta grammatices}
% Duplicating the list of names and titles, adding a long version to be called by the \citeCLLong:

\newcommand{\QuoteCL}[4]{
\vspace{5pt}
\begin{quote}\itemsep1pt\parskip0pt\parsep0pt\begin{spacing}{1}
#4 \par\hspace*{\fill}\footnotesize{\citeCLLong{#1}{#2}{#3}}
\end{spacing}
\end{quote}
\vspace{-20pt}
}
% The command is changed to call the new \citeCLLong

\begin{document}
\QuoteCL{\Per}{\PerRud}{§ 1119}{Quis maxime proponendus est quem studeant adolescentes imitari? Marcus Cicero.}
\end{document}

Now to my question: I was hoping that adding Long to the arguments in \citeCLLong (#1Long, \emph{#2Long}) would make LaTeX choose, e.g., \PerLong instead of merely \Per from my author list, even though I call the \quoteCL command with the argument \Per. That the Long part would be added before it is decided whether to read \Per or \PerLong. But it writes, e.g., "N. Per.Long" instead of choosing \PerLong = "Niccolò Perotti".
Can this be done somehow, or is there any other, smarter solution, that does not need me to go through my entire thesis changing all arguments in all quotations, but make it possible to control from the preample? And that lets my citations in footnotes stay the same, original form?

A: Use a conditional; with a new command you can define in a coherent way commands with "short" and "long" forms. Then \citeCL and \citeCLLong can use
\documentclass{article}
\usepackage[utf8]{inputenc}

\newif\ifCLLong

\newcommand{\citeCL}[3]{\CLLongfalse #1, \emph{#2}, \textbf{#3}}

\newcommand{\citeCLLong}[3]{\CLLongtrue #1, \emph{#2}, \textbf{#3}}

\newcommand{\QuoteCL}[4]{%
\begin{quote}
#4 \par\hspace*{\fill}\footnotesize\citeCLLong{#1}{#2}{#3}
\end{quote}
}

% Abstraction for easing the definition
\newcommand{\newshortlongcommand}[3]{\newcommand{#1}{\ifCLLong #3\else #2\fi}}

\newshortlongcommand{\Per}{N. Per.}{Niccolò Perotti}
\newshortlongcommand{\PerRud}{Rud. gram.}{Rudimenta grammatices}

\begin{document}

Testo introduttivo\footnote{\citeCL{\Per}{\PerRud}{§ 1119}}

\QuoteCL{\Per}{\PerRud}{§ 1119}{Quis maxime proponendus est quem studeant adolescentes imitari? Marcus Cicero.}
\end{document}

\end{document}

(I've simplified the definition of \QuoteCL, to get away with spacing and inessential things.)
In this way you can also input arguments directly without any worry; for instance
\QuoteCL{Niccolò Perotti}{Rudimenta Grammatices}{§ 1119}{...}

would work the same.

A: Change your first two arguments to just text strings, and use the \csname \endcsname construct to accomplish what you desire. (note: I turned off spacing environment, cause I didn't know what package had it)
\documentclass{article}
\usepackage[utf8]{inputenc}

\newcommand{\citeCL}[3]{\csname#1\endcsname, \emph{\csname#2\endcsname}, \textbf{#3}}
% Original command now used for footnotes

\newcommand{\citeCLLong}[3]{\csname#1Long\endcsname,
\emph{\csname#2Long\endcsname}, \textbf{#3}}
% New command to be called by the \quoteCL command.

\newcommand{\Per}{N. Per.}
\newcommand{\PerLong}{Niccolò Perotti}
\newcommand{\PerRud}{Rud. gram.}
\newcommand{\PerRudLong}{Rudimenta grammatices}
% Duplicating the list of names and titles, adding a long version to be called by the \citeCLLong:

\newcommand{\QuoteCL}[4]{
\vspace{5pt}
\begin{quote}\itemsep1pt\parskip0pt\parsep0pt%
%\begin{spacing}{1}%
#4 \par\hspace*{\fill}\footnotesize{\citeCLLong{#1}{#2}{#3}}
%\end{spacing}
\end{quote}
\vspace{-20pt}
}
% The command is changed to call the new \citeCLLong

\begin{document}
\QuoteCL{Per}{PerRud}{§ 1119}{Quis maxime proponendus est quem studeant adolescentes imitari? Marcus Cicero.}

\vspace{6em}
\citeCL{Per}{PerRud}{§ 1119}
\end{document}


text:
Q: SimpleCursorAdapter error When I use a constructor of SimpleCursorAdapter it tells me that constructor is undefined.
What should I do?
public class ReminderListFragment extends ListFragment implements LoaderCallbacks<Cursor> {
private SimpleCursorAdapter mAdapter;

@Override
public void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    String[] from = new String[] {ReminderProvider.COLUMN_TITLE};
    int[] to = new int[] {R.id.text1};
    mAdapter = new SimpleCursorAdapter(getActivity(), R.layout.reminder_row, null, from, 2, 0);
    setListAdapter(mAdapter);
    getLoaderManager().initLoader(0, null, this);
}

A: Change the line to this one:
mAdapter = new SimpleCursorAdapter(getActivity(),
                    R.layout.reminder_row, null, from, to, 0);

You had a "2" instead of "to"
SimpleCursorAdapter's constructor:
SimpleCursorAdapter(Context context, int layout, Cursor c,
                                String[] from, int[] to, int flags)

From: http://developer.android.com/reference/android/widget/SimpleCursorAdapter.html


text:
Q: Elegant way to classify singularities of $\exp(\tan(1/z))$ The function
$$ \exp\left(\tan\left(\frac{1}{z}\right)\right) $$
obviously has a removable singularity at $z=\infty$ and a non-isolated singularity at $z = 0$.
From the real $\tan(x)$ it is clear, that the singularities at
$$z_k = \frac{2}{(2k + 1)\pi} \quad (k \in \mathbb{Z})$$
must be essential. Is there an quick and elegant way to show this?

A: Consider $w=1/z$ and
$$
\exp(\tan(1/z))
=
\exp(\tan(w))
=
\exp(\tan(w))
$$
Now set
$$
k\pi+\frac{\pi}{2}-w=u
$$
so that the expression becomes
$$
\exp(\cot u)
$$
When $z\to z_k$, we have $w\to 1/z_k$ and $u\to0$. This function has an obvious essential singularity at $0$.

A: The Laurent series of $\tan\left( \frac{1}{z} \right) $ around $z_k$ is
$$ \tan\left( \frac{1}{z} \right) = \frac{1/z_k^2}{z - z_k} + h_k(z) $$
where $h_k(z)$ is holomorphic around $z_k$. Then $g$ around $z_k$ takes the form
$$ g(z) = \exp\left( \frac{1/z_k^2}{z - z_k} \right) \cdot \exp\left( h_k(z) \right)$$
where the second factor is holomorphic and the first factor clearly has a


text:
Q: Problems installing socket.io I'm developing a program that requires Node.js and Socket.io. After attempting to install both, I found no inconvenience with "Node.js" but run into an error when inputting npm install socket.io in CMD:
C:\Users\otori\node_modules\socket.io\node_modules\socket.io-client\node_module s\ws\build\binding.sln : MSBUILD : error MSB3411: Could not load the Visual C++ component "VCBuild.exe". If the component is not installed, either 1) install the Microsoft Windows SDK for Windows Server 2008 and .NET Framework 3.5, or 2) install Microsoft Visual Studio 2008.

error code: error MSB3411
It would appear my node.js or my CMD cannot find VCBuild.exe and are asking for me to install VS2008, which I already have installed (I've also tried with VS 2010).
Any help or guidance is deeply appreciated, im using Windows 8 x64 and node.js v0.10.1

A: Sorry to dig up an old question, but your question is the first result when I searched for "Socket.io VCBuild"
The solution I found, after stumbling around was :
npm install socket.io --msvs_version=2012
or
npm install sqlite3 --msvs_version=auto


text:
Q: Online resizing of mysql 5.7.12 I am seeing below error when I tried to resize the mysql buffer pool dynamically.
mysql> set global innodb_buffer_pool_size = 2147483648;
ERROR 1238 (HY000): Variable 'innodb_buffer_pool_size' is a read only variable

The mysql version I am using is
mysql> select version();
+-----------+
| version() |
+-----------+
| 5.7.12    |
+-----------+
1 row in set (0.03 sec)

As per the documentation, 5.7.5 onwards, mysql allows dynamic resizing of the buffer pool.