text:
Q: Action Script 3 / Flex builder 3 : How to make a diagram I want to make a diagram with either flash CS4 or flex builder 3, don't know with one would be the best for the job.
More about the task:
I want to send in values external to the swf file.
The swf-file takes the vaules and makes a diagram of it using x and y values.
Any advise or tips of where i can make this is much appreciated!
Thanks in advance!
jesper

A: if you're generating all of the visual information yourself then you don't need flash at all. you can generate a swf file from flexbuilder/flashbuilder (or even flashdevelop with the free flex sdk). flash cs4 itself is pretty much essential if you need to draw assets too (eg animations etc), but if you don't need that then don't bother spending the money. :)


text:
Q: Pixafy the Magento SaaS solution I just discovered Pixafy, a Magento CE SaaS solution.
One thing that strikes me, it that CE is under the OSL license. Does it allow you to take an existing product, turn it into a SaaS and charge money?
From what I can tell, Pixafy has hugely altered Magento, including the backend, and is not releasing it's modifications as open source. FTP access is (as far as I can tell) not available and you cannot leave the platform without losing your store. Only data export is offered, so you'd need to start again from scratch.
Do they have a special deal with Magento for this? Pixafiy is a gold partner and their SaaS solution was featured on the official Magento website.

A: Short answer: Yes, Pixafy can do this.
More complex answer:
The OSL and most OSS licenses deal with the copyright of the code and thus distribution. A simple summary is that if you do not distribute the code you are generally under no obligation to provide your changes back to the community.
I'm not a lawyer nor an expert on the OSL but running a SaaS does not appear on face to qualify as distribution - you can not access the source code so it can not be argued they are distributing it.  In fact, i'd argue that disabling FTP access is CRITICAL to their adherence to the license since allowing you to copy the source from their servers IS effectively distributing the source code at which point they are bound by the terms of the license dealing with distributing modifications.
Most OSS licenses deal with copyright - specifically the copying & distribution of code. You can take any OSS code modify it and run it on your servers and never have to distribute your changes to anyone.  Even if you other sites with that code - the copyright obligations are triggered when you distribute software - making a copy for your own use is not distribution, which is why you can backup any software no matter what the copyright license says.
Pixafy may have have a special agreement with Magento, but it would NOT be needed for the activities you describe to be entirely
Lawful and respecting of copyright.

A: Referring to the first answer above, I believe this is incorrect, unfortunately. Pixafy may be in violation of the OSL 3.0 terms, as I understand things. Since it's obvious they are offering a SAAS version of Magento that does not operate as the original and appears to be quite different in design and functionality from stock Magento form, since they are providing access to it, they must disclose the source code.
However, if they have never modified the core code of Magento (which is doubtful), then they would not need to disclose any code created that links or shares libraries of the core of Magento or functions purely as an extension.
My understanding of OSL 3.0, and almost everyone I see on the internet seems to not understand this (including myself for a while) but OSL 3.0 does NOT prohibit linking (extensions) to the core code and does not seem to imply that you have created a derivative work just because you created an extension and are running a SAAS environment of Magento using these extensions.
Even if you don't distribute binaries, if you provide access to the output of your software, you are still bound by the license terms and must provide source under the same license. Magento OSL 3.0 license requires the disclosure of modified core source code, even if the environment is accessed purely as a SAAS.
In short, distribution includes pure SAAS access to Magento, not limited to providing access to the files via a download or FTP. Don't modify any core file and provide a SAAS environment of Magento using these modified core files unless you are prepared to provide access to your modifications for free.
I spent many months going over and over forum posts and legal opinions including Lawrence Rosen, before it finally clicked and made sense regarding when you must disclose the source code for free and when you don't. Its all about the definition of a derivative work that determines whether you must disclose source code or not.
Does one really think that any website selling items using a Magento store that makes any addition to the site by way of extension or adding a module to the local or community folders would now be forced to disclose those changes? Of course not. Its only modifications to the core Magento files or files that contain the notice that the file is licensed under OSL 3.0 (almost always this notice is found on core files only).
Any Magento developer that follows basic good practice in coding would never touch the core code anyway so its not likely to be a problem for the majority of Magento site owners.

redpajama_set_name: RedPajamaStackExchange


text:
Q: azure data factory lookup activity - parameterize sql query How do I parameterize the where condition in a lookup activity query in azure data factory? I have created a pipeline parameter and tried to pass it to the lookup activity query as given below.
select max(dt) as dt from tab1 where col='@pipeline.parameters.parama1'
I have tried with quotes, without quotes, curly brackets, but still not firing. Any help would be appreciated.
Regards,
Sandeep

A: Official doc here: https://learn.microsoft.com/en-us/azure/data-factory/control-flow-expression-language-functions
Expressions can also appear inside strings, using a feature called string interpolation where expressions are wrapped in @{ ... }.
Taking this into consideration, this may work for you:
select max(dt) as dt from tab1 where col=@{pipeline().parameters.param}

Hope this helped!


text:
Q: C# hangman, manipulating string I'm working on a hangman game, based on new tools and techniques of arrays, we haven't reached this part of the course-work, however I'm trying to get a head start.
Thus far I have this code (see below) I'm trying to display underscores per character in the zero array element (seven characters in total) then reveal a characters location if the guess it correct, I'm just looking for some insight in addition into my code, perhaps an article or even a code snippet that may shed some light on my dilemma.
EDIT: This is my new code, however, upon entering an 'a' for arizona, it only finds and prints the first 'a' how can I remedy this to find and print both a's to console?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Array_Arizona_Test
{
class Program
{
    static void Main(string[] args)
    {
        int count = 0;
        string secretWord = "arizona";

        char[] secret = new char[secretWord.Length];

        Console.WriteLine("Welcome to Hangman!");

        Console.WriteLine("\nFirst Word.....\n");

        for (int i = 0; i < secret.Length; i++)
        {
            secret[i] = '_';
        }

        for (int i = 0; i < secret.Length; i++)
        {
            Console.Write(secret[i] + " ");
        }

        do
        {
            for (int i = 0; i < secretWord.Length; i++)
            {
                Console.Write("\n\nPlease enter your guess : ");
                char input = (Console.ReadLine().ToCharArray()[0]);

                if (secretWord[i] == input)
                {
                    secret[i] = input;

                    for (int x = 0; x < secret.Length; x++)
                    {
                        Console.Write(secret[x] + " ");
                    }
                }
                else
                {
                    for (int j = 0; j < secret.Length; j++)
                    {
                        Console.Write(secret[i] + " ");
                    }
                }
            }
            count++;

        } while (count < 5);
    }
}
}

A: Change your loop to something like the following:
char[] guess = underscores.ToCharArray();
for (int x = 0; x < characters.Length; x++)
{
    if (userInput == characters[x])
    {
        guess[x] = userInput;
    }
}
Console.Write(guess);

You will also want to add another loop to allow the user guess multiple times at the same word.

A: Here is what you should do

*

*Create an array a and put dashes equal to the number of the letters in the word

*Display that (step 1) to the user

*When the user guess the right letter, put the letter in the right position in array a

*Go to step 2

Read this http://en.wikipedia.org/wiki/Hangman_(game)
Here is a code I just wrote
     static void Main(string[] args)
    {

        string secreteWord = "Arizona";

        //have a dash array equal to the number of the letters of the secret word
        char[] a = new char[secreteWord.Length];

        for (int i = 0; i < a.Length; i++)
        {
            a[i] = '_';
        }

        // Tell the user the number of letters through the dashes
        for (int i = 0; i <a.Length ; i++)
        {
            Console.Write(a[i]+ "  ");
        }

        // ask the user to guess
        Console.WriteLine();

        int count = 0;
        do
        {
            Console.WriteLine("Enter your guess letter");
            char input = Console.ReadLine().ToCharArray()[0];

            for (int i = 0; i < secreteWord.Length; i++)
            {
                //if the user guessed right, replace the correct dash and display to the user
                if (secreteWord[i] == input)
                {
                    count++; //update the count to check when to exit
                    a[i] = input;  //here if the user guess correct, we replace the dash with the input

                   //now we display the dash array after it is modified
                    for (int j = 0; j < a.Length; j++)
                    {
                        Console.Write(a[j] + " ");
                    }
                }
            }
            Console.WriteLine();
        }

        while (count < a.Length);
        Console.WriteLine("You guessed it right");
        Console.ReadLine();
    }


text:
Q: How to use Authorization Token token=A-123456789qwertyuio12 Header in Retrofit 2.0 im trying to consume an api that has that authorization header, i can get a 200 response in Postman with all data but cant get it to work in retrofit

A: May be you need add the Token using OkHttp Interceptor.
OkHttpClient client = new OkHttpClient.Builder()
        .addNetworkInterceptor(mTokenInterceptor)
        .build();

then add it to Retrofit:
Retrofit retrofit = new Retrofit.Builder()
        .client(client)
        .baseUrl(base_url)
        .build();

the mTokenInterceptor:
Interceptor mTokenInterceptor = new Interceptor() {
    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();
        if (mToken != null) {
            Request.Builder requestBuilder = request.newBuilder()
                    .addHeader("Authorization", mToken);
            Request newRequest = requestBuilder.build();

            return chain.proceed(newRequest);
        }
        return chain.proceed(request);

    }
};

when you get the Token, just assign the mToken,

A: You can try something like below, just a crude example
@GET("your server url goes here")
    Call<Your_Model_Class> getServerData(@Header("Authorization") String token);

Pass your token to getServerData method.


text:
Q: Solve for $x$ and $y$ where $x^{\prime} = x + y + t$ and $y^{\prime} = 2x - t$. Given $x = 0$, $y = 1$ at $t = 1$.
Given the equations
  \begin{align}
x' &= x + y + t \\
y' &= 2 x - t
\end{align}
  with $x(1) = 0$ and $y(1) = 1$, how can solutions be obtained?

I tried solving it but I did not get any idea.

A: There are two standard approaches.  One is to differentiate the first and plug the second into it.  That gives a second order equation in one variable.  Do you know how to handle those?
The second is to formulate it as a vector equation.  Here it is $$\begin {pmatrix}x\\y \end {pmatrix}'=\begin {pmatrix}1&1\\2&0 \end {pmatrix}\begin {pmatrix}x\\y \end {pmatrix}+\begin {pmatrix}t\\-t \end {pmatrix} $$
which is like an inhomogeneous first order equation, but working on vector quanties.  You can diagonalize the $2 \times 2$ matrix to make exponentiating it easy.

A: For $x^{\prime} = x + y + t$ and $y^{\prime} = 2x - t$, Given $x(1) = 0$, $y(1) = 1$, then
\begin{align}
x'' &= x' + y' +1 = x' + 2 x - t + 1.
\end{align}
Now, $x''  - x' - 2 x = 1-t$ has solution $$x(t) = c_1 e^{-t} + c_2 e^{2 t} + \frac{2 t -3}{4}.$$
This also leads to
\begin{align}
y(t) &= 2 \int x(u) \, du - \frac{t^{2}}{2} + d_{0} \\
&= - 2 c_{1} \, e^{-t}  + c_{2} \, e^{2 t} - \frac{t^{2} - 3 t}{2} + d_{0}.
\end{align}
From here one can use the conditions $x(1) = 0$ and $y(1) = 1$ to find the constants.
This yields
\begin{align}
0 &= c_{1} e^{-1} + c_{2} e^{2} - \frac{1}{4} \\
1 &= -2 c_{1} e^{-1} + c_{2} e^{2} + 1 + d_{0}
\end{align}
and
\begin{align}
x(t) &= \frac{1}{12} \, \left[ (8 d_{0} + 1) \, e^{- (t-1)} + 2(2d_{0}+1) \, e^{2(t-1)} + 6 t - 9 \right] \\
y(t) &= \frac{1}{6} \, \left[ - (8 d_{0} +1) \, e^{-(t-1)} + (2 d_{0} +1) \, e^{2(t-1)} - 3 t^{2} + 9 t + 6 d_{0} \right].
\end{align}
Since the constant of integration, $d_{0}$, either needs another boundary condition, or can be arbitrary, then consider the case when $d_{0} = 0$ for which the solutions are
\begin{align}
x(t) &= \frac{1}{12} \, \left[ e^{- (t-1)} + 2\, e^{2(t-1)} + 6 t - 9 \right] \\
y(t) &= \frac{1}{6} \, \left[ - e^{-(t-1)} +  e^{2(t-1)} - 3 t^{2} + 9 t \right].
\end{align}


text:
Q: failed to connect to server on first connect. But sometimes it working after restat internet connection What to do about this error?

Server Running on port 5000 { MongoNetworkError: failed to connect to
  server [ds231242.mlab.com:31242] on first connect [MongoNetworkError:
  getaddrinfo ENOTFOUND ds231242.mlab.com ds231242.mlab.com:31242]
      at Pool. (C:\MERNapps\TestMERN14\node_modules\mongodb-core\lib\topologies\server.js:564:11)
      at emitOne (events.js:116:13)
      at Pool.emit (events.js:211:7)
      at Connection. (C:\MERNapps\TestMERN14\node_modules\mongodb-core\lib\connection\pool.js:316:12)
      at Object.onceWrapper (events.js:317:30)
      at emitTwo (events.js:126:13)
      at Connection.emit (events.js:214:7)
      at Socket. (C:\MERNapps\TestMERN14\node_modules\mongodb-core\lib\connection\connection.js:245:50)
      at Object.onceWrapper (events.js:315:30)
      at emitOne (events.js:116:13)
      at Socket.emit (events.js:211:7)
      at emitErrorNT (internal/streams/destroy.js:64:8)
      at _combinedTickCallback (internal/process/next_tick.js:138:11)
      at process._tickCallback (internal/process/next_tick.js:180:9)   name: 'MongoNetworkError',   errorLabels: [
  'TransientTransactionError' ],   [Symbol(mongoErrorContextSymbol)]: {}
  }


text:
Q: Boot failure with samsung 850 evo msata installed in hp envy 15-100j I have windows 10 installed in my HP envy 15-100j. I have 1 tb harddisk with msata slot empty at the time I bought the laptop. Now I bought a new Samsung 850 evo msata ssd (250gb) and when I install the hardware and press the power button, I get windows 10 cannot boot with boot failure error message. But when I remove ssd windows 10 properly loads up. I am trying to follow this tutorial at how to install on msata ssd boot drive in your laptop
On the hp envy specs, I find that my laptop can have msata 32gb for cache purposes. On the tutorial, it says I can boot from msata ssd even though the main purpose of that slot is for cache in my laptop.


text:
Q: Regexp на количество символов без учета пробелов Проверяю поле на количество введенных цифр, их должно быть 19. Все просто, но как сделать проверку на количество символов БЕЗ учета пробелов.
1234 5678 9012 1234 789
1234567890121234789

A: '1234 5678 9012 1234 789 1234567890121234789'.replace(/ /g, '').length;

A: Вот:
/^\s*(\d\s*){19}$/


text:
Q: Feed a scikit classifier with Tensorflow dataset Is there any simple way to connect a Tensorflow dataset to a scikit classifier (such as SVM), such that the dataset records are read automatically during training by scikit fit function?

A: Here is an example using TensorFlow with both a Classifier algo and a Regressor algo.
Classification with TensorFlow 2.0
import pandas as pd
import numpy as np
import tensorflow as tf

import matplotlib.pyplot as plt
# %matplotlib inline

import seaborn as sns
sns.set(style="darkgrid")

cols = ['price', 'maint', 'doors', 'persons', 'lug_capacity', 'safety','output']
cars = pd.read_csv(r'C:/your_path_here/car_evaluation.csv', names=cols, header=None)

cars.head()

plot_size = plt.rcParams["figure.figsize"]
plot_size [0] = 8
plot_size [1] = 6
plt.rcParams["figure.figsize"] = plot_size

cars.output.value_counts().plot(kind='pie', autopct='%0.05f%%', colors=['lightblue', 'lightgreen', 'orange', 'pink'], explode=(0.05, 0.05, 0.05,0.05))

price = pd.get_dummies(cars.price, prefix='price')
maint = pd.get_dummies(cars.maint, prefix='maint')

doors = pd.get_dummies(cars.doors, prefix='doors')
persons = pd.get_dummies(cars.persons, prefix='persons')

lug_capacity = pd.get_dummies(cars.lug_capacity, prefix='lug_capacity')
safety = pd.get_dummies(cars.safety, prefix='safety')

labels = pd.get_dummies(cars.output, prefix='condition')

X = pd.concat([price, maint, doors, persons, lug_capacity, safety] , axis=1)

labels.head()

y = labels.values

from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.20, random_state=42)

#Model Training
from tensorflow.keras.layers import Input, Dense, Activation,Dropout
from tensorflow.keras.models import Model

input_layer = Input(shape=(X.shape[1],))
dense_layer_1 = Dense(15, activation='relu')(input_layer)
dense_layer_2 = Dense(10, activation='relu')(dense_layer_1)
output = Dense(y.shape[1], activation='softmax')(dense_layer_2)

model = Model(inputs=input_layer, outputs=output)
model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['acc'])

print(model.summary())

history = model.fit(X_train, y_train, batch_size=8, epochs=50, verbose=1, validation_split=0.2)

score = model.evaluate(X_test, y_test, verbose=1)

print("Test Score:", score[0])
print("Test Accuracy:", score[1])

Regression with TensorFlow 2.0
petrol_cons = pd.read_csv(r'C:/your_path_here/petrol_consumption.csv')

petrol_cons.head()

X = petrol_cons.iloc[:, 0:4].values
y = petrol_cons.iloc[:, 4].values

from sklearn.model_selection import train_test_split

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=0)

from sklearn.preprocessing import StandardScaler

sc = StandardScaler()
X_train = sc.fit_transform(X_train)
X_test = sc.transform(X_test)

input_layer = Input(shape=(X.shape[1],))
dense_layer_1 = Dense(100, activation='relu')(input_layer)
dense_layer_2 = Dense(50, activation='relu')(dense_layer_1)
dense_layer_3 = Dense(25, activation='relu')(dense_layer_2)
output = Dense(1)(dense_layer_3)

model = Model(inputs=input_layer, outputs=output)
model.compile(loss="mean_squared_error" , optimizer="adam", metrics=["mean_squared_error"])

history = model.fit(X_train, y_train, batch_size=2, epochs=100, verbose=1, validation_split=0.2)

from sklearn.metrics import mean_squared_error
from math import sqrt

pred_train = model.predict(X_train)
print(np.sqrt(mean_squared_error(y_train,pred_train)))

pred = model.predict(X_test)
print(np.sqrt(mean_squared_error(y_test,pred)))

Path to data set:
https://www.kaggle.com/elikplim/car-evaluation-data-set


text:
Q: PHP prepared statement doesn´t work on webserver Hello i have a problem with following code on my website:
<?php
session_start();
include '../databaseConnector.php';

$uid = mysqli_real_escape_string($connector, $_POST['uid']);
$pwd = mysqli_real_escape_string($connector, $_POST['pwd']);

$stmt = $connector->prepare("SELECT * FROM nutzer WHERE uid=?");
$stmt->bind_param("s", $username);

$username = $uid;
$stmt->execute();

$result = $stmt->get_result();

$row = mysqli_fetch_assoc($result);
$hash_pw = $row['pwd'];
$dehash = password_verify($pwd, $hash_pw);

if($dehash == 0)
{
    header("Location: ../loginscreen.php?error=pwwrong");
    exit();
}else{

    $stmt2 = $connector->prepare("SELECT * FROM nutzer WHERE uid=? AND pwd=?");
    $stmt2->bind_param("ss", $username2, $password2);

    $username2 = $uid;
    $password2 = $hash_pw;

    $stmt2->execute();

    $result = $stmt2->get_result();
    $stmt->close();

    if(!$row =$result->fetch_assoc())
    {
        echo "Your username or password is incorrect!";
    } else{
    $_SESSION['id'] = $row['id'];
    $_SESSION['uid'] = $row['uid'];
    $_SESSION['email'] = $row['email'];
    $_SESSION['first'] = $row['first'];
    $_SESSION['last'] = $row['last'];
}

header("Location: ../loginscreen.php"); // go to page after signing in
}

The prepared statements work perfectly on XAMPP on my localhost but when i upload them on my webserver there is nothing happening after logging in. It is just a blank screen. My webserver is running on PHP 5.6 if that is important.

A: Just for anybody who will see this in the future. I saw that my hoster doesn´t support MYSQLnd which is required for the get_result() function. I just wrote it different with fetch() and bind_result(). There are many solution examples in the web.


text:
Q: nginx randomly displays "No Input File Specified" I am running a laravel site using vagrant with Ubuntu, NGINX and php-fpm everything works fine on my site until it doesnt.. I get the typical "No Input File Specified" error, the only thing is its at random. If I wait a while or keep sending the request it will eventually clear up.
Here is my config:
server {
listen          80;
server_name     site.dev;
root            /var/www/site.dev/public;

location / {
    index       index.html index.htm index.php;
    try_files   $uri $uri/ /index.php?$query_string;
}

location ~ \.php$ {
    #root           html;
    fastcgi_pass   unix:/var/run/php5-fpm.sock;
    fastcgi_index  index.php;
    fastcgi_param  SCRIPT_FILENAME $document_root$fastcgi_script_name;
    include        fastcgi_params;
}
}


text: Q: I created ads with AdMob. Ad appears while using test ID. I do not see any ads when I use my ID. why? I created ads with AdMob. Ad appears while using test ID. I do not see any ads when I use my ID. why ? Could it be after the game has been released? can google adsmobs not allowing this? thanks..


text:
Q: Using deployR with Python We are planning to use deployR behind a Python server. The official documentation suggests looking at the core api to do this.
Are there any examples of using deployR with Python? A github repository or blog would be helpful.


text:
Q: How to subtract 2 UTC dates in C# In my website i store User Visit DateTime information in sql server using date data Type.
for that i used  UtcNow in C# .
 visit_date = System.DateTime.UtcNow

Now  i want get the hours difference if same user visiting in my website so how can i subtract 2 UTC dates .I am using following way to get the diff in hour but it gives wrong hours difference.
TimeSpan timeDiff = System.DateTime.UtcNow.Subtract((DateTime)_Last_View.visit_date);

A: Try to get the Hours using the TotalHours on the resulting Timespan like:
TimeSpan interval = date2.Subtract(date1);
double Hours = interval.TotalHours;

A: DateTime dt1 = DateTime.UtcNow;
DateTime dt2 = (DateTime)_Last_View;

TimeSpan ts = dt1.Subtract(dt2);

int seconds = ts.Seconds;
int minutes = ts.Minutes;
double hours = ts.TotalHours;
int days = ts.Days;
int days = ts.TotalDays;
int years = (int) (ts.Days / 365.25); // leap years included

Check this Calculating Date Difference in C#

A: Try using Ticks:
double timeDiffTicks = System.DateTime.UtcNow.Ticks - visit_date.Ticks;
double hours = (((timeDiffTicks / 10000)/1000) / 60)/60;

A: Thank .
It works
TimeSpan timeDiff = System.DateTime.UtcNow.Subtract((DateTime)_Last_View.visit_date);

            if (timeDiff.TotalHours > 24)
            {
            }

I was using timeDiff.Hours instead of timeDiff.TotalHours.


text:
Q: Whats differnece between Symbol Table and Branch/Jump/Virtual Method Table in Context of C/C++ Whats differnece between Symbol Table and Branch/Jump/Virtual Method Table in Context of C/C++ ?
As both keeps the reference of the routines from library/executable module. What's major difference between the two ?

A: The symbol table is a module of the compiler, the virtual method table is a way to implement virtual function.  I'd rather explain what they have in common excepted the word table in their name (short answer nothing) than how their differ. For a start they don't exist at the same time, they serve different purpose, they contain different information.


text:
Q: Best way for processing over 150 million rows MySql I wrote a function on nodejs to SELECT 150 million records, process the data and UPDATE those same 150 million records using
UPDATE 'table' SET value1='somevalue' WHERE idRo2 = 1;

Single Update for each row concatenate send one single query string allowing multipleStatements querys on the db connection.
I've being encountering multiple errors as

*

*Error: Connection lost: The server closed the connection.

*JavaScript heap out of memory.

*RangeError: Invalid string length.

*Killed process.

I think i might not be using the right technologies or programing technique
*Edit:
The data process i need to do is to take the 'wholeApiResponse' column value, parse that string and then insert the parsed values into new added columns (askPrice, lastPrice, lowPrice, highPrice, volumePrice, platformTimestamp), this end up modifying the existing row by adding new values from an existing string.

A: Big Updates (and Deletes) are problematic.
Plan A:  Avoid the big update.  If value1 should always be 'somevalue' when idRo2 = 1, then don't store it in the table; store it elsewhere and use a JOIN.  Then, instead of checking 150M rows, you are changing exactly 1 row.
Plan B:  Do the Update in chunks of 1K rows at a time.  This avoids timeouts, and a number of other potential problems.  Details:  http://mysql.rjweb.org/doc.php/deletebig#deleting_in_chunks .  Even 10K can be problematic, hence my recommendation of 1K.  Anyway, going beyond 1K is getting into "diminishing returns".
Plan C:  Tells us what value1 and idRo2 are really called.  That might lead to some specific suggestions.
Minor issues with datatypes.  Shrinking the table size will help performance some.

*

*INT SIGNED has a limit of 2 billion.  150M is getting kinda close to it.  Keep your eye on any AUTO_INCREMENTs.

*Similarly, INT for idCurrencyPair may be wasting space.  (INT takes 4 bytes; there are smaller datatypes)

*DOUBLE can lead to rounding errors.  And it take 8 bytes.  Consider DECIMAL(...).

*platformTimestamp DOUBLE -- Huh?

*I'll bet that LONGTEXT is rarely used?  We should discuss better ways to store it.


text:
Q: How can I expose my first web application in Google? I release my first Django web application.
But can't get search result of my sites even I enter keyword similar with my url(domain)
How can I expose my site in google?
Thanks :)

A: Submit your URL to Google would be my first thought along with considering the question of where are you expecting your site to fall amongst all the other sites that probably aren't referencing it to be ranked that high as Google may well want to see other sites referencing yours to know what to associate with it.


text:
Q: Can't delete row from SQLite database in iOS? I am using this code to delete row from Sqlite3 Database,but it's not working,insert,update,select query are working fine, but the delete statement is not working in my code
 -(void)delete{

        str=title.text;
        sqlite3_stmt *selectstmt;
        if (sqlite3_open([path UTF8String], &database) == SQLITE_OK) {
            NSString *deleteSQL = [NSString stringWithFormat: @"delete from ToDo where title=\"%@\"",str];
            NSLog(@"%@",deleteSQL);
            const char *sql = [deleteSQL UTF8String];
            sqlite3_prepare_v2(database,sql, -1, &selectstmt, NULL);
            if(sqlite3_prepare_v2(database, sql, -1, &selectstmt, NULL) == SQLITE_OK)
               NSLog(@"success");
            else
              NSAssert1(0, @"Error while creating delete statement. '%s'", sqlite3_errmsg(database));
            }
            sqlite3_finalize(selectstmt);
            sqlite3_close(database);
        }

What am I doing wrong?

A: Hi take a look at it.
I thing you are doing wrong in passing the parameter.
EDIT:
    str=title.text;
    [self openDatabase];//Logic to open database goes here
    sqlite3_stmt *stmt=nil;
    BOOL status=FALSE;

    NSString *deleteSQL = [NSString stringWithFormat: @"delete from ToDo where title='%@'",str];
    NSLog(@"%@",deleteSQL);
    const char *sql = [deleteSQL UTF8String];

   //const char *sql ="delete from ToDo where title='%@'";

   if(sqlite3_prepare_v2(db, sql, -1, &stmt, NULL) == SQLITE_OK)
   {
         sqlite3_bind_text(stmt, 1, [_testId UTF8String], -1, SQLITE_STATIC);

         if(SQLITE_DONE != sqlite3_step(stmt))
               {
                 NSLog(@"Error while Deleting");
               }

    }
    sqlite3_finalize(stmt);
  [self closeDatabase];//Logic to close database goes here

A: you can delete particular recored from sqlite database using below code:-
NSDictionary *d =(NSDictionary *) [YourMutableArray objectAtIndex:0];
NSArray *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDir = [path objectAtIndex:0];
NSString *dbPath =[documentsDir stringByAppendingPathComponent:@"db.sqlite"];
sqlite3_open([dbPath UTF8String], &database);

if(deleteStmt == nil)
{

    NSString *deleteStatementNS = [NSString stringWithFormat:
                                   @"delete from tbl_postoffice where type = '%@'",
                                   urusniqIDentifire];
    const char *sql = [deleteStatementNS UTF8String];

    //const char *sql ="delete from tbl_todo where type = yourDbfildeRecored";
    if(sqlite3_prepare_v2(database, sql, -1, &deleteStmt, NULL) != SQLITE_OK)
        NSAssert1(0, @"Error while creating delete statement. '%s'", sqlite3_errmsg(database));
}

//When binding parameters, index starts from 1 and not zero.
sqlite3_bind_text(deleteStmt, 1, [[d valueForKey:@"type"] UTF8String], -1, SQLITE_TRANSIENT);
if (SQLITE_DONE != sqlite3_step(deleteStmt))
    NSAssert1(0, @"Error while deleting. '%s'", sqlite3_errmsg(database));

sqlite3_reset(deleteStmt);

hope its Helps for you

A: Yes @jason Coco is correct you have prepared your statement twice and you have not called step also after prepare statement..try calling this after prepare:
if (sqlite3_step(selectstmt) == SQLITE_DONE)
{
    NSLog(@"success");
}


text:
Q: Is it possible to send an email through PHPMailer in XML format? Basically exactly what the title suggest: is it possible to send the body of an email (not as an attachment) as XML through PHP mailer.
The formatting seems to continually be an issue and I am just wondering if this is even possible?


text:
Q: Using string as PK vs using GUID or int Id with Unique Constraint for Names Hi I was wondering what is the best practice for tables in which you have a record that must be unique. I've seen the two ways of doing that: use a Primary Key or add a Unique constraint to the column.
If you use a primary key, is it bad practice to have a primary key such as "UserName" that is varchar(*)? Does that impact performance enough that it is problematic? Is it best to use an integer id with a unique constraint on the username?
I see some other factors that may impact choosing a column as PK vs Unique. Am I right about these?
PK
- Column should be one that doesn't ever need to be changed
Unique
- Column could be changed later on

A: Having a primary key on the UserName is not the best idea, but it isn't so bad in performance as you maybe think.
The best idea would be using a ID (INT) as PRIMARY KEY and the UserName as UNIQUE.

A: Usernames change over time, that is why they are a bad candidate for a PK especally since it is extremely likely you have child records associated with the username. For instance suppose my username included some variation of my real name. If I then got divorced and returned to my maiden name, the last thing I want to do is be reminded of that SOB I was married to and so I change my username. Do you really want to change the 2 million posts I've made in the last ten years as well? I didn't think so.
Yes string comparisons are slower but this may or may not be an issue depending on the overall amount of action the database will get. Small copmany database with less than 200 users, probaly not a problem, Internet site with millions of users,  much more likely to be a problem.

A: It may or may not be a good idea as others have already discussed. Let me just add one more detail...

I see some other factors that may impact choosing a column as PK vs Unique.

The main difference is usually related to clustering. Most DBMSes (that support clustering) automatically use PK as a clustering index. For example MySQL/InnoDB always clusters data and you can't event turn it off, while MS SQL Server clusters by default (you have to use special syntax to turn it off).
Should you choose to use clustering (or are forced by your DBMS), having fewer indexes is usually better (e.g. see "Disadvantages of clustering" in this article), even when leading to "fatter" foreign keys.


text:
Q: bit manipulation function does not give the required result I'm trying to write a function that take a const char array and for every byte I'm trying to get the bits and spread them into 4 bytes where the bits are assigned to bit 2 and 5 of the 4 bytes,
int encryptDataAndSend(const char *logName, const char *data)
{
  const int len = strlen(data);
  printf("data length: %d \n", strlen(data));
  char encryptedData[len * 4 + 1];
  for (uint8_t i = 0; i < len; i++)
  {
    uint8_t v1 = 255;
    uint8_t v2 = 255;
    uint8_t v3 = 255;
    uint8_t v4 = 255;

    int bit0 = data[i] & (1 << 0);
    int bit1 = data[i] & (1 << 1);
    int bit2 = data[i] & (1 << 2);
    int bit3 = data[i] & (1 << 3);
    int bit4 = data[i] & (1 << 4);
    int bit5 = data[i] & (1 << 5);
    int bit6 = data[i] & (1 << 6);
    int bit7 = data[i] & (1 << 7);

    char temp[4] = {0};

    printf("char is %d \n", data[i]);
    printf("bits: %d %d %d %d %d %d %d %d \n", bit7, bit6, bit5, bit4, bit3, bit2, bit1, bit0);

    v1 = (v1 & ~(1 << 2)) | (bit0 << 2);
    v1 = (v1 & ~(1 << 5)) | (bit1 << 5);
    printf("v1 : %d \n", v1);
    v2 = (v2 & ~(1 << 2)) | (bit2 << 2);
    v2 = (v2 & ~(1 << 5)) | (bit3 << 5);
    printf("v2 : %d \n", v2);
    v3 = (v3 & ~(1 << 2)) | (bit4 << 2);
    v3 = (v3 & ~(1 << 5)) | (bit5 << 5);
    printf("v3 : %d \n", v3);
    v4 = (v4 & ~(1 << 2)) | (bit6 << 2);
    v4 = (v4 & ~(1 << 5)) | (bit7 << 5);
    printf("v4 : %d \n", v4);
    temp[0] = v1;
    temp[1] = v2;
    temp[2] = v3;
    temp[3] = v4;
    memcpy(encryptedData + 4 * i, temp, 4);
    // encryptedData[len * 4] = 0;
  }
  printf("encrypted data: %s", encryptedData);
  const int txBytes = uart_write_bytes(UART_NUM_2, encryptedData, strlen(encryptedData));
  ESP_LOGI(logName, "Wrote %d bytes", txBytes);
  ESP_LOG_BUFFER_HEX("SENDDATA_TAG", encryptedData, txBytes);
  return txBytes;
}

The way I call the function is
encryptDataAndSend(TX_TASK_TAG, "BF");

so the results should be 8 bytes where the 8 bits of B is split into 4 bytes and placed in the 2nd and 5th bit positions of the new bytes and then the 8 bits of F is split into 4 bytes and  placed in the 2nd and 5th positions of the new bytes.
at the moment I'm not getting the correct results, I always get the same numbers, is the bit setting and checking correct, any help would be appreciated!

A: Looking at the output:
data length: 2
char is 66
bits: 0 64 0 0 0 0 2 0
v1 : 219
v2 : 219
v3 : 219
v4 : 219
char is 70
bits: 0 64 0 0 0 4 2 0
v1 : 219
v2 : 219
v3 : 219
v4 : 219

Your bit0 ... bit7 variables contain the values of the bits that are set, for example bit6 has the value 64 i.e. bit 6 of bit6 is set.  When you later try to push that value into the destination:
v4 = (v4 & ~(1 << 2)) | (bit6 << 2);

bit6 << 2 has the value 256 i.e. bit 9 is set which you then OR into v4.
Your bitn variables should contain either 0 or 1 if the bit in question is set or not set:
int bit0 = (data[i] & (1 << 0)) != 0;
int bit1 = (data[i] & (1 << 1)) != 0;
int bit2 = (data[i] & (1 << 2)) != 0;
int bit3 = (data[i] & (1 << 3)) != 0;
int bit4 = (data[i] & (1 << 4)) != 0;
int bit5 = (data[i] & (1 << 5)) != 0;
int bit6 = (data[i] & (1 << 6)) != 0;
int bit7 = (data[i] & (1 << 7)) != 0;

Output (with extra hex printing):
data length: 2
char is 66
bits: 0 1 0 0 0 0 1 0
v1 : 251 fb
v2 : 219 db
v3 : 219 db
v4 : 223 df
char is 70
bits: 0 1 0 0 0 1 1 0
v1 : 251 fb
v2 : 223 df
v3 : 219 db
v4 : 223 df

Also, you're attempting to print encryptedData as a string and call strlen on it, but you don't put a null terminator on it (although you seem to have a statement to do that commented out).  Since you know how long your byte array is, just use len * 4 instead of strlen(encryptedData)


text:
Q: Can anyone explain to me this JavaScript code that define some variables and loop through them? I'm following this tutorial: http://vimeo.com/16961179 that teaches you how to make views and partials with express.js:
var products = [
{
    id: 1,
    name : 'Mac Book Pro',
    description: 'Apple 13 inch Mac Book Pro notebook',
    price: 1000
},
{
    id: 2,
    name : 'iPad',
    description: 'Apple 64GB 3G iPad',
    price: 899
}
];

module.exports.all = products;

module.exports.find = function(id) {
    id = parseInt(id, 10);
    var found = null;
    productloop: for(product_index in products) {
        var product = products[product_index];
        if (product.id == id) {
            found = product;
            break productloop;
        }
    };
    return found;
}

In the tutorial, the author doesn't explain much this part.
I'm specially confused about the loop part.
Can anyone explain it to me (I'm a JavaScript beginner)?
I understand the products variable at the top, but it seems like an array which has other arrays inside it.

A: The function searches for a product by product id.

*

*The loop sets product to each product in the product array, sequentially.

*It compares that product's id to the one passed in to the function.

*If it's equal, it breaks out of the loop (yay goto) and returns the product (truthy).

*If it exits the loop normally, that means the product was never found, and it will return null (falsey).

A: Would it be more readable for you expressed thus:
var products = [
{
    id: 1,
    name : 'Mac Book Pro',
    description: 'Apple 13 inch Mac Book Pro notebook',
    price: 1000
},
{
    id: 2,
    name : 'iPad',
    description: 'Apple 64GB 3G iPad',
    price: 899
}
];

module.exports.all = products;

module.exports.find = function(id) {
    var i, product,
    nProducts = products.length;

    id = parseInt(id, 10);
    for(i = 0; i < nProducts; ++i) {
        product = products[i];
        if (product.id === id) {
            return product;
        }
    }
    return null;
}

A: First of all, it's awful code. It could break down at the slightest change.
Let's start with the first line.
var products = [

Declares a variable in a global context. Try to avoid this. Everything that happens in a global context, can break down. In addition, encapsulation of data helps to increase the modularity of the code, which in turn allows you to reuse code.
Let's look at the function find():
module.exports.find = function(id) {
    id = parseInt(id, 10);
    var found = null;
    productloop: for(product_index in products) {
        var product = products[product_index];
        if (product.id == id) {
            found = product;
            break productloop;
        }
    };
    return found;
}

In JavaScript, blocks do not introduce a scope. There is only function-scope. A variable introduced anywhere in a function is visible everywhere in the function. JavaScript's blocks confuse experienced programmers and lead to errors because the familiar syntax makes a false promise.
So this (var product = products[product_index];) declaration does not actually declare a new variable each iteration.
Next.
product.id == id

The == and != operators do type coercion before comparing. This is bad because it causes ' \t\r\n' == 0 to be true. This can mask type errors.
In case of function find() operator == does not lead an error, but this is the place where the error may appear when you change the code.
Always use === operator.
for(product_index in products)

The for in statement allows for looping through the names of all of the properties of an object. Unfortunately, it also loops through all of the properties that were inherited through the prototype chain. This has the bad side effect of serving up method functions when the interest is in data properties. If a program is written without awareness of this situation, then it can fail.
The body of every for in statement should be wrapped in an if statement that does filtering. It can select for a particular type or range of values, or it can exclude functions, or it can exclude properties from the prototype. For example,
for (name in object) {
    if (object.hasOwnProperty(name)) {
        ....
    }

}

In your code 'products' is an array, so you can be sure that it has no extra properties. But! Products is global variable, so in reality it can be anything.
I'm a little rewrite the function and explain what this code does.
module.exports.find = function(id) {
    var found = null,
       product;
    id = parseInt(id, 10);
    for (product_index in products) {
        if (products.hasOwnProperty(product_index)){
            product = products[product_index];
            if (product.id === id) {
                found = product;
                break;
            }
        }
    };
    return found;
}

It's simple. The function takes a product ID as an argument (function(id)), turns it into a number (id = parseInt(id, 10);). Then runs through an array of products one by one with a loop (for(product_index in products)), checking the equality of passed to the function identifier and the identifier of the current product (if (product.id == id)). If they are equal, stops iterate (break;), assign the value of current product to the variable "found"  (found = product;) and return the result to the caller of the function (return found;).
P.S. I really hardly know English, so please forgive me for possible mistakes.

A: Products is an array containing two objects. Some people might call them "associative arrays" but they are just objects. They have 'properties' (like an id) and 'values':
var products = [{
    id: 1,
    name : 'Mac Book Pro',
    description: 'Apple 13 inch Mac Book Pro notebook',
    price: 1000
},{
    id: 2,
    name : 'iPad',
    description: 'Apple 64GB 3G iPad',
    price: 899
}];

module.exports is the object that your node program will actually see when you do require('./products.js'):
module.exports = {

    // just pass along the whole array
    all: products,

    // method to find a product by id
    find: function(id){
        return products.filter(function(product){
            return product.id == id
        })[0] // we return the first element, at index zero
    }
}

I replaced the for in loop with the filter method, should make things clearer here. It will loop over the products array and execute the function for each of them - if the result is true, the item is added to the result, otherwise it's ignored.

This is what using this module should look like using Express:
var products = require('./products.js')

app.get('/products', function(req, res){
    // get the whole products array
    products.all
    // render page...
})
app.get('/products/:id', function(req, res){
    // get product with id ':id' from URL (http://mysite.com/products/25)
    var p = products.find(req.params.id)
    // render page...
})


text:
Q: iOS & Android: swap from paid app to free with in-app billing/purchase I'm about to develop my first paid app for Android and iOS (both native). My plan is to release the first version just for purchase (no free). Later on I want to swap it to free with two levels of in app purchases.
My issue/question is: How can I make sure when a user of the first payed version of the app gets the in-app pruchase content when he/she updates to the new (free with in-app billing) version?
I found this 15 month old post with kinda the same question...
Maybe something has changed since then - and it doesn't help with iOS. Thats why I put this question up.
Thanks a lot for your input
Soko


text:
Q: how to retrieve the name and value in object list The object list is looks like that in Javascript
Object {Not In Build Scope: 37, Incomplete: 1}

I am not sure how to get the "Not In Build Scope", "Incomplete" and their value.
Please kindly help.

A: You can use Object.keys() to get the keys of that object and with each key, you can get the corresponding values, like this
> var dataObject = {
...     "Not In Build Scope": 37,
...     "Incomplete": 1
... };
> var keys = Object.keys(dataObject);
> var values = keys.map(function(key) {
...     return dataObject[key];
... });
> keys
[ 'Not In Build Scope', 'Incomplete' ]
> values
[ 37, 1 ]


text:
Q: magento admin - retrieve current selected store in a multistore backend is it possible to retrieve the current selected store view in a multi store magento backend? i'm in an admi page (Catalog -> manage Categories -> general Information) and i have to retrieve the current selected store / store id. is it possible and how?
thanks

A: There are a number of options for this but you should be able to use,
Mage::app()->getRequest()->getParam('store');

if you aren't looking for a specific ID, you can use
Mage::getModel('core/store')->getCollection()->load()->getAllIds();

assigning your own variables to use with them.


text:
Q: WCF exception--Faulted state I added the WCF service reference to my project. Next step is to create a channel from the code.
 WSHttpBinding bindingDialingType = new WSHttpBinding();
        EndpointAddress endingPointDialingType = new EndpointAddress("http://wsvc.corporate.my.com/International/DialingService.svc");
        ChannelFactory<IDialingService> iDialingServiceChannelFactory = new ChannelFactory<IDialingService>(bindingDialingType, endingPointDialingType);
        IDialingService instanceIDialingService = iDialingServiceChannelFactory.CreateChannel();

Because I met an exception, so I guess that something wrong with my channel factory code.
The communication object, System.ServiceModel.Channels.ServiceChannel, cannot be used for communication because it is in the Faulted state.

To capture the exception, I had the code.
My app.config is:

 <system.serviceModel>
  <bindings>
   <basicHttpBinding>
    <binding name="BasicHttpBinding_iLuCRE" />
   </basicHttpBinding>
   <wsHttpBinding>
    <binding name="WSHttpBinding_IDialingService">
     <security mode="None" />
   </binding>
   </wsHttpBinding>
  </bindings>
  <client>
   <endpoint address="http://wsvc.corporate.my.com/LuCRE/LuCRE.svc"
    binding="basicHttpBinding" bindingConfiguration="BasicHttpBinding_iLuCRE"
    contract="LuCRE.iLuCRE" name="BasicHttpBinding_iLuCRE" />
   <endpoint address="http://wsvc.corporate.my.com/International/DialingService.svc"
    binding="wsHttpBinding" bindingConfiguration="WSHttpBinding_IDialingService"
    contract="DialingService.IDialingService" name="WSHttpBinding_IDialingService" />
  </client>
 </system.serviceModel>

I used WCFTestClient to test it, however the service does work. I added the service reference to my project and I don't know the code details.
Updated:
If I used the code
 DialingServiceClient client = new DialingServiceClient();

Then call the method through client, then everything is fine. Why?

A: Your binding element security is None. You need to also mention it when defining programmatically.
WSHttpBinding bindingDialingType = new WSHttpBinding
   { Security = new WSHttpSecurity { Mode = SecurityMode.None } };


text:
Q: Inline query for listing all pages from a namespace without any subobjects I need an inline query that lists all pages from a specific namespace, but without listing subobjects specified on these pages.
Restricting results to a namespace is possible like that:
{{#ask: [[ExampleNamespace:+]] }}

But it lists all subobjects, too.
Workarounds:

*

*Specify a category on these pages (subobjects don't inherit it) and query for the category instead:
{{#ask: [[ExampleCategory]] }}

*Specify a property on these pages (and never on the subobjects) and query for the property (with a wildcard value) instead:
{{#ask: [[ExampleProperty::+]] }}

But both workarounds require editing, which I would like to avoid. Is there a better way to solve this?

A: Not sure if it's a better way, but it looks like array formats/arrays and their #arraymap and #arrayunique functions are a way to go in order to trim SMW subobject tags and make the DISTINCT operation. Unfortunately, the solution below has a query result limit issue described as well (at least out of what I understand in SMW). In general, it may look like the following, and I will appreciate if someone suggests a nicer solution:
<!-- Fetch all pages from the "Live event" namespace -->
{{#arraydefine: QUERY_RESULT
| {{#ask: [[Live event:+]]
  | format = array
  | link = none <!-- NOTE: array item link -->
  | limit = 10000 <!-- NOTE: limit -->
  }}
}}

<!-- Store the mapped result into another array -->
{{#arraydefine: MAPPED_QUERY_RESULT
| {{#arraymap: {{#arrayprint: QUERY_RESULT}}
  | ,
  | $O <!-- NOTE: array map iterator value -->
  | {{#explode: $O <!-- NOTE: explode by hash -->
    | #
    | 0
    }}
  }}
| ,
| unique
}}

<!-- Generate links markup -->
{{#arraymap: {{#arrayprint: MAPPED_QUERY_RESULT}}
| ,
| $O
| [[$O]] <!-- NOTE: plain links -->
}}

The notes from the code above:

*

*NOTE: array item link - Not suppressing the links causes the mapper to be more complicated (including parsing HTML <span> tags and class attributes).

*NOTE: limit - This is probably the biggest issue here as the number of subobjects affects the query result. SMW by default limits the query results, and the maximum query limit cannot be overridden as far as I know. Having more rows, which count is greater than the limits is, will cause the 'Further limits' link to appear. Actually speaking, I have no idea how to work around it nicely.

*NOTE: array map iterator value - {{#arraymap}} seems to replace strings in the simplest way like sed or a simple text editor app do. So $O is used as the iterator value placeholder for the formula parameter trying not to clash with other string tokens.

*NOTE: explode by hash - #ask subobject results generate hashed links like PageA#_159c1f213de2fcaf165f2c9c5c56686b. Just getting rid of them. In case you need to strip wiki links, you might also play around with [[ or | (encoded like [<nowiki/>[ and <nowiki>|</nowiki> respectively)

*NOTE: plain links - The generated links will have underscores instead of spaces. Unfortunately, [[{{#replace: $O | _ | <nowiki> </nowiki>}}]] didn't work for me -- the underscores are simply consumed for some reason, however this approach is also recommended at the #replace function wiki page.

Some links:

*

*SMW array result format

*SMW configuration

*SMW further results

*#arraymap:

*#explode:

*#replace:

*Help:List the set of unique values for a property (pay attention at the "Limitations and issues" section)


text:
Q: Elegant way to initialize array of structs in C++98 I am using gcc version 4.9.2
If I compile using the compiler flag -std=c++0x the following code compiles OK.
#include <iostream>
#include <vector>

using namespace std;
typedef struct
{
    vector<int> a;
    int b;
} MYTYPE;

int main(void)
{
    MYTYPE test[]=
    {
        { {1,2,3},4},
        { {5,6},7},
        { {},8}
    };
}

If I remove the -std=c++0x flag then the compiler reports:

error: could not convert '{1, 2, 3}' from '' to 'std::vector'

What is an elegant way to initialize test[] ?

A: Other than achieving some semblance of elegance at the calling site by writing a set of hideous constructors in your struct, there is no particularly elegant way of initialising an array of these structs pre-C++11.
It was for precisely these constructs that the C++11 syntax was developed.

A: With C++98, the best one can achive is probably the definition and use of an helper function:
struct Data
{
    std::vector<int> vector;
    int scalar;
};

template<std::size_t N>
Data make_data(const int (&vector)[N], int scalar)
{
    Data result;
    result.vector.assign(vector, vector+N);
    result.scalar = scalar;
    return result;
}

int main()
{
    const int vector[] = {1,2,3}; // just to annoy people using namespace std :)
    Data d = make_data(vector, 4);
    std::cout << d.vector[2] << "\n" << d.scalar << "\n";
}

live demo


text:
Q: How to make my existing ruby gem configuration available to my rails-api app? I have a ruby gem I created that I've been using in one of my rails-api apps. I recently added a configuration to the gem, so I can configure it from my rails-api app, which would look like this:
# In rails-api app /config/initializers/my_gem.rb
MyGem::MyNamespace.configure do |config|
   config.allow_custom_commands = true
end

However, when I start the rails server, I'm getting a NoMethod error:
/Users/me/dev/rails/api.abc/config/initializers/my_gem.rb:61:in `<top (required)>': undefined method `configure' for MyGem::MyNamespace:Module (NoMethodError)
        from /Users/me/dev/rails/api.mohojo-werks/vendor/bundle/gems/activesupport-5.0.5/lib/active_support/dependencies.rb:287:in `load'
        from /Users/me/dev/rails/api.mohojo-werks/vendor/bundle/gems/activesupport-5.0.5/lib/active_support/dependencies.rb:287:in `block in load'
        from /Users/me/dev/rails/api.mohojo-werks/vendor/bundle/gems/activesupport-5.0.5/lib/active_support/dependencies.rb:259:in `load_dependency'
etc.

All of my gem tests pass fine, so I don't know what I'm doing wrong. Here are my config files:
# /my_gem/configuration.rb
module MyGem
    module MyNamespace

        class Configuration
            attr_accessor :allow_custom_commands

            def initialize
            reset
            end

         public
            def reset
                @allow_custom_commands = false
            nil
            end
        end
    end
end

# /my_gem/configure.rb
module MyGem
    module MyNamespace
        class << self
            attr_writer :configuration
        end

        def self.configuration
            @configuration ||= Configuration.new
        end

        def self.configure
            yield(configuration)
        end
    end
end

A: I seemed to have missed a few 'requires' in the below files. After adding them, everything seems to work fine, and my configuration block works fine in my rails-api app /config/initializers/my_gem.rb...
# my_gem.rb
require 'my_gem/configure'

# /my_gem/configure.rb
require_relative 'configuration'


text:
Q: How can I get clicked input radio value from autocomplete to send in form to php file I'm doing an input with autocomplete where my user can select multiple users from database and I want to submit those select users in my form where action goes to a php file that does a INSERT in the database.
So this is the input, I want the selected users to show up in p#selecionados but user selects one at a time:
<form id="formCriaJogo" method="post" action="./components/insert.php">
    Other users
    <input type="text" name="autor" id="autor" placeholder="Write users name" />

    <button type="submit">Insert</button>
</form>

And this is jquery code to do the autocomplete:
$(document).ready(function() {
        $('#autor').keyup(function() {
            var query = $(this).val();;

            if (query != '') {
                $.ajax({
                    url: "./components/search.php",
                    method: "POST",
                    data: {
                        query: query
                    },
                    success: function(data) {
                        $("input#autor").css("margin-bottom", '0');
                        $("#autorLista").css("display", 'block');
                        $('#autorLista').fadeIn();
                        $('#autorLista').html(data);
                    },
                    error: function(error) {
                        console.log(error);
                    }
                });
            }
        });

        $('input#autor').on('change', function() {
             alert($('input[name=autor]:checked', '#formCriaJogo').val());
        });
    });

Also, here is search.php that does the search:
<?php

include_once "../connection/connection.php";

if (isset($_POST['query'])) {
    $link = new_db_connection();
    $stmt = mysqli_stmt_init($link);
    $output = '';
    $input = $_POST['query'];

    $query = "SELECT id_user, nome_user FROM users WHERE nome_user LIKE CONCAT(?, '%')";

    mysqli_stmt_prepare($stmt, $query);
    mysqli_stmt_bind_param($stmt, 's', $input);
    mysqli_execute($stmt);
    mysqli_stmt_bind_result($stmt, $id_user, $name_user);
    mysqli_stmt_store_result($stmt);

    if (mysqli_stmt_num_rows($stmt) > 0) {
        while (mysqli_stmt_fetch($stmt)) {
            $output .= "<input type='radio' value='" . $id_user . "' name='autor'>" . $name_user . "
";
        }
    } else {
        $output .= '
The user your looking for doesn't exist.
';
    }
    echo $output;
}

Now the clicked input type=radio value which contains users' id and name I want the user name in p#selecionados just to show them what he selected and also send id and name of user selected when submitting my form.

A: You can create an array in jquery so , whenever you select an option from autocomplete box.. put that value inside that array in jquery .I have use checkbox instead of radio-button in below code and whenever user select any option that data will get inserted in array i.e:index and when insert button is clicked the selected data will get display in p#selecionados tag and also an ajax will call to send your selected data to php page.Also i have added value='" . $id_user."," . $name_user . "' you can split this using .split() with delimiter , to get both userid and username.Sample code :

var index = [];

//when check-box is changed
$('input[name=autor]').change(function() {

  //checking if checkbox is check put it in array
  if ($(this).is(':checked')) {
    index.push($(this).val());
    console.log(index)
  } else {
    //if uncheck remove the element from array
    if ((index1 = index.indexOf($(this).val()) !== -1)) {
      index.splice($.inArray(index1, index), 1);
      console.log("remove");
    }

  }

});
//when insert button is click
$("button").click(function() {
  //clear the p tag content
  $("p#selecionados").html("");
  for (var i = 0; i < index.length; i++) {
    //append all selected check box
    $("p#selecionados").append(index[i] + "
");
    console.log("userid & username" + index[i]);

  }

  if (index != '') {
    $.ajax({
      url: "yourphp_page_name",
      method: "POST",
      data: {
        //sending array to php
        data: index
      },
      success: function(data) {
        //do something
      },
      error: function(error) {
        //do something
      }
    });
  }

});

<input type='checkbox' value='" . $id_user."," . $name_user . "' name='autor'>" . $name_user .

<input type='checkbox' value='" . $id_user."," . $name_user . "' name='autor'>" . $name_user .

<button type="submit">Insert</button>

 Selected data :

Then in your php side ,you need to get that array i.e : data using $_POST['data'] and then explode your array and use it as per your requirement.


text:
Q: Separate regex clauses I need to match a string against a list of predefined keywords and capture it in a group, where as there might be an optional character preceding the keyword.
Examples
Allowed keywords:

*

*contains

*startswith

*equals

*endswith

Optional character: !
- input value              - comment
contains(field,value)      // OK
startswith(field,value)    // OK
test(field,value)          // NOK (test is not a valid keyword)
equals(field,value)        // OK
!startswith(field,value)   // OK  (optional character ! allowed)
!contains(field,value)     // OK  (optional character ! allowed)

Regex
I tried with the following regex:
(?<action>!?startswith|endswith|contains|equals)\((?<field>\w+),(?<value>\w+)\)

I can successfully capture the groups (action, field, value), but the regex allows the optional character only for startswith. How can I separate the two rules and still capture the full keyword? Something like capture=(optional ?)(any of the allowed keywords)

A: Just put the !? outside the capturing group.
@"!?\b(?<action>startswith|endswith|contains|equals)\((?<field>\w+),(?<value>\w+)\)"

\b word boundary after !? is a much needed one.
DEMO

A: If you want to capture !startswith and !contains, use the following...
(?<action>!?(startswith|endswith|contains|equals))\((?<field>\w+),(?<value>\w+)\)

A: Why not use
(?<=^|\p{P}|\p{Zs}|\b)(?<action>\!?(?:startswith|endswith|contains|equals))\((?<field>\w+),(?<value>\w+)\)(?=$|\p{P}|\p{Zs}|\b) ?
You will match almost all possible boundaries + "!?" is used only once inside the ?<action> group, and your action will hold the method name with or without the ! symbol.
Here is some code for testing:
var MyRegex = new Regex(
      "(?<=^|\\p{P}|\\p{Zs}|\\b)(?<action>\\!?(?:startswith|endswit" +
      "h|contains|equals))\\((?<field>\\w+),(?<value>\\w+)\\)(?=$|\\p" +
      "{P}|\\p{Zs}|\\b)",
    RegexOptions.IgnoreCase
    | RegexOptions.Multiline
    | RegexOptions.CultureInvariant
    | RegexOptions.Compiled
    );
// Capture all Matches in the InputText
var ms = MyRegex.Matches(@"contains(field,value)    OK
startswith(field,value)  OK
test(field,value)        NOK (test is not a valid keyword)
equals(field,value)      OK
!startswith(field,value) OK  (optional character ! allowed)
!contains(field,value)   OK  (optional character ! allowed)");

foreach (var capturedgroup in ms.Cast<Match>().ToList())
{
    var action = capturedgroup.Groups["action"].Value;
    var field = capturedgroup.Groups["field"].Value;
    var value = capturedgroup.Groups["value"].Value;
}

Or, in case you have to check the method names as separate strings, use this:
var MyRegex = new Regex("(?<action>\\!?(?:startswith|endswith|contains|equals))\\((?<field>\\w+),(?<value>\\w+)\\)", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant | RegexOptions.Compiled);
var ms = MyRegex.Match(@"!contains(field,value)");
var action = ms.Groups["action"].Value;
var field = ms.Groups["field"].Value;
var value = ms.Groups["value"].Value;

A: This is another one. Prevailing thought is to just move !? outside the parenths.
@"(?<!\S)(?<action>!?(?:startswith|endswith|contains|equals))\((?<field>\w+),(?<value>\w+)\)"
Formatted
 (?<! \S )
 (?<action>                    #_(1 start)
      !?
      (?:
           startswith
        |  endswith
        |  contains
        |  equals
      )
 )                             #_(1 end)
 \(
 (?<field> \w+ )               #_(2)
 ,
 (?<value> \w+ )               #_(3)
 \)


text:
Q: Why bulk states in quantum hall effect do not contribute to electric conductivity Most reviews and textbooks explain quantum hall effect as insulating bulk states and conducting edge states, as is shown in the following picture.

My question is: why bulk states are insulating in quantum hall effect(if one or more landau levels are filled)?
Here is one more consideration:
Some literature says impurity is necessary for insulating bulk states. However, laughlin's gauge argument(http://journals.aps.org/prb/abstract/10.1103/PhysRevB.23.5632) does not contain anything about disorder or impurity. Chern number, which characterises hall response to magnetic field, says nothing about disorder or impurity. Is impurity really necessary to observe QHE?

A: Disorder is necessary to observe the integer quantum Hall effect (IQHE), but it is not necessarily true that current is carried only by the edge states. Disorder gives rise to localized bulk states between Landau levels. It is the existence of these localized states that gives us the broad plateaus in resistivity at integer filling fractions: increasing the Fermi level between Landau levels only occupies localized bulk states. However, just because the bulk states near the Fermi level are localized does not mean that extended bulk states below the Fermi level do not contribute to current flow. The specifics of the current distribution in a sample will depend on sample geometry and probe placement, but there are experiments that confirm the flow of Hall current in the bulk.

A: The tricky part is to explain the plateaus in $\sigma_{xy}$ and why they coincide with vanishings of $\sigma_{xx}$.
To make this more evident let us suppose first you had a system without disorder, say you have an interacting Galilean that is fully translationally invariant. Ideally this would be realized e.g. in a Torus. Then you can show, following Kohn's theorem, that the Hall conductivity is always exactly $\sigma_{xy}=\nu e^2/h$, and that $\sigma_{xx}=0$. This is completely independent of the microscopic state of the system, e.g. it woud be true if you had a Laughlin state or a Charge density wave or anything. It follows from the fact that the center of mass of the system as a whole moves as a free charged particle in electric and magnetic fields. Thus there are no plateaus in this translationally invariant limit: the Hall conductivity traces a straight line when you plot it vs $\nu$.
Therefore, what is non-trivial is to explain why the Hall conductivity gets "stuck" at $\sigma_{xy}=\nu_0 e^2/h$ when you change the filling $\nu$ slightly away from a special filling $\nu_0$, namely, the existence of a "plateau" and its coincidence with the vanishing of $\sigma_{xx}$. Essentially, the picture is that as you change the electron density (filling) away from $\nu_0$, they are added into states localized by the disorder and don't contribute to transport (A caveat is that there can be bulk states deep below the chemical potential that are delocalized and can contribute to current flow, see previous reponse).
In the Laughlin argument, which essentially applies only to non-interacting disordered electrons (i.e. only to the integer quantum Hall effect), after threading a flux quantum the Hamiltonian is the same, but the state has changed into an excited state. In this excited state, the occupation numbers of the single particle eigenstates have changed (we are imagining here the exact eigenstates of the single body problem in the presence of disorder). One needs to argue that the change of electron occupations occurs only at the edge and not in the bulk. This is why the argument relies not only on gauge invariance, but also in the existence of a bulk mobility gap. As long as the chemical potential lies in the bulk mobility gap, the electron occupation will only change at the edge after the flux insertion, and due to electron number conservation, this change is an exact integer which determines the Hall conductivity.


text:
Q: Optimizing a LINQ to SQL query I have a query that looks like this:
public IList<Post> FetchLatestOrders(int pageIndex, int recordCount)
{
    DatabaseDataContext db = new DatabaseDataContext();
    return (from o in db.Orders
            orderby o.CreatedDate descending
            select o)
            .Skip(pageIndex * recordCount)
            .Take(recordCount)
            .ToList();
}

I need to print the information of the order and the user who created it:
foreach (var o in FetchLatestOrders(0, 10))
{
    Console.WriteLine("{0} {1}", o.Code, o.Customer.Name);
}

This produces a SQL query to bring the orders and one query for each order to bring the customer. Is it possible to optimize the query so that it brings the orders and it's customer in one SQL query?
Thanks
UDPATE: By suggestion of sirrocco I changed the query like this and it works. Only one select query is generated:
public IList<Post> FetchLatestOrders(int pageIndex, int recordCount)
{
    var options = new DataLoadOptions();
    options.LoadWith<Post>(o => o.Customer);
    using (var db = new DatabaseDataContext())
    {
        db.LoadOptions = options;
        return (from o in db.Orders
                orderby o.CreatedDate descending
                select o)
                .Skip(pageIndex * recordCount)
                .Take(recordCount)
                .ToList();
    }
}

Thanks sirrocco.

A: Something else you can do is EagerLoading. In Linq2SQL you can use LoadOptions : More on LoadOptions
One VERY weird thing about L2S is that you can set LoadOptions only before the first query is sent to the Database.

A: you might want to look into using compiled queries
have a look at http://www.3devs.com/?p=3

A: Given a LINQ statement like:
context.Cars
  .OrderBy(x => x.Id)
  .Skip(50000)
  .Take(1000)
  .ToList();

This roughly gets translated into:
select * from [Cars] order by [Cars].[Id] asc offset 50000 rows fetch next 1000 rows

Because offset and fetch are extensions of order by, they are not executed until after the select-portion runs (google). This means an expensive select with lots of join-statements are executed on the whole dataset ([Cars]) prior to getting the fetched-results.
Optimize the statement
All that is needed is taking the OrderBy, Skip, and Take statements and putting them into a Where-clause:
context.Cars
  .Where(x => context.Cars.OrderBy(y => y.Id).Select(y => y.Id).Skip(50000).Take(1000).Contains(x.Id))
  .ToList();

This roughly gets translated into:
exec sp_executesql N'
select * from [Cars]
where exists
  (select 1 from
    (select [Cars].[Id] from [Cars] order by [Cars].[Id] asc offset @p__linq__0 rows fetch next @p__linq__1 rows only
    ) as [Limit1]
    where [Limit1].[Id] = [Cars].[Id]
  )
order by [Cars].[Id] asc',N'@p__linq__0 int,@p__linq__1 int',@p__linq__0=50000,@p__linq__1=1000

So now, the outer select-statement only executes on the filtered dataset based on the where exists-clause!
Again, your mileage may vary on how much query time is saved by making the change. General rule of thumb is the more complex your select-statement and the deeper into the dataset you want to go, the more this optimization will help.


text:
Q: Reliable disk image format I've recently ran into disk image corruption issues if the host computer crashes. I'm experimenting with different hardware setups and a host PC crash caused (already a few times) the VHD image to be corrupted. This happened both in VMWare or VirtualBox.
The host machine is Win 10 and so is the hosted image, 100-150GB in size. The image is of an SSD residing on a HDD.
Short of doing a full backup (which is slow) what other options do I have? I could dedicate a partition on the host computer which would likely improve the chances of recovery. I've switched to a VMDK format but not sure if that changes anything. Differential backup/snapshot would be nice but I don't know how to set that up.
Trying to get away with free software as it's home use.


text:
Q: 405 Error With Facebook App From aspx page I'm developing a very simple custom facebook tab in html, consisting of a simple background image and a few links. This page works fine on it's own, but when I go to the facebook canvas page I get this HTTP 405 error,
"The page you are looking for cannot be displayed because an invalid method (HTTP verb) was used to attempt access.
Please try the following:
Contact the Web site administrator if you believe that this request should be allowed.
Make sure that the Web site address displayed in the address bar of your browser is spelled and formatted correctly.
HTTP Error 405 - The HTTP verb used to access this page is not allowed.
Internet Information Services (IIS)"
I have renamed my page from an html file to an aspx file, as per similar questions suggested, but the error persists. What do I need to do to get my page to display? Thanks for any help.
Edit: The html looks like this, I don't know what would be throwing anything off in something so simple.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <title>Title</title>

        Link

Edit in case somebody finds this by googling, the problem was that I didn't have a public facing url because the person in charge of setting up the server had hidden everything so he could try some stuff. Woo internal miscommunication.

A: Probably changing extension of static page from .html to .aspx is not enough, and IIS is still limiting it to only allow GET requests, but visiting application on Facebook passing data to canvas URL via POST.
You can try to follow steps in next KB article http://support.microsoft.com/kb/942051

A: No matter which way you do --
1. renaming a .html to .aspx
2. create a new .aspx file
FB throws the same error. And the same page thing accessed using an iFrame locally works fine.
HTTP Error 405 - The HTTP verb used to access this page is not allowed. Internet Information Services (IIS)
Here is my .aspx code -- please advice if you find any solution.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<%@ Page Language="C#" %>

<meta content="en-us" http-equiv="Content-Language" />
<meta content="text/html; charset=utf-8" http-equiv="Content-Type" />
<title>Create My Resume</title>

<form id="form1" runat="server" class="auto-style1">
    Welcome!</form>

My first Facebook Application!

A: My solution for the 405 error was to rename my index.html to index.php. Obviously in my case, my web server is set up to use php.
Facebook attempts to do a POST to index.html (or whatever the name of the file is), something which I believe most web servers are not set up to allow. (I do believe you can alter these of necessary, in order to keep the .html extension)

A: May be it is a little later for answer, but ...
Rename fiel index.html to default.aspx. If you use aspx hosting, then you have to named index file for your app "default.aspx


text:
Q: Force static route for IP on same subnet? Any way to force the use of a defined host static route when the IP is on the same subnet and disregards the static route entry?
For instance I have a host host:
192.168.1.2 with subnet 255.255.255.0 and a default of 192.168.1.1
I'd like to communicate with 192.168.1.3 via 192.168.1.102.

A: Add the entry to the routing table:
Windows
route add 192.168.1.3 mask 255.255.255.255 192.168.1.102

Linux
route add -host 192.168.1.3 gw 192.168.1.102

However, you will likely have an asymmetric routing condition when return traffic from 192.168.1.3 returns to your 192.168.1.2 host.  That return traffic, unless otherwise configured with a similarly mirrored route, will be directly delivered.

A: Is this Windows? Linux? AIX?
For Windows, this command works fine:
route add 192.168.1.3 mask 255.255.255.255 192.168.1.102
Even if you're inside the 192.168.1.0/24 network, it will attempt to route. I can't vouch for behaviour on other OS's.

A: As stated already, the route to the destination is localy changeable. The way back isn't this way. The reply packets will arrive you direct from host 192.168.1.3. Next, you must make sure. that 192.168.1.102 will forward packages.


text:
Q: Exercise on geometrically connectedness of a scheme I want to prove the following exercise from Götz' & Wedhorn's Algebraic Geometry I on page 144: Chapter 5: Schemes over fields (only part (a); part (b) is a simple consequence):

Exercise 5.23. Let $k$ be a field and let $X$ be a connected $k$-scheme.
  (a) Assume that there exists a non-empty geometrically connected $k$-scheme $Y$ and a
  $k$-morphism $f:Y \to X$. Show that $X$ is geometrically connected.
Hint: Use Exercise 5.22 to show that $X_{\Omega} \to X$ is open, closed, and surjective for
  a separable closure $\Omega$ of $k$ and show that there are no nontrivial open and closed
  subsets of $X_{\Omega}$.

Q: I haven't found the key to show the last part of the exercise that there are no nontrivial open and closed subsets in $X_{\Omega}$.
By proposition 5.53 $X$ is geometrically connected if and only if $X_K= X \times_k Spec \text{ } K$ is connected for certain separable closed field extension
$k \to K$. thus it suffice to show that $X_{\Omega}$ is connected. because $Y$ is gemetrically connected, the pullback $Y_{\Omega}$ is connected. in addition I partially succeed in proving 5.22 except of the $p:X_{\Omega} \to X$ is open part (???). does it follow from the 'closed' part? I don't see it.
if we continue with the main claim to show that $X_{\Omega}$ is connected then let assume that $X_{\Omega}$ is not connected and we can find a non empty open & closed proper subset $U \subsetneqq X_{\Omega}$. then $p(U)$ is also non empty, open & closed in $X$ and therefore $p(U)= X$ because $X$ connected and $p$ open& closed. Similary  $p(X_{\Omega} \backslash U)= X$.
in addition since $Y_{\Omega}$ is connected one the preimages of $U$ or $X_{\Omega} \backslash U$ under induced map $f_{\Omega}: Y_{\Omega} \to X_{\Omega}$ is empty and the other the whole $Y_{\Omega}$.  at this point I'm a bit lost. can I obtain from this observations a contradiction on non emptyness of $U$?

A: The hint refers to 5.22:

Exercise 5.22. Let $A\to B$ be an integral ring homomorphism. Show that the corresponding morphism of schemes $\operatorname{Spec} B\to \operatorname{Spec} A$ is universally closed. Deduce that if $K$ is an algebraic extension of a field $k$, then the projection $X_K\to X$ is universally open, universally closed, and surjective.

You mention you have not yet proven that $X_K\to X$ is universally open. If we prove this, then we have that $X_\Omega\to X$ is universally open, universally closed and surjective, and then we're in the situation of your other post that I responded to, where the appropriate fiber product diagram is
$\require{AMScd}$
\begin{CD}
Y_\Omega @>p_X>> X_\Omega\\
@Vp_YVV @VVfV\\
Y @>g >> X
\end{CD}
where all the schemes besides $X_\Omega$ are connected by assumption. Thus $X_\Omega$ must also be connected by the result at that question.
In order to prove that $X_\omega\to X$ is universally open, it is enough to prove that $\operatorname{Spec} K\to \operatorname{Spec} k$ is universally open for an algebraic field extension $k\subset K$. By a standard locality argument, it's enough to check this on affines. So we want to check that for $R$ any $k$-module, the map $R\to R\otimes_k K$ is open. It suffices to prove that the image of a standard open $D(f)$ is again open for $f\in R\otimes_k K$. In order to do this, pick some finite algebraic $k$-subfield of $F\subset K$ so that $f\in R\otimes_kF$. Then $R\to R\otimes_kF$ is flat and finitely presented, so the image of $D(f)$ from this map is open, and it is the same image as we get when considering $D(f)$ coming from $R\otimes_kK$.
To prove that the images are the same, consider the obvious commutative triangle of schemes $\operatorname{Spec}(R\otimes_k K)_f \stackrel{\alpha}{\to} \operatorname{Spec}(R\otimes_k F)_f \stackrel{\beta}{\to} \operatorname{Spec} R$ where the third side $\beta\circ\alpha$ isn't drawn since diagrams here are difficult. Suppose a prime ideal $p\subset R$ is in the image of $\beta$. This means that $(R\otimes_k F)_f\otimes_R \kappa(p) = (F\otimes_k \kappa(p))_f$ is nonzero, so $F\otimes_k\kappa(p)$ is nonzero and the image of $f$ in it is not nilpotent. Next, the ring map $F\otimes_k \kappa(p)\to K\otimes_k \kappa(p)$ is injective, so $(R\otimes_k K)\otimes_R\kappa(p) = K\otimes_k \kappa(p)$ is not the zero ring and the image of $f$ in it is not nilpotent. So $(R\otimes_k K)\otimes_R \kappa(p)$ isn't the zero ring and we've shown what we wanted.


text:
Q: Problem with fitting a given data with an equation I want to fit a given data using the approach developed by @Bob Hanlon here: Fit and find fitting parameters of data given an equation
I have tried this approach for several different data sets but I have one in particular where the equation does not seem to fit the data very well but it is not very clear to me why or if I can "tweak the equation" or the parameters to make it fit well.
Here's the my data and the code I am using:
hey = {{-2.`, 0.3650687761296365`}, {-1.5228787452803376`,
   0.35024185145494713`}, {-1.`,
   0.35008362652827657`}, {-0.5228787452803376`,
   0.35002569469868255`}, {-4.821637332766436`*^-17,
   0.3690654823479624`}, {0.4771212547196624`,
   0.4295109082336017`}, {1.`,
   0.5336781026939912`}, {1.4771212547196624`,
   0.7942359842488445`}, {2.`,
   1.3736241822734323`}, {2.4771212547196626`,
   2.0178692522958217`}, {3.`,
   2.2855926539783797`}, {3.477121254719662`,
   2.2855974030998034`}, {4.`, 2.2855975424841546`}}

(nlmp = NonlinearModelFit[
    hey, {2.2856 (1 - Exp[-(10^logt/tauc)^bc]), bc <= 1}, {tauc, bc},
    logt]) // Normal

nlmp["BestFitParameters"]

Show[

 ListPlot[hey, PlotMarkers -> {Automatic, 13}, AspectRatio -> 1 ,
  Frame -> True, PlotRange -> All, Axes -> False, ImageSize -> Medium,
   AspectRatio -> 1, FrameStyle -> Directive[Black, 13],
  FrameLabel -> {Style["Log (\!\(\*SubscriptBox[\(t\), \(a\)]\) / s)",
      16],
    Style["\[CapitalDelta]H (\!\(\*SuperscriptBox[\(Jg\), \(-1\)]\))",
      16]}, PlotLabel -> Style[Ta[[8 + 1]] "ºC", Black, 14]],

 Plot[nlmp[logt], {logt, -2.2, 4.2}, PlotRange -> All,
  AspectRatio -> 1, Frame -> True, Axes -> False, AspectRatio -> 1,
  FrameStyle -> Directive[Black, 13],
  FrameLabel -> {Style["Log (\!\(\*SubscriptBox[\(t\), \(a\)]\) / s)",
      16], Style[
     "\!\(\*SubscriptBox[\(\[CapitalDelta]H\), \(a\)]\) (J/g)", 16]},
  Epilog -> {Red, AbsolutePointSize[4], Point[datac]}]

 ]

Which gives the following fit:

I have also tried simply using
(nlmp = NonlinearModelFit[hey, {2.2856 (1 - Exp[-(10^logt/tauc)^bc])**+ 0.35**, bc <= 1}, {tauc, bc},logt]) // Normal
and it of course fixes the fit in the bottom part but now the problem is in the upper part.
Question:
What is wrong with this particular data set and How could I modified the equation to make a correct fit (the lower part of the data is not correctly fitted)?
For reference, the fitting equation that I am using in nlmp is:

A: The equation you show will never fit your data because it cannot reproduce the asymptotic behavior at negative logt. You need to add a constant vertical offset for it do so:
nlm = NonlinearModelFit[
   hey, {deltaHinf (1 - E^-(10^logt/tau0)^beta) + const, beta <= 1},
   {{deltaHinf, 2.2}, {beta, 0.6}, {tau0, 200}, {const, 0.2}},
   logt
   ];

Show[
 Plot[nlm[logt], Evaluate@Flatten@{logt, MinMax[hey[[All, 1]]]}],
 ListPlot[hey, PlotStyle -> Black]
]

nlm["BestFitParameters"]

(* Out: {deltaHinf -> 1.9366,
         beta -> 0.878246,
         tau0 -> 138.601,
         const -> 0.351186} *)

BUT!! (and this is a big but), can you justify that offset physically within your model?


text:
Q: Is verifying a file's extension enough to know that the file isn't hiding a virus (or something that can infiltrate my server)? I'm developing a system where the user will be able to upload a ".docx" file. Is verifying it's extension enough to know that this ".docx" file isn't infected?
Here's my upload PHP code:
<?php
session_start();

include("connection.php");
include("functions.php");

// Just to validate the user
$user_data = check_login($con);

include("connectionPostsDB.php");

if (isset($_POST['submit'])){

    $title = $_POST['title'];
    $tag = $_POST['tag'];
    $description = $_POST['description'];

    $file = $_FILES['file'];

    $fileName = $_FILES['file']['name'];
    $fileTmpName = $_FILES['file']['tmp_name'];
    $fileSize = $_FILES['file']['size'];
    $fileError = $_FILES['file']['error'];
    $fileType = $_FILES['file']['type'];

    $fileExt = explode('.', $fileName);
    $fileActualExt = strtolower(end($fileExt)); //here I get the actual file's extension (I hope xD)

    $allowed = array('docx');

    if(in_array($fileActualExt, $allowed)){
        if($fileError === 0){
            if($fileSize < 1000000){
                $fileNameNew = uniqid('', true).".".$fileActualExt;
                $fileDestination = '../imgs/posts/'.$fileNameNew;
                move_uploaded_file($fileTmpName, $fileDestination);

                $query = "INSERT INTO posts (title, descr, imgname, tag)
                          VALUES ('".$title."','".$description."','".$fileNameNew."','".$tag."')";

                mysqli_query($postcon, $query);

                echo 'File successfully uploaded';
            }
            else {
                echo 'Your file is too big.';
            }
        }
        else {
            echo 'There was an error uploading your file.';
        }
    }
    else {
        echo 'This type of file not allowed.';
    }

}

So, me checking for the file's extension is enough to prevent some user to put some php code in my server (or do something to get information from the server)?

A: No, just checking the extension isn't enough, however the main question is what you exactly mean by safe.
The code you've shown only stores the file on your server (under a server-generated name), and then publishes its existence in the database. Neither of those things themselves would be dangerous, even if the file contained the digital equivalent of the black plague.
But let's first take a step back; your SQL query is very much unsafe, though that has nothing to do with the uploaded files. You should read up on prepared statements as your entire site is wide open to SQL injection when you create queries this way.

Now, back on topic:
There are at least 2 things you could explore in order to become more relaxed about the .docx file being what it should be.

*

*As far as i know, the docx format is really just a .zip file with some .xml files inside. PHP understands both those formats, so you could attempt to unzip it's contents, see if it contains the sorts of files you expect, including xml(s), and then see if those XML files are parse-able.

*You could feed the uploaded file to a virusscanner

Neither of these methods is full proof, but they will both illuminate the situation a bit, allowing you (more specifically, your algorithm) to make a more informed decision.
Now as for what i ment with "what you exactly mean by safe". The actions you take here (merely renaming and storing the file and writing text to a database) are fundamentally pretty safe.
But i imagine there is someone or something else, on the other side of that database, that reads the same DB table, and allows someone to either open and or download that file. Now that action does actually have a lot of security implications.
Now if that database is only viewed through your application, then you could theoretically waive all responsibility and say "this file was anonymously uploaded by god knows who, treat it as if it arrived in your emails junk folder by unknown sender". But if you're taking any level of responsibility (be it implied or literal), you'll have to verify it to whatever degree you're comfortable with.

A: Nope, it's never enough just chekcing the file extension because we can set .docx extension to any file type.
We should also check many more things like:

*

*Is the mime type of the file expected?

*Is the file size reasonable enough. For example, if someone upload a 25 GB docx file, then even if it's a valid docx file your server might go down.

*Ideally you shouldn't upload any file in any production server instead you should upload in any storage provider like s3 bucket of AWS. So that even if that file is executable it's not being executed in your server. It's uploaded into a different server that is well optimized to handle files.

And many more such things to consider.


text:
Q: WPF Dragging elements from listbox In my WPF application I've got a listbox with DataTemplate defined as follows:
 <DataTemplate x:Key="ListBoxTemplate">
            <ui:TaskMonthPreview/>
 </DataTemplate>

and TaskMonthPreview is my custom control defined as follows:
<UserControl x:Class="Lista.TaskMonthPreview"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Height="30" Width="100">

    <UserControl.Resources>
        <ResourceDictionary>
            <ControlTemplate x:Key="TaskView" TargetType="Thumb">

                <Rectangle
                Name="rectangle1"
                Stroke="Chocolate"
                HorizontalAlignment="Left"
                Width="{TemplateBinding Width}"
                Height="{TemplateBinding Height}"
                Fill="LightSkyBlue"/>

            </ControlTemplate>
        </ResourceDictionary>
    </UserControl.Resources>

        <Thumb Name="myThumb"  Background="Blue"
          Width="100" Height="20" DragDelta="onDragDelta"
          DragStarted="onDragStarted" DragCompleted="onDragCompleted" HorizontalAlignment="Left"
          Template="{StaticResource TaskView}"/>

</UserControl>

My Thumb in TaskMonthPreview is dragabble but unfortunatelly it cannot be dragged outside the area of TaskMonthPreview. Is is possible to enable dragging my thumb outside the scope of TaskMonthPreview and even outside the scope of listbox?


text:
Q: Flutter Cloud Firestore issue initializing futures I am trying to get my first cloud firestore app working, using the firestore_flutter master example for cloud firestore as a template. In the example app main.dart has all the firestore and other init and access logic, and consequently runs the Futre void() main() method as in the example main.dart section copy below. It does not have the
====================
import...

Future<void> main() async {
  WidgetsFlutterBinding.ensureInitialized();
  final FirebaseApp app = await FirebaseApp.configure(
    name: 'test',
    options: const FirebaseOptions(
      googleAppID: '1:79601577497:ios:5f2bcc6ba8cecddd',
      gcmSenderID: '79601577497',
      apiKey: 'AIzaSyArgmRGfB5kiQT6CunAOmKRVKEsxKmy6YI-G72PVU',
      projectID: 'flutter-firestore',
    ),
  );
  final Firestore firestore = Firestore(app: app);

  runApp(MaterialApp(title: 'Firestore Example', home: MyHomePage(firestore: firestore)));
}

class MyHomePage extends StatelessWidget {
  MyHomePage({this.firestore});
  final Firestore firestore;
  CollectionReference get messages => firestore.collection('messages');

====================
But in my app I want to load the data in the 3rd page after authenticating users with firebase_auth, but the main Future function never gets called (only 1 main right?)
Here is my code that does not work because main() never gets called. What do I need to do to make the code below work? PS: I tried making it a called function, moving it, but I am not able to make main run in my page source below.
It doesn't have the next line from teh example in it, because it didn't help either.
runApp(MaterialApp(title: 'Firestore Example', home: TopicList(firestore: firestore)));}
Thanks for any help in advance.
====================
import ...

Future<void> main() async {
  WidgetsFlutterBinding.ensureInitialized();
  final FirebaseApp app = await FirebaseApp.configure(
    name: 'test',
    options: const FirebaseOptions(
      googleAppID: 'AIzaSyBPq8j3NT5DMmVgXLEN3Z91QJK32ZhrH90',
      gcmSenderID: '36424891892',
      apiKey: 'AIzaSyArgmRGfB5kiQT6CunAOmKRVKEsxKmy6YI',
      projectID: 'usay-94b3a',
    ),
  );
  final Firestore firestore = Firestore(app: app);
}

class MessageList extends StatelessWidget {
  MessageList({this.firestore});
  final Firestore firestore;

  @override
  Widget build(BuildContext context) {
    return StreamBuilder<QuerySnapshot>(
      stream: firestore.collection("message").orderBy("timestamp", descending: true).snapshots(),
      builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot) {
        if (!snapshot.hasData) return const Text('Loading...');
        final int messageCount = snapshot.data.documents.length;
        return ListView.builder(
          itemCount: messageCount,
          itemBuilder: (_, int index) {
            final DocumentSnapshot document = snapshot.data.documents[index];
            final dynamic message = document['message'];
            return ListTile(
              trailing: IconButton(
                onPressed: () => document.reference.delete(),
                icon: Icon(Icons.delete),
              ),
              title: Text(
                message != null ? message.toString() : '<No message retrieved>',
              ),
              subtitle: Text('Message ${index + 1} of $messageCount'),
            );
          },
        );
      },
    );
  }
}

class TopicList extends StatelessWidget {
  TopicList({this.firestore});
  final Firestore firestore;
  CollectionReference get messages => firestore.collection('message');

  Future<void> _addMessage() async {
    await messages.add(<String, dynamic>{
      'messageTitle': 'Hello world!',
      'messageDescription': 'Hello world!',
      'timestamp': FieldValue.serverTimestamp(),
    });
  }

  Future<void> _runTransaction() async {
    firestore.runTransaction((Transaction transaction) async {
      final allDocs = await firestore.collection("message").getDocuments();
      final toBeRetrieved = allDocs.documents.sublist(allDocs.documents.length ~/ 2);
      final toBeDeleted = allDocs.documents.sublist(0, allDocs.documents.length ~/ 2);
      await Future.forEach(toBeDeleted, (DocumentSnapshot snapshot) async {
        await transaction.delete(snapshot.reference);
      });

      await Future.forEach(toBeRetrieved, (DocumentSnapshot snapshot) async {
        await transaction.update(snapshot.reference, {
//          "messageTitle": FieldValue.messageTitle,
//          "messageDescription": FieldValue.messageDescription",
          "timestamp": FieldValue.serverTimestamp()
        });
      });
    });

    await Future.forEach(List.generate(2, (index) => index), (item) async {
      await firestore.runTransaction((Transaction transaction) async {
        await Future.forEach(List.generate(10, (index) => index), (item) async {
          await transaction.set(firestore.collection("message").document(), {
            "messageTitle": "Created from Transaction $item",
            "messageDescription": "Created from Transaction $item",
            "timestamp": FieldValue.serverTimestamp()
          });
        });
      });
    });
  }

  Future<void> _runBatchWrite() async {
    final batchWrite = firestore.batch();
    final querySnapshot = await firestore.collection("message").orderBy("timestamp").limit(12).getDocuments();
    querySnapshot.documents.sublist(0, querySnapshot.documents.length - 3).forEach((DocumentSnapshot doc) {
      batchWrite.updateData(doc.reference, {
        "messageTitle": "Batched messageTitle",
        "messageDescription": "Batched messageDescription",
        "timestamp": FieldValue.serverTimestamp()
      });
    });
    batchWrite.setData(firestore.collection("message").document(), {
      "messageTitle": "Batched message created",
      "messageDescription": "Batched message created",
      "timestamp": FieldValue.serverTimestamp()
    });
    batchWrite.delete(querySnapshot.documents[querySnapshot.documents.length - 2].reference);
    batchWrite.delete(querySnapshot.documents.last.reference);
    await batchWrite.commit();
  }

  @override
  Widget build(BuildContext context) {
    return FittedBox(
      fit: BoxFit.scaleDown,
      child: Scaffold(
        appBar: AppBar(
          title: const Text('Firestore Example'),
          actions: <Widget>[
            FlatButton(
              onPressed: _runTransaction,
              child: Text("Run Transaction"),
            ),
            FlatButton(
              onPressed: _runBatchWrite,
              child: Text("Batch Write"),
            )
          ],
        ),
        body: MessageList(firestore: firestore),
        floatingActionButton: FloatingActionButton(
          onPressed: _addMessage,
          tooltip: 'Increment',
          child: const Icon(Icons.add),
        ),
      ),
    );
  }
}

===============


text:
Q: How to Set Up the Gmail Mailer in WP Mail SMTP Got real life feedback from users on my weblog that they couldn't send emails anymore even though this was working.
I'm using WP Mail SMTP with Gmail, which was previously configured.
After going to the admin panel, under WP Mail SMTP > Email Test:

You cannot send an email. Mailer is not properly configured. Please
  check your settings.

How can this be fixed?

A: This link has everything we need to know about this configuration.
In order to fix this problem I just followed the next two steps

*

*Create a Web App in Your Google Account

*Grant Permissions and Send Test Email
The tricky part is somewhere in step 2 where we are going to get a login screen for Google. Once logging in, I got a not secure page

had to click advanced

and click Go to tiagoperes.eu unsafe.
Only then was able to see a screen asking for permission for this site to send email on my behalf.
Then, under WP Mail SMTP > Email Test:

Once clicking it, received the email so the problem is solved.


text:
Q: Python reads only the formula from excel cell I have a excel 2010 file which has cells (See C2 below in formula bar) with formulae. (Screenshot 1 below)

I am reading the value using python and it's printing the formula instead of actual value of the cell (Screenshot below of eclipse console.)

I want the results to print 10.188.11.184 which is the value populated by the formula of the excel cell. How can this be achieved? Thanks in advance.

A: From:
https://openpyxl.readthedocs.org/en/latest/usage.html#read-an-existing-workbook
data_only controls whether cells with formulae have either the formula (default) or the value stored the last time Excel read the sheet.
wb = load_workbook('file.xlsx', data_only=True)

A: You can use xlrd module and do the reading easily.
read_fullreport = xlrd.open_workbook(report_to_read)
read_fullreport_sheet = read_fullreport.sheet_by_index(0)
ipAddressofMC = read_fullreport_sheet.cell_value(row_nr, col_nr)