text:
Q: environment specific variables in pingfederate templates I am customizing a pingfederate temaplte (for login).
As part of this customization I would like to be able to have a java script variable that is dependent on the configuration of the form being used. Essentially to distinguish between a test and a live environment.
I'm trying to keep the templates in source control and not have duplicated code and also to be able to test configurations before I deploy.
I'd like to think that I could set a variable somewhere in the admin interface and get this exposed in the template, however I have found nothing in the documentation to suggest that this is possible.
Is there a way to do this, or a reasonable work around?

A: From the perspective of PingFederate itself, no. There are plenty of mechanisms in Javascript that you could use, like window.location.host to trigger CSS properties. You could even use the Velocity variable of $PingFedBaseURL to drive CSS properties.


text:
Q: Minimum wins needed to advance into Let's say we have $16$ teams and the teams are divided into two groups of $8$ teams each.
Each team in a group played exactly one match against every other team in that group. No match ended in a draw. This is the first stage.
At the end of the first stage, the top four teams from each group advanced to the second stage while the rest got eliminated. At the end of the first stage, top four teams in each group were determined on the basis of total number of matches won by individual teams.
My question is how can we figure out the minimum number of wins needed by any team from one group to proceed into the second stage. What if the numbers are huge i.e. let's say there are $56$ teams in a group? Is there any formula or easy way to determine this value?
Please help !!!!
Thanks in advance !!!

A: Unlucky case: If there are $n$ teams and $m$ go through, it is possible for $m+1$ teams to win $(n-m-1) + \Big\lfloor\frac m2\Big\rfloor$ games each with one of these teams failing to go through (it cannot be more, as there are not enough games between these $m+1$ teams), so you need to win one more than this i.e. $n-\Big\lceil\frac m2\Big\rceil$ games to be certain of going through
Lucky case: If there are $n$ teams and $m$ go through, it is possible for $n-m+1$ teams to win just $\Big\lceil \frac{n-m}{2}\Big\rceil$ games each with one of these managing to go through (there may need to be a tie-break to decide which one)
Examples:

*

*with $n=8$ teams and $m=4$ going through, you need to win $6$ out of $7$ games to be sure of going through, while you might go through winning $2$ out of $7$ games

*with $n=56$ teams and $m=28$ going through, you need to win $42$ out of $55$ games to be sure of going through, while you might go through winning $14$ out of $55$ games

*with $n=56$ teams and $m=4$ going through, you need to win $54$ out of $55$ games to be sure of going through, while you might go through winning $26$ out of $55$ games

A: HINT:
For $2n$ teams in the tournament you described $n = 2m$ teams in a group ($n$ is an even integer), by the pigeon principle, the first team have at least $k_1 = \lceil\dfrac{n(n+1)}{2\cdot n}\rceil $ wins to advance. The second, $k_2 = \lceil\dfrac{\dfrac{n(n+1)}{2}-k_1}{n-1}\rceil$, and try to find the formula for $k_{m}$, the last team that would advance.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to log out of your android studio account using Firebase Auth? There is an application with Firebase Auth, the sign out function lies in the MainActivity, but the output must be implemented from the MenuActivity, Intent does not work because the input is executed and the user value is initialized. Need to call the function sign Out of other activities, I don't know how to do it, please explain or tell where to read about it.
MainActivity
package com.example.ecohelp;

    import android.app.Activity;
    import android.content.Intent;
    import android.os.Bundle;
    import android.text.TextUtils;
    import android.util.Log;
    import android.view.View;
    import android.widget.EditText;
    import android.widget.Toast;
    import android.app.ProgressDialog;

    import com.google.firebase.FirebaseApp;
    import com.google.firebase.auth.FirebaseAuth;
    import com.google.firebase.auth.FirebaseUser;

public class MainActivity extends Activity implements
    View.OnClickListener {
private static final String TAG = "EmailPassword";

private EditText mEmailField;
private EditText mPasswordField;
public ProgressDialog pd;

protected FirebaseAuth mAuth;

@Override
public void onCreate(Bundle savedInstanceState) {
    FirebaseApp.initializeApp(this);
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    mEmailField = findViewById(R.id.fieldEmail);
    mPasswordField = findViewById(R.id.fieldPassword);

    findViewById(R.id.emailSignInButton).setOnClickListener(this);
    findViewById(R.id.emailCreateAccountButton).setOnClickListener(this);

    mAuth = FirebaseAuth.getInstance();
}

@Override
public void onStart() {
    super.onStart();
    FirebaseUser currentUser = mAuth.getCurrentUser();
    updateUI(currentUser);
}

private void createAccount(String email, String password) {
    Log.d(TAG, "Создание аккаунта" + email);
    if (validateForm()) {
        return;
    }
    pd = new ProgressDialog(this);

    pd.show();
    pd.setMessage("Регистрация");

    mAuth.createUserWithEmailAndPassword(email, password).addOnCompleteListener(this, task -> {
        if (task.isSuccessful()) {
            pd.hide();
            Log.d(TAG, "Аккаунт успешно создан");
            FirebaseUser user = mAuth.getCurrentUser();
            updateUI(user);
        } else {
            pd.hide();
            Log.w(TAG, "Ошибка создания аккаунта", task.getException());
            Toast.makeText(MainActivity.this, "Ошибка создания аккаунта",
                    Toast.LENGTH_SHORT).show();
            updateUI(null);
        }

    });
}

private void signIn(String email, String password) {
    Log.d(TAG, "Вход" + email);
    if (validateForm()) {
        return;
    }
    pd = new ProgressDialog(this);
    pd.show();
    pd.setMessage("Вход");

    mAuth.signInWithEmailAndPassword(email, password)
            .addOnCompleteListener(this, task -> {
                if (task.isSuccessful()) {
                    pd.hide();
                    Log.d(TAG, "Вход через почту успешен");
                    FirebaseUser user = mAuth.getCurrentUser();
                    updateUI(user);
                } else {
                    pd.hide();
                    Log.w(TAG, "Вход не вошелся", task.getException());
                    Toast.makeText(MainActivity.this, "Ошибка входа",
                            Toast.LENGTH_SHORT).show();
                    updateUI(null);
                }

            });
}

private boolean validateForm() {
    boolean valid = true;

    String email = mEmailField.getText().toString();
    if (TextUtils.isEmpty(email)) {
        mEmailField.setError("Пусто");
        valid = false;
    } else {
        mEmailField.setError(null);
    }

    String password = mPasswordField.getText().toString();
    if (TextUtils.isEmpty(password)) {
        mPasswordField.setError("Пусто");
        valid = false;
    } else {
        mPasswordField.setError(null);
    }

    return !valid;
}

protected void signOut() {
    mAuth.signOut();
    updateUI(null);
}

private void updateUI(FirebaseUser user) {
    pd = new ProgressDialog(this);
    pd.hide();
    if (user != null) {
        Intent intent = new Intent(MainActivity.this, Menu.class);
        startActivity(intent);

    }

}

@Override
public void onClick(View v) {

    int i = v.getId();
    if (i == R.id.emailCreateAccountButton) {
        createAccount(mEmailField.getText().toString(), mPasswordField.getText().toString());
    } else if (i == R.id.emailSignInButton) {
        signIn(mEmailField.getText().toString(), mPasswordField.getText().toString());
    }

}

MenuActivity
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;

public class Menu extends Activity implements View.OnClickListener {

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    super.setContentView(R.layout.activity_menu);

}

public void onClick(View v) {
        int i = v.getId();
        if (i == R.id.map) {
            Intent intent = new Intent(this, MapsActivity.class);
            startActivity(intent);
        } else if (i == R.id.signOut) {

        }

    }
}

MenuActivity.xml
<Button
    android:id="@+id/map"
    android:layout_width="164dp"
    android:layout_height="61dp"
    android:layout_marginStart="8dp"
    android:layout_marginTop="8dp"
    android:layout_marginEnd="8dp"
    android:layout_marginBottom="8dp"
    android:backgroundTint="@color/maps"
    android:text="@string/map"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintHorizontal_bias="0.497"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    app:layout_constraintVertical_bias="0.451" />

<Button
    android:id="@+id/signOut"
    android:layout_width="88dp"
    android:layout_height="wrap_content"
    android:layout_marginTop="8dp"
    android:layout_marginEnd="8dp"
    android:layout_marginRight="8dp"
    android:text="@string/signOut"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintTop_toTopOf="parent" />

ActivityMain.xml
<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <TableRow
        android:layout_width="422dp"
        android:layout_height="359dp">

        <ImageView
            android:id="@+id/imageView2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@drawable/aaaaaaaaaaa" />
    </TableRow>

    <LinearLayout
        android:layout_width="434dp"
        android:layout_height="225dp"
        android:orientation="vertical">

        <EditText
            android:id="@+id/fieldEmail"
            android:layout_width="match_parent"
            android:layout_height="87dp"
            android:ems="10"
            android:hint="@string/email"
            android:inputType="textEmailAddress" />

        <EditText
            android:id="@+id/fieldPassword"
            android:layout_width="match_parent"
            android:layout_height="84dp"
            android:ems="10"
            android:hint="@string/password"
            android:inputType="textPassword" />
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="69dp"
        android:orientation="horizontal">

        <Button
            android:id="@+id/emailCreateAccountButton"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="@string/createAccount" />

        <Button
            android:id="@+id/emailSignInButton"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="@string/signIn" />
    </LinearLayout>

</LinearLayout>

A: You can logout From current activity and then Use Intent to navigate into another activity.
public void onClick(View v) {
    int i = v.getId();
    if (i == R.id.map) {
        Intent intent = new Intent(this, MapsActivity.class);
        startActivity(intent);
    } else if (i == R.id.signOut) {

         FirebaseAuth.getInstance.signOut();
         Intent navigateIntent=new Intent(CurrentActivity.this,SecondActivity.class);
         startActivity(navigateIntent);
           //so that when you click the back button, you won't have to able to go back the previous activity
         finish();
    }

}
}


text:
Q: some app that can be installed without going through the app store and without a jailbreak? some app that can be installed without going through the app store and without a jailbreak? They use a mechanism of sharing of appleID,but i can't know how to use it

A: You can install applications onto an iOS device using the program Xcode:
https://developer.apple.com/xcode/


text:
Q: Unseen category in validation set gives error when using Keras I have data that consists of numerical and categorical variables. The categorical variables have a lot of categories so I'm using Embeddings to represent these. My model is a simple neural network.
I know that when you define the Embedding layer you need to pass input_dim=number of categories + 1 in order to account for unseen-in-training categories. This is what I had done.
Also, when encoding these categories to numerical values in order to input them into the neural network I have done the following:
1. Enumerate all the unique values in the training set and put them into a dictionary. Save also a variable called num_values which is the number of unique categories + 1.
2. For the validation set, if the value is not in the dictionary then I give it the value of num_values.
This introduces a problem because when I want to evaluate the model (using model.predict()) I get an error like:
tensorflow.python.framework.errors_impl.InvalidArgumentError: indices[0,0] = 118752 is not in [0, 118752)

This is because I had an unseen-before category in the validation set in some variable, and it was mapped to num_values, but num_values is never assigned to any category in the training set because the dictionary building takes place on the training set. I don't how to solve this issue.
I am using Keras 2.3.1 and Tensorflow 1.13.1
The relevant code:
class EmbeddingMapping:
    """
    An instance of this class should be defined
    for each categorical variable you want to use.
    """
    def __init__(self, series: pd.Series) -> None:
        # get a list of unique values
        values = series.unique().tolist()

        # dictionary mapping
        self.embedding_dict: Dict[str, int] = {value: int_value + 1 for int_value, value in enumerate(values)}
        self.num_values: int = len(values) + 1  # +1 for unknown categories

    def get_mapping(self, value: str) -> int:
        # return value if it was seen in training
        if value in self.embedding_dict:
            return self.embedding_dict[value]
        # else return num_values which is the same for all
        # unseen values
        else:
            return self.num_values

# build mappings
res_dict_train: Dict[str, EmbeddingMapping] = {}
res_dict_val: Dict[str, EmbeddingMapping] = {}
for var in categorical_features:
    embd_train = EmbeddingMapping(X_train_categorical[var])

    temp_series_train = X_train_categorical[var].apply(embd_train.get_mapping)
    temp_series_val = X_val_categorical[var].apply(embd_train.get_mapping)

    res_dict_train[var] = temp_series_train
    res_dict_val[var] = temp_series_val

X_train_categorical = X_train_categorical.assign(**res_dict_train)
X_val_categorical = X_val_categorical.assign(**res_dict_val)

# Keras
# Categorical vars
models_lst = []
inputs = []
for cat_feature in categorical_features:
    print('---------------------------------------')
    print(f'Info for categorical feature {cat_feature}')
    input_i = Input(shape=(1,), dtype='int32')
    inputs.append(input_i)
    num_categories = EmbeddingMapping(X_train_categorical[cat_feature]).num_values
    print(f"Number of categories: {num_categories}")
    embedding_size = min(np.ceil(num_categories/2), 50)     # rule of thumb
    embedding_size = int(embedding_size)
    print(f'Embedding size: {embedding_size}')
    model_i = Embedding(input_dim=num_categories, output_dim=embedding_size, input_length=1, name=f'embedding_{cat_feature}')(input_i)
    model_i2 = Reshape(target_shape=(embedding_size,))(model_i)

    models_lst.append(model_i2)

# layer for numerical
input_numerical = Input(shape=(len(numerical_features),), dtype='float32')
numerical_model = Reshape(target_shape=(2,))(input_numerical)
models_lst.append(numerical_model)
inputs.append(input_numerical)

concatenated = concatenate(models_lst, axis=-1)
mymodel = Dense(50, activation="relu")(concatenated)
mymodel2 = Dense(15, activation="relu")(mymodel)
mymodel3 = Dense(1, activation='sigmoid')(mymodel2)

final_model = models.Model(inputs, mymodel3)

final_model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['acc', 'binary_accuracy'])

final_model.fit(x=train_input_list, validation_data=(val_input_list, y_val), y=y_train, epochs=1, batch_size=128)

I get the error when the epoch ends and the model tries to compute validation statistics.

A: with this line:
self.embedding_dict: Dict[str, int] = {value: int_value + 1 for int_value, value in enumerate(values)}

you are adding +1 to all your integer encoding so you are transforming your values from [0,max_cat] to [1,max_cat+1] and that it's correct
but doing this, the best way to encode unseen categories is with 0, so you have to modify:
    def get_mapping(self, value: str) -> int:
        # return value if it was seen in training
        if value in self.embedding_dict:
            return self.embedding_dict[value]
        # else return 0 which is the same for all unseen values
        else:
            return 0

hope this can help you


text:
Q: Matplotlib with Tkinter notebook I am trying to build up a program using Tkinter and Matplotlib which the user can select among several functions thorough a checkbutton and plotting the selected function using a plot button. The resulted plots must be stored into a tabs of a Tkinter notebook, I mean, every time the plot button is clicked, the generated graph must appear in a new tab. For this aim, I have created two classes, the first one creates the GUI and the second one makes the graphs. I am facing two problems, when I imported the Matplotlib charts into a tab of the Tkinter notebook, the toolbar is not imported, all what I got was the image of the function but I really need the toolbar with the cursor position tool. Moreover, every time I clicked the plot button, the next graph is overlapped with the old one, it is supposed that the old graph have been destroyed. Finally, if I dont import the matplotlib charts into a Tkinter notebook, the programs plots correctly the first time but when I clicked the plot button a second time, all what I got was a blank canvas. I have tried a lot of things but I cannot figured out what is going on here.
I know there are many problems but I would appreciate a lot your help.
Thank you in advance.
GUI:
from stack2 import *
import numpy as np
from tkinter import ttk
from tkinter.ttk import *
from tkinter import *

class Gui:

    # Attributes of the class

    # Array to store the objects
    objects = np.array([])

    # Dictionary to store the data
    data = {
        "x": np.array(
            [
                0,
                2.216666667,
                4.216666667,
                6.216666667,
                23.48333333,
                70.83333333,
                143.8333333,
            ]
        ),
        "y": np.array([0, 0.3812, 0.59375, 0.6176, 0.6165, 0.39845, 0.2692]),
    }

    # Constructor function
    def __init__(self, title, width, height, foreground, background):

        # Attributes of the instance
        self.root = Tk()  # Root
        self.title = title  # Title
        self.height = height  # Height
        self.width = width  # Width
        self.foreground = foreground  # Foreground
        self.background = background  # Background color

    # Method of the class

    # Function for setting the style of each button
    def buttonStyle(self):

        # Creating object style
        buttonStyle = ttk.Style()

        # Setting style
        buttonStyle.configure("TButton", foreground="black", background="blue", width=5)

        return "TButton"

    # Function for setting the style of each frame
    def frameStyle(self):

        # Creating object style
        frameStyle = ttk.Style()

        # Setting style
        frameStyle.configure("TFrame", background=self.background)

        return "TFrame"

    # Function for setting the style of each frame
    def notebookStyle(self):

        # Creating object style
        notebookStyle = ttk.Style()

        # Setting style
        notebookStyle.configure("TNotebook", background=self.background)

        return "TNotebook"

    # Function for setting the style of each checkbutton
    def checkButtonStyle(self):

        # Creating object style
        checkButtonStyle = ttk.Style()

        # Setting style
        checkButtonStyle.configure(
            "TCheckbutton", foreground="black", background="white"
        )

        return "TCheckbutton"

    # Function for creating the appareance of Gui
    def appareance(self):

        # Setting tittle
        self.root.title(self.title)

        # Size of screen
        self.root.geometry(str(self.width) + "x" + str(self.height))

        # Changing background color
        self.root.configure(bg=self.background)

        # Creating a notebook
        self.notebook = ttk.Notebook(self.root, style=self.notebookStyle())
        self.notebook.pack(fill=BOTH, expand=True, pady=15)

        # Creating frame for Gui
        self.frameGui = ttk.Frame(self.notebook, style=self.frameStyle())
        self.frameGui.pack(fill=BOTH, expand=True)

        # Adding frame to tabs of notebook
        self.notebook.add(self.frameGui, text="Data")

    # Function to create a menu
    def menu(self):

        # Creating main menu
        mainMenu = Menu(self.root)

        # Setting main menu
        self.root.config(menu=mainMenu)

        plot = Menu(mainMenu, tearoff=FALSE)

        # Adding submenus to main menu
        mainMenu.add_cascade(label="Plot", menu=plot)

        # Adding command to submenus
        plot.add_command(label="Functions", command=self.secondMenu)

    # Function to create the second menu
    def secondMenu(self):

        # Creating a second window
        secondWindow = Toplevel(self.root, background=self.background)

        # Size of screen
        secondWindow.geometry("400x200")

        # Getting the coordinates of root window
        coordinateX = self.root.winfo_x()
        coordinateY = self.root.winfo_y()

        # Positioning the left upper toplevel window
        secondWindow.geometry("+%d+%d" % (coordinateX + self.width, coordinateY))

        # Creating first checkbutton
        self.firstVariable = IntVar()

        checkbuttonFirst = ttk.Checkbutton(
            secondWindow,
            text="Function",
            style=self.checkButtonStyle(),
            variable=self.firstVariable,
        )
        # Showing in screen
        checkbuttonFirst.grid(row=1, column=0, padx=20, sticky="EW")

        # Creating button to plot the selected function
        buttonPlotFunction = ttk.Button(
            secondWindow, text="Plot", style=self.buttonStyle(), command=self.plot
        )
        # Showing in screen
        buttonPlotFunction.grid(row=3, column=0, pady=10)

    # Function to plot the pharmacokinetics
    def plot(self):

        # Deleting each object
        for object in self.objects:

            del object

        # Creating frame for Pharmakinetics plot
        framePlot = ttk.Frame(self.notebook, style=self.frameStyle())
        framePlot.pack(fill=BOTH, expand=True)

        # Adding frame to tabs of notebook
        self.notebook.add(framePlot, text="Plot")

        # Creating an object from classPharmakinetics
        objPlot = Plot(
            framePlot,
            "Test plot",
            self.background,
            "x",
            "y",
            self.data,
        )

        self.objects = np.append(self.objects, objPlot)

        if self.firstVariable.get() == 1:
            objPlot.plot()

    # Function for calling each function from the class
    def gui(self):

        self.appareance()

        self.menu()

        # Creating infinite loop to show in screen
        self.root.mainloop()

Plot:
import matplotlib.pyplot as plt
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2Tk
import numpy as np
from lmfit import Model
from tkinter import *

class Plot:

    # Attributes of the class

    # Creating the canvas and the axis
    fig, ax = plt.subplots()

    # Constructor function
    def __init__(self, root, title, background, xLabel, yLabel, data):

        self.root = root  # Root
        self.title = title  # Title
        self.background = background  # Background color
        self.xLabel = xLabel  # Label of axis X
        self.yLabel = yLabel  # Label of axis Y
        self.data = data  # Dictionary to store the data

        # Data to evaluate the functions
        self.dataRange = np.linspace(
            self.data["x"][0],
            self.data["x"][len(self.data["x"]) - 1],
            100,
            endpoint=True,
        )

    # Double exponential function
    def doubleExponential(self, time, A, B, C):

        return A * (np.exp(-B * time) - np.exp(-C * time))

    # Function to plot the double exponential function
    def plot(self):

        # Adding the function to fit as the Model
        model = Model(self.doubleExponential)

        # Initializing the parameters
        params = model.make_params(A=0.5, B=0.005, C=0.5)

        # Getting the fitting data
        dataFitting = model.fit(self.data["y"], params, time=self.data["x"])

        # Plotting the fitted function using the obtained parameters
        self.ax.plot(
            self.dataRange,
            self.doubleExponential(
                self.dataRange,
                dataFitting.params["A"].value,
                dataFitting.params["B"].value,
                dataFitting.params["C"].value,
            ),
            "-",
            label="Fit",
        )

        # Inserting matplotlib charts into canvas
        matplotlib_gui = self.root

        # Creating the Tkinter canvas containing the Matplotlib figure
        canvas = FigureCanvasTkAgg(self.fig, master=matplotlib_gui)
        canvas.draw()

        # Placing the canvas on the Tkinter window
        canvas.get_tk_widget().pack()

        # Creating the Matplotlib toolbar
        toolbar = NavigationToolbar2Tk(canvas, matplotlib_gui)
        toolbar.update()

        # Placing the toolbar on the Tkinter window
        canvas.get_tk_widget().pack()

Main:
from stack1 import *

# Main features of a GUI
title = "Plot"
width = 500
height = 500
foreground = "black"
background = "white"

# Creating an object from classGUI
a = Gui(title, width, height, foreground, background)

a.gui()

A: The issue of importing the tool bar was produced due to inserting the frame instead of the root window, as the second argument of
NavigationToolbar2Tk(canvas, matplotlib_gui). Apparently, the second argument must be the root window.


text:
Q: How to make session variable last longer in CodeIgniter I am storing a session variable in codeigniter but it lasts only for some time.  How to increase the time of sesion variable or make not expire in CodeIgniter?

A: In your config config file, find this line $config['sess_expiration'] = 7200; and change it to whatever time you want.It is in seconds.


text:
Q: Complex Analysis and Bernoulli Numbers from $\frac{z}{2} \cot (\frac{z}{2})$
Define the Bernoulli numbers $B_n$ by $\frac{z}{2} \cot (z/2) = 1 - B_1 \frac{z^2}{2!} - B_2 \frac{z^4}{4!} - B_{3} \frac{z^6}{6!} - ...$ Explain why there are no odd terms in this series. What is the radius of convergence of the series? Find the first five Bernoulli numbers.

I understand why the power series expansion of $\frac{z}{2} \cot (\frac{z}{2})$ contains only terms with even powers (it has to do with the fact that the function is even, and so all the derivatives of odd order will vanish at $0$, so they odd order terms will vanish too). The only two things tricking are the radius of convergence and find the Bernoulli numbers.
First, let me discuss the radius of convergence. The form of the power series suggests that it's an expansion of $\frac{z}{2} \cot (\frac{z}{2})$ at $0$, but what's confusing me is that $\frac{z}{2} \cot (\frac{z}{2})$ is not defined at $0$. In fact, this leads to my confusion about the radius of convergence. From my understanding, the radius of convergence is the distance from the expansion point to the nearest pole, but $0$ is the nearest pole so shouldn't the radius of convergence be $0$?
As for calculating the Bernoulli numbers, my book discusses how to calculate the first few terms of the power series of $\frac{1}{g(z)}$ when $g(z)$ is analytic at $z=0$. I thought of using this calculation, but my problem is that $\frac{z}{2} \cot (\frac{z}{2})$ is not even defined at $z=0$. Also, in my book they calculate the power series of $\tan (z)$ (expanded at $z=0$ presumably). I thought of using the fact that $\cot (z) = \frac{1}{\tan (z)}$, but again the function is not defined at $z=0$. How am I to calculate the first five Bernoulli numbers?


text:
Q: Prevent recyclerview from stop scrolling on touch event I have a simple recyclerview with an adapter of strings displaying a list of numbers, i want to avoid the recyclerview to stop when it is scrolling and it's touched by the user.
I've already canceled to manually scroll the recyclerview on dragging by the user, but i need to manage the scrolling by myself programmatically (start and stop scroll)
I dont want to let the user interact with the recyclerview.
Here's a small video showing what happens when the user touches the recyclerview when its scrolling (it stops). I want to cancel that behaviour.
this is how i cancel scroll on dragging by the user
recyclerViewSlot.addOnItemTouchListener(new RecyclerView.OnItemTouchListener() {
        @Override
        public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent e) {
            // set return "true" = disables scrolling behaviour on dragging
            return true;
        }

        @Override
        public void onTouchEvent(RecyclerView rv, MotionEvent e) {
        }

        @Override
        public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {
        }
    });

by adding these lines of code, there is no change on the behaviour.
recyclerViewSlot.setEnabled(false);
recyclerViewSlot.setClickable(false);

A: You have to extend the RecyclerView class then manually prevent onTouch from being called like so:
public class YourRecyclerView extends RecyclerView {

    private boolean lock=false;
    public YourRecyclerView (Context context) {
        super(context);

    }

    public YourRecyclerView (Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public YourRecyclerView (Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);

    }

    @Override
    public boolean onTouchEvent(MotionEvent ev) {
        if(!lock){

        return super.onTouchEvent(ev);
        }
        else{
            return true;
        }

    }

    /**
     * @return the lock
     */
    public boolean isLock() {
        return lock;
    }

    /**
     * @param lock the lock to set
     */
    public void setLock(boolean lock) {
        this.lock = lock;
    }
}

A: Overriding onInterceptTouchEvent in a custom RecyclerView you can achieve that.
@Override
public boolean onInterceptTouchEvent(MotionEvent e) {
    return false;
}


text:
Q: Can anyone know how to setting cross web browser cookie I'm a php developer but not experience in training now and got a task that if someone open website from firefox then cookie must be saved in chrome, opera and other browsers too.

A: You are not able to set a cross browser cookies through PHP.
There are some tricks though, but it will use flash instead. See this link for more information.

A: While, you can't share directly cookies across browsers, you can use Flash to store the value in a SharedObject and read it. As this is handled by Flash player, it will work on all browsers.
This will work. It's done in Flex:
//Write the SharedObject
var mySharedObject:SharedObject=SharedObject.getLocal("mySharedObject", "/");
mySharedObject.data.role = role;
mySharedObject.flush();

//Read it when needed
var mySharedObject:SharedObject=SharedObject.getLocal("mySharedObject", "/");
role = mySharedObject.data.role;

If you need it as a cookie, you can also call javascript from Flex to read the SharedObject and write the value in a cookie:
//Write it as a cookie
        ExternalInterface.call("document.insertScript = function ()" +
        "{ " +
            "if (document.snw_setCookie==null)" +
            "{" +
                "snw_setCookie = function (name, value, minutes)" +
                "{" +
                    "if (minutes) {"+
                            "var date = new Date();"+
                            "date.setTime(date.getTime()+(minutes*60*1000));"+
                            "var expires = '; expires='+date.toGMTString();"+
                        "}" +
                        "else var expires = '';"+
                        "document.cookie = name+'='+value+expires+'; path=/; domain=.example.com;';" +
                    "}" +
            "}" +
        "}");

This way you can have the same cookie in all browsers. Let me know if you have trouble with this.


text:
Q: merge array in deep array nodejs I have the following structure:
const array = [
  [
    [
      [
        [
          {
            'name':'John'
          }
        ],
        {
          'name':'Mary'
        }
      ],
      {
        'name':'Cris'
      }
    ],
    {
      'name':'Deen'
    }
  ],
  {
    'name':'Bob'
  }
]

And I'd like to get the following structure as a result:
const expect = [
  {
    'name':'John'
  },
  {
    'name':'Mary'
  },
  {
    'name':'Cris'
  },
  {
    'name':'Deen'
  },
  {
    'name':'Bob'
  },
]

How do I make such conversion with lodash or another library?

A: You could use _.flattenDeep from lodash:

Recursively flattens array.

const array = [[[[[{ name: 'John' }], { name: 'Mary' }], { name: 'Cris' }], { name: 'Deen' }], { name: 'Bob' }];

console.log(_.flattenDeep(array));
.as-console-wrapper { max-height: 100% !important; top: 0; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.15.0/lodash.min.js"></script>

A: You can create recursive function using reduce() to return desired result.

const array = [[[[[{"name":"John"}],{"name":"Mary"}],{"name":"Cris"}],{"name":"Deen"}],{"name":"Bob"}]

function flatten(arr) {
  return arr.reduce(function(r, e) {
     return r = r.concat(Array.isArray(e) ? flatten(e) : e), r
  }, [])
}

console.log(flatten(array))

A: You can use this npm package npm underscore and this is a simple example:

var _ = require('underscore-node');
var extractedArray = _.flatten(deepArray)

A: function flattenArray(array, result) {
    result = result || [];
    for (var i = 0; i < array.length; i++) {
        if (Array.isArray(array[i])) {
            flattenArray(array[i], result);
        } else {
            result.push(array[i]);
        }
    }

    return result;
}

I wrote this some time back. Follows a recursive approach and is really fast as well.
JSPerf: https://jsperf.com/flatten-array-r1

A: By pure ES6 and a Haskellesque pattern matching implemented by destructuring, you may simply do as follows;

function flat([a,...b]){
  return (Array.isArray(a) ? flat(a) : [a]).concat(b.length ? flat(b) : []);
}

var arr = [[[[[{"name":"John"}],{"name":"Mary"}],{"name":"Cris"}],{"name":"Deen"}],{"name":"Bob"}],
    res = flat(arr);
console.log(res);

A: You can do it with closures and a single line of code with ES6. Libraries, when not necessary are a burden. Avoid them where you can.

const flatten = arr => arr.reduce((r, e) => (r = r.concat(Array.isArray(e) ? flatten(e) : e), r), []);

const array = [
  [
    [
      [
        [{
          'name': 'John'
        }],
        {
          'name': 'Mary'
        }
      ],
      {
        'name': 'Cris'
      }
    ],
    {
      'name': 'Deen'
    }
  ],
  {
    'name': 'Bob'
  }
];
console.log(flatten(array))

A: Optimal way without any library and using good-old JS logic:

var arr = [
  [
    [
      [
        [
          {
            'name':'John'
          }
        ],
        {
          'name':'Mary'
        }
      ],
      {
        'name':'Cris'
      }
    ],
    {
      'name':'Deen'
    }
  ],
  {
    'name':'Bob'
  }
];

// convert to string and remove all Array "[" and "]" symbols
var str = JSON.stringify(arr).replace(/\[|]/g,'');
// convert the String back to an Object (Array)
var flatArr = JSON.parse("[" + str + "]");

console.log(flatArr)

A: Consider using object-scan. It's powerful for doing in memory data structure processing (once you wrap your head around it).
Here is how you could solve your example

// const objectScan = require('object-scan');

const find = (input) => objectScan(['**'], {
  reverse: false,
  rtn: 'value',
  filterFn: ({ value }) => typeof value.name === 'string'
})(input);

const array = [[[[[{ name: 'John' }], { name: 'Mary' }], { name: 'Cris' }], { name: 'Deen' }], { name: 'Bob' }];

console.log(find(array));
// => [ { name: 'John' }, { name: 'Mary' }, { name: 'Cris' }, { name: 'Deen' }, { name: 'Bob' } ]
.as-console-wrapper {max-height: 100% !important; top: 0}
<script src="https://bundle.run/object-scan@13.8.0"></script>

Disclaimer: I'm the author of object-scan


text:
Q: Adding the same cell from multiple worksheets with python I have a Python program with works great so far, However...... I need to sum all of the same cell position across 52 different worksheets now.
For example:   I have 52 sheets and need to sum cell D75 across all the sheets in my coversheet.

Mind you the coversheet is already made and I have no issues with that, i just need to determine how to incorporate the sum into  my coversheet.
CHEERS!!!

A: completely untested, let me know if you can't get this to work and I'll take a closer look
wb = open_workbook('simple.xls')
values = []
for s in wb.sheets(): #iterate over the sheets
    cell = sheet.cell(3,74) #D=3, need to offset 75 by 1 hence 74
    values.append(float(cell.value))
print sum(values)

also, this is a pretty good tutorial http://www.simplistix.co.uk/presentations/python-excel.pdf


text:
Q: How to count a record multiple times based on years of subscription I am trying to create a report that counts the number of subscriptions per year along with the avg revenue. The problem is when a customer orders a multi-year subscription they are wanting to count that customer for each year that they are active. So if the subscription starts in 2020 and expires in 2023 I need to count for 2020, 2021, 2022 and 2023. The report needs to display by pub, count of customers, year, sales and avg sales. I am unsure how to get it to count the record multiple times and actually display the date for the proper year. For example if they started in 2020 and expire in 2023. I want the first count for the customer to show 2020 and the second count to show 2021 and so on.
select  top 6 count(distinct CTM_NBR) as 'Count',
dtl.PUB_CDE AS 'Pub',

SUM(tot_liab) as 'Sales',
YEAR(strt_DTE) as 'Start Year',
year(exp_dte) as 'exp_year',

case term
when '6' then '1 year'
when '12' then '2 years'
when '18' then '3 years'
when '24' then '4 years'
when '30' then '5 years'
when '36' then '6 years'
when '42' then '7 years'
when '48' then '8 years'
when '54' then '9 years'
when '60' then '10 years' else ' ' end as 'Years Subscribed'
from CIRSUB_M  dtl
where YEAR(STRT_DTE) >= '2013'

and dtl.PUB_CDE in ('MEN')--('FCM','GEM','GRT','MEN','FER','HGR','MCC')
and CRC_STS in ('r','w','p') and TERM > 6 and year(CTG_DTE) > '2012'
and CTM_NBR not in (select ord.CTM_NBR from PROOLN_M oln
                    inner join PROORD_M ord on ord.ORD_NUM = oln.ORD_NUM
                    and YEAR(ord.CTG_DTE) = YEAR(dtl.CTG_DTE)
                    and SUBSTRING(oln.PMO_CDE,2,2) = 'ME'
                    and oln.ITM_NUM <> 'DIGITAL SUB')
group by YEAR(strt_DTE),dtl.CTG_DTE,EXP_DTE, TERM, dtl.PUB_CDE

Sample Data


text:
Q: How to duplicate table row based on column value in Teradata? Can someone help this task? If I have one table as below in Teradata:

caseid
content
repeat

id1
row1
2

id2
row2
3

I want to build a new table based on the repeat value as below. How should I do?

caseid
content
repeat
groupid

id1
row1
2
1

id1
row1
2
2

id2
row2
3
1

id2
row2
3
2

id2
row2
3
3

Thanks!

A: Teradata proprietary EXPAND ON syntax creates time series and can be used for this task:
SELECT t.*
   -- convert period back to int
  ,End(pd) - Current_Date AS groupid
FROM mytable AS t
-- works on date/time only -> convert int to period
EXPAND ON PERIOD(Current_Date, Current_Date + repeat) AS pd

A: you can do it using recursive cte :

with recursive cte as (
select * , 1 groupid from cases
union all
select caseid ,content, repeat, groupid + 1 groupid
from cte
where groupid  < repeat
)

select  * from cte
order by caseid

caseid | content | repeat | groupid
-----: | :------ | -----: | ------:
     1 | row1    |      2 |       1
     1 | row1    |      2 |       2
     2 | row2    |      3 |       1
     2 | row2    |      3 |       2
     2 | row2    |      3 |       3

db<>fiddle here


text:
Q: CASE Statement with multiple outcomes - some outcomes overlooked I have a case statement such as the one below that has multiple outcomes. Unfortunately, due to the first three outcomes being satisfied, the other options are being ignored. Is there some way of the statement considering all outcomes?
 ,CASE WHEN T.T1_HoNOSCA_Score IS NULL THEN 'Missing T1'
    WHEN T.T2_HoNOSCA_Score IS NULL THEN 'Missing T2'
    WHEN T.T1HonosValidity IN ('NULL','Invalid 9','Invalid Null')
    OR T.T2_HonosValidity IN ('NULL','Invalid 9','Invalid Null') THEN 'Invalid Data'
    WHEN T.T1_HoNOSCA_Score IS NULL AND T.T2_HoNOSCA_Score IS NULL THEN 'Missing T1 & T2'
    WHEN T.T1_HoNOSCA_Score IS NULL AND T.T1HonosValidity IN ('NULL','Invalid 9','Invalid    `enter code here`Null')
    OR T.T2_HonosValidity IN ('NULL','Invalid 9','Invalid Null') THEN 'Missing T1 & Invalid Data'
    WHEN T.T2_HoNOSCA_Score IS NULL AND T.T1HonosValidity IN ('NULL','Invalid 9','Invalid Null')
    OR T.T2_HonosValidity IN ('NULL','Invalid 9','Invalid Null') THEN 'Missing T2 & Invalid Data'
    WHEN T.T1_HoNOSCA_Score IS NULL AND T.T2_HoNOSCA_Score IS NULL AND T.T1HonosValidity IN ('NULL','Invalid 9','Invalid Null')
    OR T.T2_HonosValidity IN ('NULL','Invalid 9','Invalid Null') THEN 'Missing T1 & T2 & Invalid Data'
    ELSE NULL END AS Data_Quality_Type

A: Your CASE statement contains boolean expressions that are not mutually exclusive. Some of these expressions are stronger than others.
A condition X is said to be stronger than a condition Y if X implies Y. In other words, Y is true every time the X is true.
For example, consider two conditions:
T.T2_HoNOSCA_Score IS NULL                                -- Condition 1

and
T.T1_HoNOSCA_Score IS NULL AND T.T2_HoNOSCA_Score IS NULL -- Condition 2

Every time condition 2 is satisfied, condition 1 will be satisfied as well, because condition 1 is AND-ed with some additional criteria to form condition 2. Therefore, condition 2 is stronger than condition 1.
When you have a case statement with non-mutually exclusive conditions like yours, you need to order them from strongest to weakest. Otherwise, your weaker conditions would "shadow" the stronger ones, never letting them to execute.

A: you can dissect the case expresssion into a set of 3 individual tests, joining the result as needed.
the example is provided in oracle syntax. however, your dbms will provide similar string formatting functions, otherwise choose the functionally equivalent but less readable version in pure sql.
, RTRIM (
     RTRIM (
         SUBSTR(
                CASE WHEN T.T1_HoNOSCA_Score IS NULL THEN ' Missing T1 &'   ELSE '' END
             || CASE WHEN T.T2_HoNOSCA_Score IS NULL THEN ' Missing T2 &'   ELSE '' END
             || CASE WHEN    T.T1_HonosValidity IN ('NULL','Invalid 9','Invalid Null')
                          OR T.T2_HonosValidity IN ('NULL','Invalid 9','Invalid Null')
                                                     THEN ' Invalid Data &' ELSE '' END
           , 2
         )
       , '&'
     )
  )

sql:
 SUBSTR(
        CASE WHEN T.T1_HoNOSCA_Score IS NULL THEN ' Missing T1 &'   ELSE '' END
     || CASE WHEN T.T2_HoNOSCA_Score IS NULL THEN ' Missing T2 &'   ELSE '' END
     || CASE WHEN    T.T1_HonosValidity IN ('NULL','Invalid 9','Invalid Null')
                  OR T.T2_HonosValidity IN ('NULL','Invalid 9','Invalid Null')
                                             THEN ' Invalid Data &' ELSE '' END
   , 2
   , LENGTH (
            CASE WHEN T.T1_HoNOSCA_Score IS NULL THEN ' Missing T1 &'   ELSE '' END
         || CASE WHEN T.T2_HoNOSCA_Score IS NULL THEN ' Missing T2 &'   ELSE '' END
         || CASE WHEN    T.T1_HonosValidity IN ('NULL','Invalid 9','Invalid Null')
                      OR T.T2_HonosValidity IN ('NULL','Invalid 9','Invalid Null')
                                                 THEN ' Invalid Data &' ELSE '' END
     ) - 3
 )


text:
Q: Reg: izPack dynamic variables How to assign dynamic variable value from file in izPack.
Can you please post some code snippet?
I tried it with the following syntax:
    <variable name="EXIST_IP_ADDRESS" file="${INSTALL_PATH}/test.properties"
type="options" key="IpAddress"/>

But am getting error says that value attribute is mandatory. If I assign value with some string then this cannot be loaded from file. Please check what mistakes am doing.

A: Dynamic variables have their own section, I guess you are trying to use it in "variables" section.
<dynamicvariables>
  <variable name="previous.JAVA_HOME" escape="false" file="${INSTALL_PATH}/run.cmd" type="options" key="SET JRE" ignorefailure="true">
</dynamicvariables>


text:
Q: getting the output of a grep command in a loop I have a shell script that includes this search:
find . -type f -exec grep -iPho "barh(li|mar|ag)" {}  \;

I want to capture each string the grep command finds and send it a function I will create named "parser"
parser(){
# do stuff with each single grep result found
}

how can that be done?
is this right?
find . -type f -exec grep -iPho "barh(li|mar|ag)" {parser $1}  \;

I do not want to output the entire find command result to the function

A: Only shell can execute a function. You need to use bash -c in your find in order to execute it. That is also the reason you need to export your function, so that the new process sees it.
parser() {
    while IFS= read -r line; do
        echo "Processing line: $line"
    done <<< "$1"
}

export -f parser
find . -type f -exec bash -c 'parser "$(grep -iPho "barh(li|mar|ag)" "$1")"' -- {} \;

The code above will send all occurrences from file1, then file2 etc to your function to process. It will not send each line one by one and therefore you need to loop over the lines in your function. If there is no occurrence of your regex in a file, it will still call your function with an empty input!
That might not be the best solution for you so let's try to add the loop inside the bash -c statement and really process the lines one by one:
parser() {
    echo "Processing line: $1"
}

export -f parser
find . -type f -exec bash -c 'grep -iPho "barh(li|mar|ag)" "$@" | while IFS= read -r line; do parser "$line"; done' -- {} +

EDIT: Very nice and simple solution not using bash -c suggested by @gniourf_gniourf:
parser() {
   echo "Processing line: $1"
}

find . -type f -exec grep -iPho "barh(li|mar|ag)" {} + | while IFS= read -r line; do parser "$line"; done

This approach works fine and it will process each line one by one. You also do not need to export your function with this approach. But you have to care for some things that might surprise you.
Each command in a pipeline is executed in its own subshell, and any variable assignment in your parser function or your while in general will be lost after returning from that very subshell. If you are writing a script, simple shopt -s lastpipe will suffice and run the last pipe command in the current shell environment. Or you can use process substitution:
parser() {
   echo "Processing line: $1"
}

while IFS= read -r line; do
   parser "$line";
done < <(find . -type f -exec grep -iPho "barh(li|mar|ag)" {} +)

Note that in the previous bash -c examples, you will experience the same behavior and your variable assignments will be lost as well.

A: You need to export your function.
You also need to call bash to execute the function.
parser() {
  echo "GOT: $1"
}
export -f parser

find Projects/ -type f -name '*rb' -exec bash -c 'parser "$0"' {} \;

A: i suggest you to use sed ,this is more powerful tool to do text processing.
for example i want to add string "myparse" after the line that end as "ha",i can do this like
# echo "haha" > text1
# echo "hehe" > text2
# echo "heha" > text3
# find . -type f -exec sed '/ha$/s/ha$/ha myparse/' {} \;
haha myparse
heha myparse
hehe

if you really want to replace the file ,not just print to stdout,you can do this like
# find . -type f -exec sed -i '/ha$/s/ha$/ha myparse/' {} \;


text:
Q: how to run pod spec file I am trying to implement the firebase dynamic link plugin in Flutter
I had I achieved in native iOS and android
now is the time to implement Flutter
I created plugin using the template
flutter create --org com.sample --template=plugin firebasedynamiclink

I had added firebase core, and firebase dynamic link dependency in pod spec in the iOS section
created the firebase app in one of the projects and got googleserviceInfo.plist file added example-> runner-> directory
Now my question is how to run a pod spec file to integrate core and dynamic link pages to iOS class files
generally, I used to run pod install but here no pod file is there.
It shows output if I add #import "Firebase/Firebase.h"
in dynamiclinkplugin.m
  Xcode's output:
↳
=== BUILD TARGET app_referrals OF PROJECT Pods WITH CONFIGURATION Debug ===
/Users/Siva/IdeaProjects/app_referrals/ios/Classes/AppReferralsPlugin.m:2:9: fatal error: 'Firebase/Firebase.h' file not found
#import "Firebase/Firebase.h"
        ^~~~~~~~~~~~~~~~~~~~~
1 error generated.

my pod spec looks like this
 #
 # To learn more about a Podspec see      http://guides.cocoapods.org/syntax/podspec.html
 #
Pod::Spec.new do |s|
   s.name             = 'app_referrals'
    s.version          = '0.0.1'
   s.summary          = 'A new flutter plugin project to refer your application using native dynamic links .'
   s.description      = <<-DESC
 A new flutter plugin project.
                   DESC
   s.homepage         = 'http://example.com'
   s.license          = { :file => '../LICENSE' }
   s.author           = { 'xyzzy Technologies' => 'siva@xyz.com'      }
   s.source           = { :path => '.' }
   s.source_files = 'Classes/**/*'
  s.public_header_files = 'Classes/**/*.h'
  s.dependency 'Flutter'
  s.dependency 'Firebase/Core'
  s.dependency 'Firebase/DynamicLinks'
  s.ios.deployment_target = '8.0'
  end

Thanks in advance.


text:
Q: What's the difference between BAREWORD and *BAREWORD in Perl? my $childpid = open3(HIS_IN, HIS_OUT, HIS_ERR, $cmd, @args);

my $childpid = open3(*HIS_IN, *HIS_OUT, *HIS_ERR, $cmd, @args);

It seems the above both works for my application.
What's the difference between BAREWORD and *BAREWORD in Perl?

A: The meaning of a bareword varies. Most of the time, a bareword is a function call.
sub foo { say "Hello"; }
foo;

Sometimes, it's a string literal.
$x{foo}    # $x{"foo"}

In yet other circumstances, it produces a typeglob.
print STDOUT "foo";   # print { *STDOUT } "foo";

In this case,
open3(HIS_IN, HIS_OUT, HIS_ERR, ...)

is equivalent to
open3("HIS_IN", "HIS_OUT", "HIS_ERR", ...)

but open3 uses that string as the name of a glob in the caller's package, so the above is functionally equivalent to
open3(*HIS_IN, *IS_OUT, *HIS_ERR, ...)


text:
Q: TSQL Procedure returning multiple rows of data I'm busy trying to rewrite some PostgreSQL stored procedures/functions for SQL Server 2014s TSQL.
I am struggling to return my values from this stored procedure though, this one is just a test but I am trying to return multiple rows of data in this case the for the two variables si_code and co_desc.
I have my procedure as follows (as a test)
if (object_id('p_get_serial')) is not null
   drop procedure p_get_serial
go

create procedure p_get_serial(@par01 char(20), @par02 integer)
as

   declare
      @co_num integer,
      @co_desc char(20),
       @si_code char(20),
       @log char(40)

   declare mycur cursor for
      select co_num, co_desc
       from colours
       where co_num <= @par02

   open mycur
   fetch next from mycur into @co_num,
                              @co_desc

   while @@FETCH_STATUS = 0
   begin

      set @si_code = ''

    select @si_code = si_code
       from sitems
       where si_co_num = @co_num

       set @log = @co_desc + ' ' + @si_code
       raiserror(@log,0,1) with nowait

      fetch next from mycur into @co_num, @co_desc

   end
   close mycur deallocate mycur

go

exec p_get_serial @par01 = 'paramater01', @par02 = 10

what is the best way to return my results knowing that there will be several rows?

A: In T-SQL you do not need to declare a cursor. Just select what you need and it will be available to the client app.
Cursor is Oracle/DB2/PostgreSQL etc way of returning data. SQL Server does not need it.
create procedure p
as
    select 1 as a

returns a recordset containing one record with one column.
create procedure p
as
    select 1 as a, 'a' as b
    union select 2, 'b'

returns two rows each with two columns.
Example of a more complex processing before returning a result set:
create procedure p
as
begin
    declare @a int, @b varchar(10)

    select @a = 1
    select @b = convert(varchar(10), @a)

    select @a = @a + 1

    select @a as a, @b as b -- this will be the resultset returned to the client
end

A: All you need to do is, just save the data for each row in a temp table or table variable and just write a SELECT statement at the the end of the Stored Procedure.
Your question is not clear what you need exactly, you have a cursor and while loop, they seem to be redundant


text:
Q: Display template not accepting list from another property on the model? I have a model that looks like this:
 public class WorksheetViewModel() {
     public Worksheet Worksheet {get; set;}
     // ... more properties
 }

 public class Worksheet() {
     public List<LineItem> LineItems {get; set;}
     public Loan Loan {get; set; }
     // ... more properties
 }

 public class LineItem() {
     // ... some properties
 }

 public class Loan() {
     public List<LoanField> Fields {get; set;}
     // ... more properties
 }

 public class LoanField() {
     // ... some properties
 }

In my view I have the following:
 @Html.DisplayFor(m => m.Worksheet.LineItems)   // this works great
 @Html.DisplayFor(m => m.Worksheet.Loan.Fields) // this throws exception

I'm getting an exception that looks like this:
 The model item passed into the dictionary is of type
 'System.Collections.Generic.List`1[DataContracts.LoanField]',
 but this dictionary requires a model item of type
 'DataContracts.LoanField'.

The display templates for both collections are similar in that both reference on the model they are are showing:
Working template:
 @model DataContracts.LineItem
 @Html.Label(Model.ItemType.Description) : @Model.RecipientEmployee.FullName

Not working template:
 @model DataContracts.LoanField
 @Html.Label(Model.FieldName) : @Model.FieldValue

Since the first template correctly accepts a List of LineItem objects then it would seem that the second template would behave the same way, but clearly its not in this case.
Anyone have an idea why the template is complaining about the list and a way to get around it?

A: After trying many whacky tricks unlikely to work I decided to try changing the name of the template... and it worked.
The problem was an initial misunderstanding in the convention being followed. When I first created a display template I named it after the property name is was being displayed for... in this case "Fields".
Silly me... I assumed that MVC would be smart enough to use the @model to resolve the type. I thought this assumption was confirmed when I saw that you can pass in a template name as one of the parameters in Html.DisplayFor().
However, as most of you can probably guess by now, the template must be named the same as the datatype its displaying (the very same type which is clearly spelled out in the @model statement).  Once I changed the name of the template everything worked fine.


text:
Q: Relative directory not working on subdomain - adding subdomain to src I've got a blog I installed to my /blog directory and have the htaccess written so that it only displays if you go to http://blog.domain.com
So my hierarchy looks like this
/blog
/system
    /js
    /css
    <php pages>

I have a header file that is included that has all the links to my style sheets and javascript files. On http://domain.com when they are included it will look like this instead and I can't figure out why.
 <link href="../system/css/bootstrap.css" rel="stylesheet">

Which works great but when I try to call this from my /blog directory it shows up like this
  <link href="http://blog.domain.com/system/css/bootstrap.css" rel="stylesheet">

Which obviously doesn't exist.  The code is the same, it should be a relative path to the css directory. What am I missing here?


text:
Q: Tech Design to achieve a workflow usability using UINavigationController New to iOS development with a simple technical design question. The project I'm working has walks a user through a set of questions, upwards of 20. I want to use the UINavigationController to give a workflow feel in terms of usability with the back button and Next button in the navigation bar - that is a requirement. However, the design of each of the 20 views will be identical, except of course for the content which will be data driven.
From a design standpoint, would I...

*

*Replicate the View Controller 20 times with 20 separate h and m classes, and use push segue's between each to give a workflow feel.

*Replicate the View Controller 20 times but connect to same h and m class.

*Redraw the View each time the user clicks Back or Next, thus keeping 1 viewcontroller

I've looked at several samples with xib files, but I'm looking to pull this off with the latest version of xcode and storyboards.

A: The simplest approach will be to reuse what has already been created. The View (From Modal-View-Controller) part of your application needs to be implemented only once.
All you need is a simple action to allow user to navigate between provide options (20 in this case).
The preferred option in this case will be
3)Redraw the View each time the user clicks Back or Next, thus keeping 1 viewcontroller
All you need is to update the content (equivalent to redraw the view)using proper selectors such as
- (IBAction)navigateToNextOption:(int)index;
- (IBAction)navigateToPreviousOption:(int)index;

You might also like to handle validation based on indices and prompt user to select proper navigation buttons.
A simple case say what if the options are 1000 , might also help you decide the best approach.
Cheers!!

A: I would suggest that use a single viewcontroller and show the animation behavior like UINavigationController on next and back button click. use this source code a Git
kASlidshow git repositry
how it looks
replace the arrow buttons and place it a top of the UIViewController.


text:
Q: How to Enable/Disable session based on url using nodejs? I use express and express-session middleware to build a website, with session enabled. But some url such as /health-check' and/version-checkdo not need session, especially the/health-check`, which will generate a lot of useless session in db(the project use mongodb).I believe there is a good solution to solve the problem.
The following is a snippets of the session:
var session = require('express-session'),
    passport = require('passport');

var app = express();
//other middleware.

// Express MongoDB session storage
app.use(session({
    saveUninitialized: true,
    resave: true,
    secret: config.sessionSecret,
    cookie: { maxAge: 2628000000 },
    store: new mongoStore({
        db: db.connection.db,
        collection: config.sessionCollection
    })
}));

// use passport session
app.use(passport.initialize());
app.use(passport.session());
//...

A: I suggest to create own middleware function and put there your session middleware as function, but with conditions e.g:
app.use(function(req, res, next){
  if(...some condition...){//for example check url
    //do something or nothing
    next();//very important or request will freeze
  } else {//otherwise run session
    session({your options})(req, res, next);
  }
});

instead your app.use(session())
in one custom middleware you can put any other middleware to add conditions. But when you want to wrap more then one middleware to single custom middleware be careful on 'next'. It can be use only once in middleware (multiple middlewares use use it multiple time). Then you have to create your own callback 'next'.


text:
Q: Issue after device rotation with series of CheckBoxes I have a LinearLayout in which I inflate several CheckBoxes from an xml file. They work as expected; however when the screen rotates (and thus the Activity is destroyed/recreated) a weird bug is happening. Say there are 6 checkboxes, and they have text 'one', 'two' etc through 'six'. After rotation, all six of them will read 'six'. This persists no matter what I attempt, until I run a custom function which either adds or deletes one of the checkboxes, at which point the remaining ones show their proper text again, and in the proper order.
Here's the XML for the checkbox:
<?xml version="1.0" encoding="utf-8"?>
<CheckBox xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/groupcreate_entry"
    android:layout_marginTop="5dp"
    android:layout_marginBottom="5dp"
    android:button="@null"
    android:drawableRight="?android:attr/listChoiceIndicatorMultiple"
      //The above two lines allow the checkbox to be to the right of the text.
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:gravity="right" />

And the code in question:
protected void onCreate(Bundle savedInstanceState) {
    private ArrayList<String> groupNames = new ArrayList<String>(10);
    super.onCreate(savedInstanceState);
    setContentView(R.layout.groupcreate);

    LinearLayout groupCreate = (LinearLayout) findViewById(R.id.groupCreate);
    setupGroupViews();
}

private void setupGroupViews() {
    groupCreate.removeAllViews();
    CheckBox[] textBox = new CheckBox[groupNames.size()];
        //I originally reused the same CheckBox each time, but switched to an
        //array to try debugging this issue; no luck

    for (int i = 0; i < groupNames.size(); i++) {
        textBox[i] = (CheckBox) (getLayoutInflater().inflate(R.layout.groupcreate_entry, groupCreate, false));
        textBox[i].setText(groupNames.get(i));
        registerForContextMenu(textBox[i]);
        groupCreate.addView(textBox[i]);
    }
}

In the function where I add or delete a checkbox, I don't do much more than add/remove it from the ArrayList groupNames and rerun setupGroupViews.
I've tried running groupCreate.invalidate() in onCreate() to no effect. I'm guessing it has something to do with the activity being redrawn, but I've tried a bunch of things and can't figure out what it is. Is it because I'm inflating each CheckBox using the same layout file? Is that why it redraws them all with the same text of the last created CheckBox?
Getting toward my wit's end; any and all input appreciated. Happy to clarify if anything needs it.
Edit: Another function I created allows you to edit the text of the checkbox through a right-click context menu which brings up a dialog. If you go to edit the text of, say, the first checkbox, which should have text of 'one' in this example but instead reads 'six', the dialog pulls the checkbox's text via getText().toString() and it does indeed show the incorrect text of 'six'. However, no matter what modifications you make to the text in the dialog, once you hit Ok and submit the change, all the checkboxes go back to their correct text, and it will read 'one' again.
I'm wondering if it's in some way holding on to references to deleted CheckBox views, but if so I don't know why as I call groupCreate.removeAllViews() before proceeding.

A: I believe the problem you are experiencing is due to the fact that all your CheckBox instances are using the same id groupcreate_entry.
Android restores View data based on object id, so when it was saving, it was pulling the item id and saving its respective value. When restoring, it was looking at each element, and giving it the value saved for that id (which was "six", the last value saved for groupcreate_entry).
Solution: try giving the objects their own unique ids, and then it should fix it. The other option, of course, is to simply override the default behaviour.


text:
Q: Visual Studio Debugging an old version of code- for instantiated classes only I am debugging a solution in visual studio, and the debugger is not building up to date code for each class. The solution consists of 3 projects:

*

*Project 1) A windows service- set up for debugging as a console app

*Project 2) An actual console app (which basically functions as a class library and needs to be changed to one at some point)

*Project 3) A unit test project.

Project 1, the windows service, uses quartz scheduler and instantiates classes from project 2, the console app, in some of it's jobs. I am certain the the updated code in project 2 is not being hit because the main job of the scheduler is to send emails, which it still does successfully, and in the code that must be called before any emails are sent I have put:
 throw new exception("hello");

Visual studio will also not hit any break points I put in the instantiated classes of project 2 when debugging from project 1. Bizarrely however, in a static class full of constants in project 2 if I put:
public static readonly string test = textFxn();

private static string testFxn()
{
   throw new exception("hello");
}

The debugger will throw the exception, and hit any break points I put in the class.
What have I tried:

*

*Build solution

*Clean + Rebuild solution

*Delete all bin and obj folders from the solution, then clean + rebuild

*Delete all bin and obj folders from the solution, restart computer, then clean + rebuild

*Delete all bin and obj folders from the solution, delete recycle bin + temp files, then clean + rebuild

*check settings based on similar posts about VS not building up to date code, everything seems to be set to build the new code

*Updating to latest .NET target version

Other details:

*

*I am debugging under project 1

*Visual studio version is 2017, Windows

*break points / code changes are picked up for project 1, the windows service

*Console.WriteLine() does not appear to be working within project 2, even in places where the code was not updated, I am fairly certain it did before

*I had been working on this solution for months with the same setup and never encountered this issue

*I wrote unit tests for the new code in project 2 which tested the updated code when project 3 was run

*There is a local git folder for the project, but obviously I don't really want to try deleting that

Where on earth (or more specifically, on my computer) is visual studio picking up these old class builds from? I am unable to find anything about anyone having an issue like this so suggestions are appreciated.

A: I ended up being able to resolve the issue by downgrading my version of Quartz from 3.0.7 to an any arbitrary 2.x version. The behavior was totally bizarre and still unsure of what exactly what Quartz was doing to cause this.


text:
Q: How to launch some links in particular browser using slickrun How to specify the command parameter in slick run to launch a specific link in chrome or IE or firefox.

A: Instead of including the website link in the "Filename" field, type the link in "parameters" field. In the "filename" field give the browser details such as "chrome" for google chrome, "iexplore" for IE.

A: The 'Filename' field should contain the application that you wish to run (e.g.  firefox, chrome, iexplore).  You can then specify the URL that you want to open in the 'Parameters' field.

If you wish to open more than one URL then please see the following page for details:  http://boontlee.blogspot.co.uk/2009/01/slickrun-opening-multiple-sites-with.html


text:
Q: Can I express some power of $\cos(\frac {2\pi}{5})$ as a rational number without using complex numbers? I have been trying to express a power of $\cos(\frac {2\pi}{5})$ as a
"rational number", or trying to find a
"rational number" that results from a linear combination of powers of $\cos(\frac {2\pi}{5})$. Meaning $\frac {p}{q} = [\cos (\frac {2\pi}{5})]^n$ or $\frac {p}{q} = a_1[\cos (\frac {2\pi}{5})]^n + \cdots + a_n[\cos (\frac {2\pi}{5})]^m $.
I have seen in other posts (example:  Find exact value of $\cos (\frac{2\pi}{5})$ using complex numbers. ) that this is possible by using the fifth roots of unity. So I would suppose that it is not possible without the aid of complex numbers? If that is or isn't the case, I do not have an idea about how to argument this.

A: By well-known trigonometric formulas and a few transformations
$$\cos(5t)=\cos(4t)\cos(t)-\sin(4t)\sin(t)\\
=(2\cos^2(2t)-1)\cos(t)-2\sin(2t)\cos(2t)\sin(t)\\
=(2(2\cos^2(t)-1)^2-1)\cos(t)-4\sin(t)\cos(t)(2\cos^2(t)-1)\sin(t)\\
=16\cos^5(t)- 20\cos^3(t)+ 5\cos(t)$$
Then,
$$\cos\left(5\frac{2\pi}5\right)=16\cos^5\left(\frac{2\pi}5\right)-20\cos^3\left(\frac{2\pi}5\right)+\cos\left(\frac{2\pi}5\right)=1$$  is a rational expression.

We can solve further
$$\cos(5t)=1,$$ or
$$16x^5-20x^3+5x-1=0.$$
We have the obvious root $x=1$ and by synthetic division
$$16x^5-20x^3+5x-1=(x-1)(16x^4+16x^3-4x^2-4x+1).$$
As the four other solutions of the trigonometric equation go in pairs, the second factor must be a perfect square.
The leading term of the squared polynomial is obviously $4x^2$, and by
$$(4x^2+ax+b)^2=16x^4+8ax^3+(a^2+8b)x^2+2abx+b^2$$ we get $a=2,b=-1$ and the factor is
$$(4x^2+2x-1)^2.$$
Your rational number can be
$$4\cos^2\left(\frac{2\pi}5\right)+2\cos\left(\frac{2\pi}5\right)=1.$$
Finally, the roots of the polynomial are
$$\frac{-1\pm\sqrt{5}}4$$ and we choose the positive value.


text:
Q: Pandas dataframe to json list format I have large pandas tabular dataframe to convert into JSON.
The standard .to_json() functions does not make a compact format for JSON.
How to get JSON output forma like this,  using pandas only ?
{"index": [ 0, 1 ,3 ],
 "col1": [ "250", "1" ,"3" ],
 "col2": [ "250", "1" ,"3" ]
}

This is a much compact format form of JSON for tabular data.
(I can do a loop over the rows.... but)

A: It seems you need to_dict first and then dict to json:
df = pd.DataFrame({"index": [ 0, 1 ,3 ],
 "col1": [ "250", "1" ,"3" ],
 "col2": [ "250", "1" ,"3" ]
})
print (df)
  col1 col2  index
0  250  250      0
1    1    1      1
2    3    3      3

print (df.to_dict(orient='list'))
{'col1': ['250', '1', '3'], 'col2': ['250', '1', '3'], 'index': [0, 1, 3]}

import json

print (json.dumps(df.to_dict(orient='list')))
{"col1": ["250", "1", "3"], "col2": ["250", "1", "3"], "index": [0, 1, 3]}

Because it is not implemented yet:
print (df.to_json(orient='list'))

ValueError: Invalid value 'list' for option 'orient'

EDIT:
If index is not column, add reset_index:
df = pd.DataFrame({"col1": [250, 1, 3],
                   "col2": [250, 1, 3]})
print (df)
   col1  col2
0   250   250
1     1     1
2     3     3

print (df.reset_index().to_dict(orient='list'))
{'col1': [250, 1, 3], 'index': [0, 1, 2], 'col2': [250, 1, 3]}

A: You can use to_dict and json (and add the index as extra column if required via assign):
import json

df = pd.DataFrame({"col1": [250, 1, 3],
                   "col2": [250, 1, 3]})

json_dict = df.assign(index=df.index).to_dict(orient="list")
print(json.dumps(json_dict))

>>> '{"index": [0, 1, 2], "col1": [250, 1, 3], "col2": [250, 1, 3]}'


text:
Q: Office365 has a different track pad scroll direction with X-Mouse-Button-Control In my company, I got a new notebook with Microsoft Windows 10. It comes with natural scrolling support on the touchpad: Sliding up with two fingers moves the document up. So far, so nice.
Sadly, if I connect a mouse, there is no such option for the mouse wheel: Moving the mouse wheel up, moves the document down. This is rather confusing when switching between touchpad and mouse. Fortunally, I found the tool X-Mouse-Button-Control which can address this behaviour without admin priviliges.
Now all applications have natural scrolling with mouse button, almost all have natual scrolling with touchpad, but for some strange reason, the touchpad scrolling direction for Microsoft Office365 is changed by the mouse scrollwheel setting of X-Mouse-Button-Control. All other applications I tried are not influenced (as supposed!).
Seems like Microsoft themselves did not follow their own Windows programming guidelines, while everybody else did?! How can I switch off this nonsense behaviour?

A: My Windows 10 is offering me an option to change the direction for touchpads easily, but not for Mice.
I have reversed the scroll direction of these before with the Registry (Walkthrough)
Based on the screenshots from the XMBC site (which seems like it is here), XMBC can have many different application profiles, have you double-checked to see if there is a profile for any of the MS Office apps, or are you just using Default?

Unfortunately, this program is not open source, and based on the FAQ it is mostly just hooking into Mouse events.
It is very possible that Office is just directly listening to those Mouse Events as well, and therefore not getting any modified events you are sending it.
Best advice would be to look for vendor options to reprogram, or work with your IT department on that Registry Walkthrough above (Like Logitech options for it's Mice, et cetera)
Changing Touchpad scroll direction with Windows 10 Settings

A: If you open X-Mouse Button Control and view the Layer 1 tab, then when you click a mouse button or roll the wheel the corresponding item flashes in the list of mappable events.  If you 2-finger drag your touchpad over something like a Chrome window then you see no flashing, but if you do this over an MS-Office window then the Wheel Up and Wheel Down events flash depending on the direction of the drag.  The same happens if you pinch on the trackpad to zoom in and out.  So my guess is that MS-Office supports trackpad gestures by injecting mouse wheel events into the application, which means that X-Mouse will invert them if that's what you've told it to do.
So perhaps the Registry hack is the best way to invert the mouse wheel after all - I'll give that a try later and update this answer with my findings.
[edit] I tried the FlipFlopWheel registry hack.  It changed the behaviour of my mouse but left my trackpad untouched, presumably because the hack only affects the HID associated with the device identified in Device Manager.  I guess if I connected another mouse then I'd have to repeat the hack.  But I now have "natural" scrolling in Office as well as the rest of my apps!  Oh, and with the Registry hack it was sufficient to disable and re-enable the device to get the new setting to take effect - no need to log out or reboot.  I discovered this by accident because I was disabling devices one at a time to find out which one was the mouse in my hand.


text:
Q: Chef stuck at "Recipe: java::openjdk" I'm currently using knife zero to help me provision the servers and the commands are executed through Jenkins.
But recently I noticed that the process will stuck halfway through without any error and it is always at the part where it start executing the Java recipe.
So every time the process got stuck, I will have to reboot my system to get it running again.
The Java cookbook i'm using is from Chef supermarket.
https://supermarket.chef.io/cookbooks/java/versions/1.50.0
How should I debug this issue?

A: I would agree with @coderanger that this sounds like a symptom of a process that is waiting for user input before it can continue. Is it possible that you're trying to install Java 7 and haven't included the attribute accept_oracle_download_terms?
From the docs for that cookbook, this is explicitly noted as being required:

To install Oracle Java 7 (note that when installing Oracle JDK,
  accept_oracle_download_terms attribute must be set

A: After much investigation, I found out that this is due to the lack of available ram in the system when chef is running.
I use the sudo sh -c 'echo 3 > /proc/sys/vm/drop_caches' command to clear up the caches at the start of each run and my script no longer get stuck anymore.
http://linuxinsight.com/proc_sys_vm_drop_caches.html


text:
Q: onclick select whole text textarea iam not understanding how to copy to clickboard as soon as I click on a textarea..I mean it should select all content inside it and then it should  pop and and ask something like 'press ctrl c' to copy into clipboard..
I already have a code BUT unable to select full text in text area and should copy into clipboard..
 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
 <head>
 <script type="text/javascript">

function myfunc2() {
 var selectedobj=document.getElementById('showthis');

  if(selectedobj.className=='hide'){  //check if classname is hide
    selectedobj.style.display = "block";
    selectedobj.readOnly=true;
    selectedobj.className ='show';
  }else{
    selectedobj.style.display = "none";
    selectedobj.className ='hide';
 }
}

function copyToClipboard (text) {
  window.prompt ("Copy to clipboard: Ctrl+C, Enter", text);
}

function select_all()
{
// alert(document.getElementById("showthis").value);

var text_val=eval("document.getElementById('showthis').value");
text_val.focus();

var copy = text_val.select();
window.prompt ("Copy to clipboard: Ctrl+C, Enter", copy);

}

</script>
 </head>

 <body>

            <label  onclick="myfunc2()">Click here</label>
            <textarea id="showthis" style="display:none" class="hide"  onclick="select_all()" readonly>dfdsfsfasdfdsfsfasdfssdfsfasf</textarea>

 </body>
</html>

could anyone pls look into this...
EDITED:
I need only Javascript code (not JQuery)

A: try this code to select text inside TextBox or TextArea:
<textarea id="txtSelect">Hello</textarea>

<script type="text/javascript">
    var textBox = document.getElementById("txtSelect");
    textBox.onfocus = function() {
        textBox.select();

        // Work around Chrome's little problem
        textBox.onmouseup = function() {
            // Prevent further mouseup intervention
            textBox.onmouseup = null;
            return false;
        };
    };
</script>

if you need to select text and get it copied to clipboard i think you should a plugin for that purpose. Look at this question ::
Copy text to the client's clipboard using jQuery

A: On the base of your code I have developed the following example, hope it will be helpfull:
HTML:
<textarea id="showthis" class="hide" readonly>click to copy</textarea>

JS:
$(function(){
    var select_all = function(control){
        $(control).focus().select();
        var copy = $(control).val();
        window.prompt ("Copy to clipboard: Ctrl+C, Enter", copy);
    }
    $("#showthis").click(function(){
        select_all(this);
    })
})

A: Using JQuery, It will be just:
$('#showthis').select()

Using just javascript:
document.getElementById('showthis').select()


text:
Q: R: creating a new variable in data frame inside a user defined function I have a dataframe with (age and gender). Based on the age and gender of each record in my dataframe, I want to look through a reference data frame (called bmi)and calculate something and create a new variable in my data frame and assign to the calulated value to it. Following is my function for the calculation lambda
lambda <-function(ag, gnd, ibmi) {

  sel <- ibmi[ibmi$age==ag & ibmi$gender == gnd, ]
  out <- boxcox(lm(bmi~1, data = sel), data = sel)
  rn <- range(out$x[out$y > max(out$y)-qchisq(0.95,1)/2])
  (rn[1] + rn[2])/2
}

This is how I call this function and create the new variable in my data frame
myData$L <- lambda(myData$age, myData$gender, bmi)
I pass age, gender and reference data frame bmi to the function lambda. But I get the following Warning and getting same answer repeated for all the records of different age and gender.
Warning messages:
1: In ibmi$age == ag :
  longer object length is not a multiple of shorter object length
2: In ibmi$gender == gnd :
  longer object length is not a multiple of shorter object length

Can someone please help me.


text:
Q: Create association on non-primary key fields with Entity Framework 4.1 Fluent API We are using EF 4.1 and the fluent API to get data from a legacy database (that we are not permitted to change). We are having a problem creating a relationship between two tables where the related columns are not primary and foreign keys.
With the classes below, how would we configure the one-to-many relationship between Report and RunStat such that Report.RunStats would return all of the RunStat entities where the ReportCode fields are equal?
public class Report
{
    [Key]
    public int ReportKey { get; set; }
    public string Name { get; set; }
    public int ReportCode { get; set; } // Can we associate on this field?
    public virtual ICollection<RunStat> RunStats { get; set; }
}

public class RunStat
{
    [Key]
    public int RunStatKey { get; set; }
    public int ReportCode { get; set; }
    public DateTime RunDate { get; set; }
}

Basically, I want to use the Fluent API to configure EF such that it considers Report.ReportCode to be the foreign key and RunStat.ReportCode to be the primary key.

A: This capability is now possible in EF Core 1.0 (EF7) as indicated in the reference provided by @Brian on Jul 16, 2014 to a feature request posted to Microsoft's UserVoice forum.
So that this valuable information is not lost should this information disappear at the referenced page, here is the text of the feature request:

Unique Constraint (i.e. Candidate Key) Support
(posted by Kati Iceva on Sep 10, 2010)
SQL Server and other databases support Unique Constraints on tables.
  Foreign key constraints are generally based on unique constraints on
  the principal side, with the Primary Key being only a special case of
  a unique constraint. The Entity Framework currently only supports
  basing referential constraints on primary keys and does not have a
  notion of a unique constraint. The idea is to have:

*

*Support for specifying a unique constraint on an Entity

*Support for specifying a foreign key associations that on the principal end specify columns(s) that comprise a unique constraint but
  are not the primary key.

And Microsoft's announcement of the implementation of this capability in EF Core 1.0:

Completed
(posted by Diego Vega (Program Manager, Microsoft Entity Framework) on Aug 9, 2016)
Closing as support for this feature was added in EF Core 1.0 and we
  don't have plans to add it in the EF6 codebase. Also, please create
  new ideas for specific improvements to the feature.

A: It is not possible. Relations in EF follows exactly same rules as in the database. It means that principal table must have unique identifier which is referenced by dependent table. In case of database the identifier can be either primary key or unique column(s) of principal table. Otherwise it is not valid relation.
Entity framework doesn't support unique keys. If you want to have one-to-many relation between Report and RunStat your dependent table (RunStat) must contains column with value of Report.ReportKey. There is no other way to make it automatic - otherwise you must simply make it custom property and fill it from entity framework manually when you need it.


text:
Q: bind tmux prefix to OS X cmd key (or any other binding) I'm used to iTerm2 (or Terminal.app for this case) on OS X. But I want to move to use tmux (or screen, but the problem is similar to both apps).
So my idea is to have a single iTerm tab with a tmux session opened with multiple tabs. To do the transition I have a basic feature I need to configure on tmux: switch the the tab 'n' by using cmd + n (like Firefox, Chrome, iTerm2 itself, etc)
However I can't find a way of mapping the cmd key on the mac keyboard. I first tried to implement cmd as a prefix key, with no success. I've tried setting
set-option -g prefix M-a (hoping for Meta-a)
set-option -g prefix ^a (hoping for ^ to work)
but nothing works. Is this possible? I don't really need to bind the prefix to cmd, but I want to be able to change tmux tabs with cmd+n.
Thank you

A: In iTerm2, you can map shortcuts to hex codes that get sent into the terminal.
Goto iTerm2 Preferences -> Keys.
In Global Shortcut Keys, click the + and add type your desired shortcut like the cmd+1, which will be captured. Then select "Send Hex Code". In the box that appears, type the hex codes that you want sent to tmux separated by spaces. Ctrl-B is 0x02, so for "Ctrl-B 1", type "0x02 0x31". See here for more hex codes: http://www.nthelp.com/ascii.htm
I mapped Cmd with h,j,k,l for moving around between tmux panes, and Cmd with % and " for creating the splits.
I'll probably do something similar to move between vim splits with one control key.

A: Special shortcuts can be made with Terminal.app. I just found out the other day, but this may have been possible prior to lion.
Go into Preferences > Settings and click on the "Keyboard" tab. Now you need to add a new keyboard shortcut by clicking on the plus icon below the box. Now you want to set a key combo that "Sends string to shell."
Example:
Let's say I want to set M-LeftArrow to be mapped to prefix-p (previous window).
Key: Left Arrow
Modifier: Option
Action: send string to shell

Now just type in prefix-p into the input box where prefix is whatever you have set for tmux (I use cntrl-a so the box displays \001p). Note that if you make a mistake, delete characters will be inserted instead of actually deleting characters, so hit the "Delete one character" button to move backwards, in case you mess up.
Special characters I have set to make life easier:
M-Left  > Previous Window
M-Right > Next Window
M-Up    > Enter scrolling mode
M-Down  > Next Pane

You can also modify cntrl-anything and shift-anything, but do remember that these could interfere with your $EDITOR or other programs, so be careful about what special functions might be rendered useless.
Also, note that I could not figure out how to duplicate this functionality in iTerm2.

A: You want to invoke a sequence of keystrokes (first Ctrl-b, then n ranging from 0 to 9).
Your best bet is to use a keyboard shortcut utility such as Butler or Keyboard Maestro to do this for you.

Using Butler:
Select + » Smart Item » Keystrokes, configure the hotkey Cmd-1. Press Ctrl-B, then 1 for the Keystrokes. Configure it to be only valid in Terminal (or iTerm). It will warn you that other applications might not like it, but you know that already.

Using Keyboard Maestro:
Create a new group on the left that is only available in Terminal (or iTerm).
Add a new item, triggered by Hot Key Trigger (Cmd-1) and add two Keystrokes to its actions: Ctrl-B and 1.

You might also want to take a look at this topic -- doesn't use Command though, and didn't work for me using Terminal.

From the tmux documentation:

Bind key key to command. Keys may be specified prefixed with 'C-' or 'ˆ' for ctrl keys, or 'M-' for alt (meta) keys. The −r flag indicates this key may repeat, see the repeat-time option.

They don't support a third modifier key.

A: You may also want to consider the native (but very experimental) integration that iTerm2 offers with tmux:
http://code.google.com/p/iterm2/wiki/TmuxIntegration
That way, when you press Cmd-D to split the screen iTerm2 will split the tab for you. This is great, because the split is native, so you can drag the edge in the middle to re-adjust widths, or you can select a pane by clicking. Ditto for new tabs/windows (but the shortcuts are slightly different -- otherwise you'd have no way to add non-tmux tabs).
And like tmux, if you detach and re-attach, everything will be saved for you.
There are two caveats though:
* this is a very experimental feature and very flaky for me.
* you will have to build tmux yourself (using the archive somewhere on the link above).
-Chris

A: You might also look at this blog post that has very detailed explanations about tmux/iterm integration:
http://tangledhelix.com/blog/2012/04/28/iterm2-keymaps-for-tmux/


text:
Q: Declaring and initializing array of classes in C at runtime Okay, first I will begin with some background.
I'm working on a project for a class that involves a client and a server. They are two separate processes that communicate with each other through what we are calling request channels.
The client collects command line arguments for the number of requests, the size of the buffer for the request channels, and the number of worker threads that send the requests (-n, -b, and -w respectively).
How ever many worker threads the user wants is how many request channels I must create between the client and server.
RequestChannel *channel;

int main(int argc, char * argv[])
{
    char *n=NULL, *b=NULL, *w=NULL;
    int num, buf, workers;
    char optchar=0;

    while((optchar=getopt(argc,argv,"n:b:w:"))!=-1)
    switch(optchar)
    {
        case 'n':
            n=optarg;
            break;
        case 'b':
            b=optarg;
            break;
        case 'w':
            w=optarg;
            break;
        case '?':
            break;
        default:
            abort();
    }
    num=atoi(n);
    buf=atoi(b);
    workers=atoi(w);

    channel=malloc(workers*sizeof(RequestChannel));

    cout << "CLIENT STARTED:" << endl;

    pid_t child_pid;
    child_pid = fork();

    if(child_pid==0)
    {
       execv("dataserver", argv);
    }
    else
    {
        cout << "Establishing control channel... " << flush;
        RequestChannel chan("control", RequestChannel::CLIENT_SIDE);
        cout << "done." << endl;

        for(int i=0;i<workers;i++)
            RequestChannel channel[i](chan.send_request("newthread"), RequestChannel::CLIENT_SIDE);
    }
}

I'm getting compile errors with the malloc line and I don't know what the issue is. I just want to be able to access each RequestChannel like channel[i].
The way it is now, I receive an error saying

invalid conversion from void* to RequestChannel*

When I replace the sizeof(RequestChannel) with sizeof(*RequestChannel), I receive an error saying

expected primary-expression before ')' token.

A: The malloc line is correct (but please check if it returns NULL). A C++ compiler (not C) complains since in C++ you need a cast:
channel = static_cast<RequestChannel *>malloc(...);

or, with C syntax:
channel = (RequestChannel*) malloc(...);

A: Besides the compiler error you also have logical one.
For example, you should explicitly call constructor for every object to create them. But you just allocate the space for them and then just use it. It will lead to very strange errors.
Also don't forget about calling destructor. Anyway, why don't you use new operator?


text:
Q: Detect DOM level in JavaScript? There are multiple levels of DOM. Is there a DOM API for JavaScript which could detect the highest supported DOM level of current execution engine at runtime?

A:     if(document.implementation){
        if(document.implementation.hasFeature('Core','2.0')){
            alert('DOM2 Core supported');
        }else{
            alert('DOM2 Core not supported');
        }

    }

A: The short answer is no. There used to be but it has been removed.
Introduced in DOM 1, document.implementation.hasFeature( "HTML", "1.0") was supposed to return true if HTML was supported at DOM level 1.0. Whilst a presumption might be made that this could be used to detect the DOM level supported by increasing the version parameter until false is returned, implementations of the feature were unreliable to the point that DOM4 requires the method to return true in all cases so as not to break the web.
MDN warns not to use hasFeature and to remove it from existing code if possible
That leaves standard feature detection by means of either checking for the presence and type of DOM methods that need to be used or trying them inside try/catch blocks.


text:
Q: Exporting shapefiles to file geodatabase results in no coordinate system (ArcMap) I export shapefiles with a defined coordinate system to a file geodatabase assigning the export coordinate system same as input file, but when I try to import them back into the project from the file geodatabase, they do not have an assigned coordinate system. Not sure where I'm going wrong.

A: It turns out, when you create a a feature dataset within a file geodatabase, you have to define the coordinate system of the feature dataset to which you will import data at the time of the creation of the feature dataset (you cannot assign later), regardless of whether or not the data that you will import has a defined coordinate system.


text:
Q: Listing the files on a device from the command line On the left side of the Dolphin display, one of the categories shown is "Devices".  Just as one would expect, clicking on any of the listed devices shows the files available from that device, e.g., a camera or a memory stick. if the device isn't read-only, you can even use the Dolphin display to add files to the device.  But how can one get that same list of files (for any listed device) from the command line, using either ls or something similar to it?  I would expect the method to be the same no matter what the nature of the device. And if the device is writable, how would you write to it from the command line?

A: With command line there is a small bit that you have to keep in mind - it has to be mounted ( in other words connected programmaticaly to the system; it may be physically connected like a USB drive to USB port, but that doesn't mean it is mounted ).
Checking if device is mounted is easy enough - lsblk, df commands or mount without any - flags/options.
Now, by default, Ubuntu's GUI such as Unity or Gnome automatically mount the devices you connect. With pure command line or  a GUI that doesn't do this automatically (like openbox or blackbox ), you have to issue mount command or udiscksctl mount --block /dev/sd* where * is the letter for that device. I'd prefer the last one, since it automatically mounts to /media folder. With mount you have to specify the folder. Also with mount you have to know filesystem type, like NTFS (windows), ext4 (linux), FAT (many USB drives).
As for actual listing of the files, there is plenty of ways

*

*find /directory/where/device/mounted -type f is a recursive way to list all files in all folders on that device.

*ls /mount/folder

*stat /mount/folder

*dir which is same as ls

A: The phrase In UNIX, everything is a file can be applied here: Each physical drive plugged into your computer will be represented by one or more files inside /dev, as long as it is recognized by the system.
In order to be readable and writable, these devices need to be mounted somewhere. To get a list of all mounted devices, use the command mount. Here is an extract of my mount table:
/dev/sda1 on / type ext4 (rw,errors=remount-ro)
proc on /proc type proc (rw,noexec,nosuid,nodev)
sysfs on /sys type sysfs (rw,noexec,nosuid,nodev)
/dev/sdc1 on /media/sebastian/some-id type ext4 (rw,nosuid,nodev,uhelper=udisks2)

If your device is not listed here, it isn't mounted yet. Most file managers auto-mount drives when they are plugged in, but if they aren't, or you aren't using a file manager, you can do this manually. First list the partitions you got with lsblk. This will give information like the following:
NAME   MAJ:MIN RM   SIZE RO TYPE MOUNTPOINT
sda      8:0    0 232.9G  0 disk
├─sda1   8:1    0 224.8G  0 part /
├─sda2   8:2    0     1K  0 part
└─sda5   8:5    0   8.1G  0 part [SWAP]
sdc      8:32   1   3.8G  0 disk
└─sdc1   8:33   1   3.8G  0 part /media/sebastian/some-id

From here we can see that the USB stick I just plugged in is enumerated as /dev/sdc, and it has one partition with the number 1. This partition can be found at /dev/sdc1. As you noticed, it is already mounted, but let's just assume it isn't. Here are the steps to manually mount a drive:

*

*mkdir /mnt/somedir will create a directory with the name somedir (change name at one's leisure) inside /mnt. Here you will mount the drive.

*mount /dev/sdc1 /mnt/somedir will attempt to mount the partition /dev/sdc1 (my USB stick's only partition) in /mnt/somedir

*In case this fails, you may have to give optional arguments, because mount is quite smart, but can't always guess what to do. For this, best look at the options presented in man mount. An option you may need could be -t <type> to indicate the partition format, e.g. mount -t vfat /dev/sdc1 /mnt/somedir. If mount complains that you don't have the necessary permissions, add yourselves to the group plugdev or execute the mount command as root with sudo mount <...>
The partition should now be mounted, so again run mount to see the new entry. You can now jump into the mounted partition with cd /mnt/somedir. Now type ls to list the contents of the drive.
To get files from the drive to your computer, and vice versa, use the cp command:
cp <source> <destination>

e.g.
cp image1.png image2.png image3.png /home/username/Pictures

will copy the three files over to your Pictures folder.
To unmount a device after using it, use the umount command:
umount /dev/sdc1

or
umount /mnt/somedir

You can now safely delete the mount directory, but you don't have to.