text:
Q: BitmapImage cannot access the file In my current project, I need to download the file from the Internet once and use them in my WPF application later. I've set up this lazy loading pattern in order to download/initialize BitmapImage only when requested by application, but despite my utmost effort, I can't get it to work. The problem is that I get IOException when it tries to instantiate BitmapImage.
Below I post a complete application, that you can run yourself and arrive the same problem...
public partial class MainWindow : Window, INotifyPropertyChanged
    {
        string url = @"http://upload.wikimedia.org/wikipedia/commons/d/d3/Nelumno_nucifera_open_flower_-_botanic_garden_adelaide2.jpg";
        string filename = "PrettyFlower.jpg";
        Mutex m = new Mutex();
        bool isLoaded = false;
        BitmapImage flowerImage = null;

        public MainWindow()
        {
            InitializeComponent();

            Binding b = new Binding("FlowerImage");
            b.Source = this;
            img.SetBinding(Image.SourceProperty, b);
        }

        public BitmapImage FlowerImage
        {
            get
            {
                if (isLoaded == false)
                {
                    LoadImage();
                    return null;
                }
                return flowerImage;
            }
        }

        private async void LoadImage()
        {
            WebClient wc = new WebClient();
            m.WaitOne();

            FileInfo fi = new FileInfo(filename);
            if (fi.Exists == false)
            {
                await wc.DownloadFileTaskAsync(url, filename);
            }

            flowerImage = new BitmapImage(new Uri("pack://siteOfOrigin:,,,/" + filename));
            isLoaded = true;
            OnPropertyChanged("FlowerImage");

            m.ReleaseMutex();
        }

        public event PropertyChangedEventHandler PropertyChanged;

        protected void OnPropertyChanged(string propertyName)
        {
            if (PropertyChanged != null)
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }

And corresponding MainWindow.xaml is nothing more but:
<Window x:Class="WpfApplication1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
   <Image x:Name="img"/>
</Window>

I do notice whats going on, but honestly I don't understand why is this happening - that is, BitmapImage is instantiated before the download completes, but shouldn't mutex here prevent this behaviour?

A: You won't use a Pack URI for this. Instead use a plain file URI that references the downloaded file (where filename is the full path as in your code):
flowerImage = new BitmapImage(new Uri(filename));

A: Ok, I got this to work finally, and it is not like Clemens said.. :(
The problem seems to be ... (and I believe it is) that LoadImage doesn't start another thread until it calls wc.DownloadFileTaskAsync. This is the only thing that runs in another thread, therefore... the call to WaitOne() is completly silly, since mutex is claimed by UI thread ...
The way I got it to work is...
private async void LoadImage()
        {
            WebClient wc = new WebClient();

            await Task.Run(() =>
                {
                    m.WaitOne();

                    FileInfo fi = new FileInfo(filename);
                    if (fi.Exists == false)
                    {
                        wc.DownloadFile(url, filename);
                        wc.Dispose();
                    }

                    m.ReleaseMutex();
                });

            m.WaitOne();
            flowerImage = new BitmapImage(new Uri("pack://siteOfOrigin:,,,/" + filename));
            m.ReleaseMutex();

            isLoaded = true;
            OnPropertyChanged("FlowerImage");
        }


text:
Q: Installing nservicebus Servicecontrol in loadbalanced environment I am to install NServiceBus ServiceControl in a two machine setup (Load balanced by F5 box).
any idea if both instance are sharing same RavenDatabase location, will it work?

A: ServiceControl uses an embedded RavenDB instance. This configuration does not support load balancing. It only supports high availability via clustering (active/passive).
See the following guidance on high availability:
http://docs.particular.net/servicecontrol/deploying-servicecontrol-in-a-cluster

redpajama_set_name: RedPajamaStackExchange


text:
Q: Changing the Pin of a Virtual SmartCard in Windows 10 In our environment we need a virtual smart card for VPN authentication under Windows 10 and we need to create a little tool for the users to change the pin of the virtual smart cards.
I've downloaded the Smart card sample to see how to create a virtual smart card and change it's pin. But I'm having trouble with running the code.
My first problem is, that I'm getting a 'The request requires elevation' Exception on calling the method RequestVirtualSmartCardCreationAsync. I'm using the default parameters defined in the project. I tried to log-in as an Admin and Visual Studio is also started as Administrator. I also made sure that the 'Shared User Certificates' option is checked under Capabilities in the appxmanifest.
Next I tried to create a virtual smart card with the tpmsvcmgr.exe command line tool. The command line was: tpmvscmgr.exe create /name myVSC /pin prompt /adminkey default /generate
I made sure that the virtual smart card was generated successfully by finding it in the device manager under Smartcard-Readers.
Next I modified the code from the sample by setting the SmartCardReaderDeviceId in the ValidateTPMSmartCard() method just before the check whether the string is empty.
I tried different values for this variable but I'm still getting Exceptions in the GetSmartCard() method on SmartCardReader.FromIdAsync during code execution. Here are the values that I tried with the according Exceptions that I get:
//NO_SUCH_DEVICE_INTERFACE
SmartCardReaderDeviceId = "ROOT\\SMARTCARDREADER\\0000";
//NO_SUCH_DEVICE_INTERFACE
SmartCardReaderDeviceId = "\\ROOT\\SMARTCARDREADER\\0000";
//NO_SUCH_DEVICE_INTERFACE
SmartCardReaderDeviceId = "\\\\?\\ROOT#SMARTCARDREADER#0000";
//REQUEST_NOT_SUPPORTED
SmartCardReaderDeviceId = "\\\\?\\ROOT#SMARTCARDREADER#0000#{50dd5230-ba8a-11d1-bf5d-0000f805f530}";
//NO_SUCH_DEVICE_INTERFACE
SmartCardReaderDeviceId = "50dd5230-ba8a-11d1-bf5d-0000f805f530}";

Does anyone know either how to get this SDK sample to work or how to change the PIN of a virtual smart card programatically?
I'm running this Project under Windows 10.0.10586 with Visual Studio Enterprise 2015 on a Surface Pro 4.


text:
Q: Undefined reference to 'function' that has been defined I've started learning C++ and trying to figure out how header files work.
I have
main.cpp
#include <iostream>
#include "fibonacci.h"
using std::cout;
using std::cin;
using std::endl;

int main(){
   int n;
   cin >> n;
   for(int i = 0; i < n; i++)
       cout << fibonacci(i) << ", ";
   cout << endl;

   return 0;
}

fibonacci.h
#pragma once
int fibonacci(int n);

fibonacci.cpp
#include "fibonacci.h"

int fibonacci(int n){
    if(n == 0){
        return 0;
    }
    if(n == 1){
        return 1;
    }
    return fibonacci(n - 1) + fibonacci(n-2);
}

But while building I get undefined reference to 'fibonacci(int)' error.
I'm using VSCode and g++ compiler.


text:
Q: xamarin forms - ios - listview header - showing bold border? Please see below image

please see below code
//PopUp.Xaml

            <ListView.Header>
                <Frame>
                    <Grid>

                        <Grid.RowDefinitions>
                            <RowDefinition Height="*"/>
                            <RowDefinition Height="Auto"/>
                        </Grid.RowDefinitions>

                        <Grid.ColumnDefinitions>
                            <ColumnDefinition Width="30*" />
                            <ColumnDefinition Width="25*" />
                            <ColumnDefinition Width="25*" />
                            <ColumnDefinition Width="20*" />
                        </Grid.ColumnDefinitions>

                        <Label Grid.Column="0" Grid.Row="0" Text="Product"
                       HorizontalOptions="Center"/>
                    <Label Grid.Column="1" Grid.Row="0"
                   Text="Quantity"
                       HorizontalOptions="Center"/>
                    <Label Grid.Column="2" Grid.Row="0"
                   Text="Price"
                       HorizontalOptions="Center"/>
                    <Label Grid.Column="3" Grid.Row="0"
                   Text="Sub"
                       HorizontalOptions="Center"/>

                        <BoxView Grid.Row="1"
                         Grid.ColumnSpan="4"
                         HeightRequest="1"
                         BackgroundColor="LightGray"/>

                    </Grid>
                </Frame>
            </ListView.Header>

            <ListView.ItemTemplate>
                <DataTemplate>
                    <ViewCell>
                        <Grid Padding="10" RowSpacing="10" ColumnSpacing="10">
                            <Grid.RowDefinitions>
                                <RowDefinition Height="Auto"/>
                                <RowDefinition Height="*"/>
                            </Grid.RowDefinitions>
                            <Grid.ColumnDefinitions>
                                <ColumnDefinition Width="43*" />
                                <ColumnDefinition Width="8*" />
                                <ColumnDefinition Width="25*" />
                                <ColumnDefinition Width="24*" />
                            </Grid.ColumnDefinitions>
                            <Label Grid.Column="0" Text="{Binding OrderModel_Id}" VerticalOptions="End"/>
                        <Label Grid.Column="1" Grid.Row="0" Text="{Binding User_Name}" VerticalOptions="End"/>
                        <Label Grid.Column="0" Grid.Row="0" HorizontalOptions="StartAndExpand" VerticalOptions="StartAndExpand" Text="{Binding Product_Id, Converter={StaticResource converter}}"/>
                            <Label Grid.Column="1" Grid.Row="0" HorizontalOptions="CenterAndExpand" VerticalOptions="CenterAndExpand" Text="{Binding Quantity}"/>
                            <Label Grid.Column="2" Grid.Row="0" HorizontalOptions="CenterAndExpand" VerticalOptions="CenterAndExpand" Text="{Binding PriceOf_Item, StringFormat='£{0:0.00}'}"/>
                            <Label Grid.Column="3" Grid.Row="0" HorizontalOptions="CenterAndExpand" VerticalOptions="CenterAndExpand" Text="{Binding SubtotalForThis_Item, StringFormat='£{0:0.00}'}"/>
                        </Grid>
                    </ViewCell>
                </DataTemplate>
            </ListView.ItemTemplate>
        </ListView>
    </StackLayout>

</pages:PopupPage>

My Q being why does the popUp header of the listview...appear with a bold border below it? only on ios...not on android...I would like to remove it please. does anyone know how?


text:
Q: Use object between multiple functions I am creating a spam email checker. One method scans the email, another adds a known flag to an array of words and phrases to check against; both methods are part of Tester class. Currently I have a button per method, however each event creates its own spam object. How do I get both events to use the same object, allowing the scan to recognize the flag I just added?
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace HW8_DR
{
    public partial class Spam_Scanner : Form
    {
        public Spam_Scanner()
        {
            InitializeComponent();
        }

        private void testButton_Click(object sender, EventArgs e)
        {
            Tester scan = new Tester();
            scan.tester(Convert.ToString(emailBox.Text));
            this.SpamRatingBox.Text = string.Format("{0:N1}%", Tester.countSpam / Tester.wordCount * 100);
            this.WordsBox.Text = Tester.posSpam;
            this.OutputPanal.Visible = true;
            this.pictureBox1.Visible = false;
        }

        private void addButton_Click(object sender, EventArgs e)
        {
            Tester scan = new Tester();
            scan.addSpam(Convert.ToString(addFlagBox.Text));
            this.addFlagBox.Text = "";
        }
    }
}

A: Move the Tester variable to the class field, like this:
public partial class Spam_Scanner : Form
{
    Tester scan;

    public Spam_Scanner()
    {
        InitializeComponent();
        scan = new Tester();
    }

    private void testButton_Click(object sender, EventArgs e)
    {
        scan.tester(Convert.ToString(emailBox.Text));
        this.SpamRatingBox.Text = string.Format("{0:N1}%", Tester.countSpam / Tester.wordCount * 100);
        this.WordsBox.Text = Tester.posSpam;
        this.OutputPanal.Visible = true;
        this.pictureBox1.Visible = false;
    }

    private void addButton_Click(object sender, EventArgs e)
    {
        scan.addSpam(Convert.ToString(addFlagBox.Text));
        this.addFlagBox.Text = "";
    }
}

A: Variables declared inside of a method (as yours are) have method scope, so they can't be seen by other methods.
Instead, declare the variable in the class scope so that both the class's methods can see it.
public partial class Spam_Scanner : Form
{
    private Tester scan;

    private void testButton_Click(object sender, EventArgs e)
    {
       scan = new Tester();
       ...
    }

    private void addButton_Click(object sender, EventArgs e)
    {
      scan.addSpam(Convert.ToString(addFlagBox.Text));
      ...
    }
}

Depending on the order of button clicks, you may want to initialize the variable in the declaration rather than in the testButton_Click method, but thats up to you. The important thing to remember is that scopes can see their own members, and all scopes they are nested in. Thus, methods can see class-scope variables, but not each other's.


text:
Q: Run a Powershellscript by clicking a button on HTML/PHP I'm trying to find out, how I can run a simple powershellscript by clicking on a button. What am I doing wrong?
I tried the following:
<input type="button"> onclick="<?php hello.ps1; ?>">
and this one:
<input type="button" onclick="hello.ps1" value="Send" name="button"/>

Inside the .ps1 is the following:
Write-Output "Hello World"


text:
Q: Does the function $x^2 \sin({1 \over x})$ have a tangent at $0$? Consider the function $f(x)$ defined by $x^2 \sin({1 \over x})$. Remove the discontinuity at $0$ by setting $f(0)$ to $0$. This function is continuous everywhere on $\mathbb{R}$, and it seems differentiable everywhere on $\mathbb{R}^\times$ (ie. $\mathbb{R}$ without the origin).
Is it differentiable at $0$? Equivalently, does this function have a tangent line at $0$? Intuitively, it seems to me that, near $0$, it wiggles like crazy (at smaller and smaller scales), and the wiggles never "settle down", in the sense that, if you try to construct the tangent to the graph (passing through $(0, f(0))$ by using secants (passing through $(0, f(0))$ and $(0+\delta, f(0+\delta))$ , and letting $\delta\to 0$), your secants will never converge to the tangent (which, if it exists, I think should be the constant line $y=0$).
Is this correct?

A: For $x\neq 0$
$$\frac {f (x)-f (0)}{x-0}=x\sin (\frac {1}{x}   )$$
but
$$|x\sin ( \frac {1}{x} )|\leq |x|$$
$$\implies $$
$$\lim_{x\to 0} x\sin (\frac {1}{x}   )=0$$
$$\implies $$
$f $ is diffetentiable at $x=0$ and
$$f'(0)=0$$.


text:
Q: Save image to desktop from iframe tag I am using iframe tag to display image. Also there is a Save Image Button on page. I want that when user click the button, then the image inside iframe should save on desktop.
Remember i want only image to be saved on desktop not the whole page.
How to do this...
eg:

<title></title>

<form id="form1" runat="server">
<asp:Button ID="Button1" runat="server" OnClientClick="saveIt();" Text="Save" />

</form>

A: You can try this code. I've tested this and working fine:

    <title></title>

    <form id="form1" runat="server">
        <input type="button" id="Button1" runat="server" onclick="saveIt();"
               value="Save" />

    </form>


text:
Q: GalaSoft.MvvmLight.EventToCommand args always null I have a base class derived from MvvmLight.ViewModelBase with additional responsibilities to handle object selections.  This class defines a RelayCommand<MouseButtonEventArgs> property which is bound in the View:
        <i:Interaction.Triggers>
            <i:EventTrigger EventName="MouseDown">
                <galaxcmd:EventToCommand Command="{Binding SelectCommand,Mode=OneWay}" PassEventArgsToCommand="True"  />
            </i:EventTrigger>
        </i:Interaction.Triggers>

This view is used multiple times inside a containing view that I now need to handle mousedowns too.  My issue arises because I don't want the container to handle mousedown if it was handled by a contained view.  I thought the PassEventArgsToCommand was my solution to this problem because I planned a child VM to just set MouseButtonEventArgs.Handled = true.  Unfortunately, the MouseButtonEventArgs argument is always null.  Just in case, I also tried RoutedEventArgs and even EventArgs, but they're all null too.
What am I doing wrong with EventToCommand (or EventTrigger?)?

A: You can find here a modified EventToCommand implementation - based on the Galasofts one - where you can set the Eventargs as CommandParameter and stop event routing.


text:
Q: Issues with div inside div height I have an issue with the code below. If you run it you'll see that the background doesn't flow with the content, any ideas how to fix this, thanks.
All the divs are needed the sw is used to stop the content going bigger then 900px;
one and two are used to slit the content into two columns unless its a mobile device, i.e less then 481px;
<!DOCTYPE html>

            Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.

            Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.

A: Because you float the contents, you need to add overflow:auto to the container to restore the behavior you seek:
.sw {
    margin: 0 auto;
    max-width: 900px;
    overflow:auto;
}

jsFiddle example

A: You need to add a clearfix to achieve the effect you want, the float of .one and .two causes the current effect.
#about:before,
#about:after {
  content:"";
  display:table;
}
#about:after {
  clear:both;
}
#about {
  zoom:1; /* For IE 6/7 (trigger hasLayout) */
}

You can read more about it here http://nicolasgallagher.com/micro-clearfix-hack/


text:
Q: prove that $a_{n}$ converges using Cauchy's convergence test Check using Cauchy's convergence test if $a_{n}$ is convergent;
$$a_{1}=\frac{1}{3}$$  $$a_{n+1}=
\begin{cases}
a_{n}^2,  &\text{$a_{n}>\frac{1}{10}$} \\
2a_{n}, & \text{else}
\end{cases}$$
I need to show that $\forall m,n>\mathbb N$ Implies $\vert a_{m}-a_{n}\vert <\epsilon$
That's what I tried so far.
$$
\begin{split}
\vert a_{m}-a_{n}\vert
   &= \vert a_{m}-a_{m-1}+a_{m-1}-a_{m-2}+a_{m-2}+...-a_{n+1}+a_{n+1}-a_{n}\vert \\
   &\le \vert a_{m}-a_{m-1}\vert+\vert a_{m-1}-a_{m-2}\vert+...+\vert a_{n+1}-a_{n}\vert
\end{split}
$$
I don't know how to go from there and if this is even the right way..

A: It is actually not convergent. Try to prove:
[1] $a_n \gt \frac {1}{100}$ by induction on $n$.
[2] $|a_{n+1}-a_n| \gt \frac {1}{100}$ for every $n$.
[2] contradicts the Cauchy criterion (how?), thereby the sequence is divergent.


text:
Q: Differentiation of maps Let $f: \mathbb{R}^3 \to \mathbb{R}$ and $g: \mathbb{R} \to \mathbb{R}$ be differentiable. Let $F: \mathbb{R}^2 \to \mathbb{R}$ be defined by the equation
$$F(x,y)=f(x,y,g(x,y)).$$
(a)Find $DF$ in terms of the partials of $f$ and $g$.
(b) If $F(x,y)=0$ for all $(x,y)$, find $D_1g$ and $D_2g$ in terms of the partials of $f$.

A: it's easier to see when you define a function $h: R^2 \rightarrow R^3 $ where:
$$h(x,y)=(x,y,g(x,y))=(h_1(x,y),h_2(x,y),h_3(x,y))$$
where $h_i: R^2\rightarrow R, i=1,2,3$, and note that $F(x,y)=f(h(x,y))=(f\,o\,h)(x,y)$, here we can use the chain rule (of course h is differentiable), and...
$$DF(x,y)=D(f\,o\,h)(x,y)=Df(h(x,y))*Dh(h,y)$$
then you only have to compute the last equation, but that's not difficult, then you will be in the result given by Berci
Hope help someone

A: (a) $DF$ is the $1\times 2$ matrix of $(D_1F,D_2F)$ where $D_i$'s denote the partials.
Well,
$$\begin{align} D_1F &=D_1f(x,y,g(x,y)) + D_3f(x,y,g(x,y))\cdot D_1g(x,y)  \\
D_2F &=D_2f(x,y,g(x,y)) + D_3f(x,y,g(x,y))\cdot D_2g(x,y)
\end{align}$$
I guess the real question is: Why is it addition between the different partials, and.. well.. they are somehow projections of vectors, maybe someone else can give a more explicit explanation on that.
(b) is straightforward, since then $DF=(0,0)$ , so the left hand sides above become $0$, and we get
$$D_ig(x,y) = -\frac{D_if(x,y,g(x,y))}{D_3f(x,y,g(x,y))} . $$


text:
Q: How to retrieve relationship mapping in hibernate? I need to get the relationship between two model classes.
For example
In database, I have two tables table1 and table2. where table2 has foreign key of table1.
I have two classes Table1 and Table2 that maps to these tables respectively and has a relationship mapping One to One.
Now, from java code I need to retrieve what relationship do they have? i.e the output should be one-to-one for above example.

A: I have prepared this demo to find the association type between two hibernate entity classes. It may help other community users so posting this answer.
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Map;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.metadata.ClassMetadata;
import org.hibernate.metadata.CollectionMetadata;
import org.hibernate.persister.collection.BasicCollectionPersister;
import org.hibernate.persister.collection.OneToManyPersister;
import org.hibernate.service.ServiceRegistryBuilder;
import org.hibernate.type.ManyToOneType;
import org.hibernate.type.OneToOneType;
import org.hibernate.type.Type;

/**
 *
 * @author shruti
 */
public class RelationDemo {

    public static void main(String[] args) throws Exception {

        Configuration configuration = new Configuration().configure();
        ServiceRegistryBuilder builder = new ServiceRegistryBuilder().applySettings(configuration.getProperties());
        SessionFactory sessionfactory = configuration.buildSessionFactory(builder.buildServiceRegistry());

        //1. Read class names
        System.out.println("Enter first class names (make sure you enter fully qualified name): ");
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
        String class1 = bufferedReader.readLine();
        System.out.println("Enter second class names (make sure you enter fully qualified name): ");
        String class2 = bufferedReader.readLine();

        ClassMetadata classMetadata = null;

        //2. Create ClassMetaData for the first class name and check that both the classes exists.
        try {
            classMetadata = sessionfactory.getClassMetadata(Class.forName(class1));
            Class.forName(class2);
        } catch (ClassNotFoundException classNotFoundException) {
            System.err.println("Invalid class name.\nHint: Enter fully qualified class names for eg. packagename.Classname");
            classNotFoundException.printStackTrace(System.err);
            return;
        }

        //3. Retrieve all collection metada for collection type properties
        @SuppressWarnings("unchecked")
        Map<String, CollectionMetadata> allCollectionMetadata = sessionfactory.getAllCollectionMetadata();

        //Retrieve all properties of the first class
        String[] propertyNames = classMetadata.getPropertyNames();

        //Loop through the retrieved properties
        for (String name : propertyNames) {

            //Retrieve type of each property
            Type type = classMetadata.getPropertyType(name.trim());

            //Check if the type is association type
            if (type.isAssociationType()) {

                //Check if it is collection type.
                if (type.isCollectionType()) {

                    //From retrieved collection metadata (Strp 3) get value of the property we are refering to.
                    CollectionMetadata collectionMetadata = allCollectionMetadata.get(class1 + "." + name);

                    //Check if the elements of the collection are of desiered type
                    if (collectionMetadata.getElementType().getName().trim().equals(class2)) {
                        System.out.println("Property Name: " + name);
                        //Check if the value is of type OneToManyPersister
                        if (collectionMetadata instanceof OneToManyPersister) {
                            System.out.println("ONE TO MANY TYPE");
                            return;
                        } //Check if the value is of type BasicCollectionPersister. Note that for many to many relationship it would return an object of type BasicCollectionPersister.
                        else if (collectionMetadata instanceof BasicCollectionPersister) {
                            if (((BasicCollectionPersister) collectionMetadata).isManyToMany()) {
                                System.out.println("MANY TO MANY");
                            }
                        }
                    }
                } //If property is not a collection then retrieve the class of the type and check if it is the same as Second class.
                else if (type.getReturnedClass().getTypeName().equals(class2)) {
                    System.out.println("Property Name: " + name);
                    if (type instanceof ManyToOneType) {
                        System.out.println("MANY TO ONE TYPE");
                        return;
                    } else if (type instanceof OneToOneType) {
                        System.out.println("ONE TO ONE TYPE");
                        return;
                    }
                }
            }
        }
        System.out.println("NO RELATIONSHIP FOUND BETWEEN GIVEN CLASSES");
    }
}

A: Hibernate has metadata package org.hibernate.metadta which will help you.
Please refer to
https://docs.jboss.org/hibernate/orm/3.5/api/org/hibernate/metadata/ClassMetadata.html

A: You can try below code which shows the collection details available for entities:
Map<String,CollectionMetadata> map = sessionFactory.getAllCollectionMetadata();
        Set<Entry<String,CollectionMetadata>> set = map.entrySet();
        for (Entry e : set) {
            System.out.println(e.getKey());
            System.out.println(e.getValue());
        }


text:
Q: Understanding document size in MongoDB My collection.stats():
{
    "ns" : "csdbprotobuf.archive",
    "count" : 429787895,
    "size" : 48374032272,
    "avgObjSize" : 112,
    "storageSize" : 56527326864,
    "numExtents" : 47,
    "nindexes" : 1,
    "lastExtentSize" : 2146426864,
    "paddingFactor" : 1,
    "systemFlags" : 1,
    "userFlags" : 1,
    "totalIndexSize" : 19917512720,
    "indexSizes" : {
        "_id_" : 19917512720
    },
    "ok" : 1
}

paddingFactor is 1, avgObjSize is 112. But the average document size, which I can see using Object.bsonsize() function, is 73.4 bytes. I have no updates, only inserts and deletes. How can I optimize space consumption? How much RAM does each document consume: 112 or 73.4 bytes?
Upd: How many documents can be stored in a one page: <page size>/<avgObjSize from db.stats()> or <page size>/<avg size from Object.bsonsize()>, i.e 4096/112 or 4096/73.4?

A: To answer your question, I start out with an empty collection csdbprotobuf.archive on a stand-alone server that has nothing currently in cache
db.serverStatus({workingSet:1})
"workingSet" : {
    "note" : "thisIsAnEstimate",
    "pagesInMemory" : 10,
    "computationTimeMicros" : 4736,
    "overSeconds" : 81
},

Create the database and insert 10000 documents, an integer _id field and a string some name that has nine characters
use csdbprotobuf
t=db.archive
for(var i = 1; i <= 10000; i++){t.insert({a : i, name : 'some name'})}

Run an explain to load my data into memory called pre-heating
t.find().explain()
> t.find().explain()
{
    "cursor" : "BasicCursor",
    "isMultiKey" : false,
    "n" : 10000,
    "nscannedObjects" : 10000,
    "nscanned" : 10000,
    "nscannedObjectsAllPlans" : 10000,
    "nscannedAllPlans" : 10000,
    "scanAndOrder" : false,
    "indexOnly" : false,
    "nYields" : 78,
    "nChunkSkips" : 0,
    "millis" : 1,
    "server" : "precise64_work:27000",
    "filterSet" : false
}

What is the status of memory?

    "workingSet" : {
        "note" : "thisIsAnEstimate",
        "pagesInMemory" : 363,
        "computationTimeMicros" : 2136,
        "overSeconds" : 600
    },

Initally I had 10 pages of data in memory, after the pre-heat using .explain(), I now have 363 pages in memory. Started out with 31MB of resident memory and now have 34MB which give me a difference of 3MB or 3072KB.
10000 documents / 3072KB = 3.255kb per document.
10000 documents / 353 pages of data = 28 documents per page
Using MongoDB's db.serverStatus({workingSet:1}) command, I was able to determine (approximately) how many documents fit onto a page.
It is important to note though, that each document in MongoDB is totally different. This is because of the polymorphic nature of its schema design. So just trying to determine exactly how much space one document is going to take is probably not what you are looking for.
Just because one document takes up 3KB doesn't mean that the next document won't take up twice that much or even more. This is not the way a traditional RDBMS works as you would know how much space each row can use.


text:
Q: Package dependencies on sub process With subprocess module iam trying to call c-python from iron python and pipe the output back to iron python.
I am working on iron python IDE inside dynamo for revit,I have a c-python script in my desktop and running it.
The question is how do i make sure if the packages in the c- python is available with the end user? Since the end users will not be comfortable going to cmd prompt and install every package(civil engineers may not even know about this) I am searching for a way to open cmd in background with iron python and install the necessary package if they were not previously installed.


text:
Q: Submit in a fetch mode collapsed rows I have this datatable:
 <p:dataTable id="necesidades"
         value="#{registrarAccionDosBean.accionDos.necesidadesConTema}"
         rendered="#{not empty registrarAccionDosBean.accionDos.necesidadesConTema}"
         var="necesidad"
         rowKey="#{necesidad.idNecesidad}">
    <p:column style="width:16px">
        <p:rowToggler />
    </p:column>
    <p:rowExpansion>
        <h:panelGroup id="grupoTema">
            <h:panelGroup id="edicion" rendered="#{necesidad.tema.idTema ne null}">
              <p:row>
                <p:column >
                   <h:outputLabel value="#{etiq.lbl_comunes_requerido} #{etiq.etiqueta_checkbox_transparenciasFocalizadas}" styleClass="textoAcciones"/>
                </p:column>
                <p:column >
                    <!-- Nested data table -->
                    <p:dataTable id="transparenciasInplace"
                         var="transparencias"
                         value="#{registrarAccionDosBean.transparenciasFocalizadas}"
                         selection="#{necesidad.tema.transparenciasFocalizadas}"
                         rowKey="#{transparencias.idTf}">
                        <f:facet name="header">
                            Objetives
                        </f:facet>
                        <p:column selectionMode="multiple" style="width:16px;text-align:center"/>
                        <p:column>
                            <h:outputLabel value="#{transparencias.descripcion}" styleClass="textoAccionesSmall"/>
                        </p:column>
                    </p:dataTable>
                 </p:column>
              </p:row>
            </h:panelGroup>
        </h:panelGroup>
    </p:rowExpansion>
</p:dataTable>

I have n rows collapsed with information inside of each of them, this information was persisted in different times and days, so I need to save some information plus the n rows as a whole, the problem is that the rows are collapsed when is show on screen and I want to be in that way because a can have a lot rows on screen and if I show them expanded it will be hard to read, but when I send it through a command button the table inside my collapsed row are setting null, I need to expand each of them in order to properly send all the information.
So I want to send the information collapsed but in some way force to fetch the information inside of each of them
I am getting the information from the database right, because there I just fetch my query and get the information right, so my problem is on my jsf page I think


text:
Q: Manipulating multidimensional arrays with a variable I want to use the value of a variable and assign it to an array.
For example - this code works:
$mf_hook_emails[19734]['Dept Notify'] = 'customer_service@abc.com';

But this code doesn't work (assigning the email address to a variable first):
$deptemail='customer_service@abc.com';
$mf_hook_emails[19734]['Dept Notify'] = $deptemail;

A: $deptemail='customer_service@abc.com';
$mf_hook_emails[19734]['Dept Notify'] = $deptemail;

This works fine for me. print_r($mf_hook_emails) gives:
Array (
       [19734] => Array (
             [Dept Notify] => customer_service@abc.com
             )
      )

A: You may define it like this:-
 $mf_hook_emails[19734]['Dept Notify'] = (string)$deptemail;


text:
Q: How can I shred this Extended Events XML as fast as possible? I created an Extended Events session in SQL Server 2008 R2.  The session runs, and collects events as they happen, exactly like you'd expect.
If I shred the xml when there are relatively few events, performance is acceptable.  When I have thousands of events, it takes for ever to shred the xml.
I know I am doing something wrong, I just don't have enough knowledge about the internals of the XML engine to understand what.
This is the definition of my Extended Events session:
IF EXISTS
(
    SELECT 1
    FROM sys.server_event_sessions dxs
    WHERE dxs.name = 'queries'
)
BEGIN
    IF EXISTS (
        SELECT 1
        FROM sys.dm_xe_sessions dxs
        WHERE dxs.name = 'queries'
    )
    BEGIN
        ALTER EVENT SESSION queries ON SERVER STATE = STOP;
    END
    DROP EVENT SESSION queries ON SERVER;
END

CREATE EVENT SESSION queries ON SERVER
ADD EVENT sqlserver.sql_statement_starting
(
    ACTION
    (
        package0.collect_system_time
        --, package0.event_sequence
        , sqlserver.client_app_name
        , sqlserver.client_hostname
        --, sqlserver.database_name
        , sqlserver.plan_handle
        , sqlserver.sql_text
        , sqlserver.username
    )
    WHERE sqlserver.username = N'<some username>'
        AND sqlserver.database_id = 6 /* specific database */
        AND sqlserver.client_hostname <> '<my machine>'
)
, ADD EVENT sqlserver.error_reported
(
    ACTION
    (
        package0.collect_system_time
        , sqlserver.client_app_name
        , sqlserver.client_hostname
        , sqlserver.plan_handle
        , sqlserver.sql_text
        , sqlserver.username
    )
    WHERE sqlserver.username <> N'<some username>'
        /* fluff errors below */
        AND error <> 5703 /* Changed language setting to %.*ls. */
        AND error <> 5701 /* Changed database context to '%.*ls'. */
        AND error <> 2528 /* DBCC execution completed. If DBCC printed error messages, contact your system administrator. */
        AND error <> 7969 /* No active open transactions. */
        --AND error <> 14205/* (unknown) */
        AND error <> 4035 /* Processed %I64d pages for database '%ls', file '%ls' on file %d. */
        AND error <> 18265/* Log was backed up. Database: %s, creation date(time): %s(%s), first LSN: %s, last LSN: %s, number of dump devices: %d, device information: (%s). This is an informational message only. No user action is required. */
        AND error <> 3014 /* %hs successfully processed %I64d pages in %d.%03d seconds (%d.%03d MB/sec). */
        AND error <> 14570/* (Job outcome) */
        AND error <> 8153 /* Warning: Null value is eliminated by an aggregate or other SET operation. */

)
ADD TARGET package0.ring_buffer
(
    SET max_memory = 102400
)
WITH
(
    STARTUP_STATE=OFF
    , TRACK_CAUSALITY = ON
);
GO

IF EXISTS
(
    SELECT 1
    FROM sys.server_event_sessions dxs
    WHERE dxs.name = 'queries'
)
BEGIN
    ALTER EVENT SESSION queries ON SERVER STATE = START;
END

This is how I'm shredding the results:
/***************************

shred the Event Data into readable form

***************************/

DECLARE @xml XML;

SELECT TOP(1) @xml = CONVERT(xml, xet.target_data)
FROM sys.dm_xe_session_targets AS xet
    INNER JOIN sys.dm_xe_sessions AS xe ON (xe.address = xet.event_session_address)
WHERE xe.name = 'queries';

SELECT t.EventName
    , DateStamp = DATEADD(HOUR, -6, t.EventDateStamp)
    , DatabaseName = d.name
    , t.ErrorNumber
    , t.ErrorSeverity
    , t.ErrorState
    , t.ErrorMessage
    , t.CollectSystemTime
    , t.ClientAppName
    , t.ClientHostName
    , t.PlanHandle
    , t.SqlText
    , t.UserName
FROM (
        SELECT EventName = s.value('(@name)[1]','varchar(500)')
            , EventDateStamp = s.value('(@timestamp)[1]','datetime')
            , DatabaseID = s.value('(data[(@name)[1] eq "source_database_id"]/value/text())[1]','varchar(255)')
            , ErrorNumber = s.value('(data[(@name)[1] eq "error"]/value/text())[1]','int')
            , ErrorSeverity = s.value('(data[(@name)[1] eq "severity"]/value/text())[1]','int')
            , ErrorState = s.value('(data[(@name)[1] eq "state"]/value/text())[1]','int')
            , ErrorMessage = s.value('(data[(@name)[1] eq "message"]/value/text())[1]','varchar(255)')
            , CollectSystemTime = s.value('(action[(@name)[1] eq "collect_system_time"]/text/text())[1]','varchar(255)')
            , ClientAppName = s.value('(action[(@name)[1] eq "client_app_name"]/value/text())[1]','varchar(255)')
            , ClientHostName = s.value('(action[(@name)[1] eq "client_hostname"]/value/text())[1]','varchar(255)')
            , PlanHandle = CONVERT(xml, s.value('(action[(@name)[1] eq "plan_handle"]/value/text())[1]','varchar(255)')).value('(plan/@handle)[1]', 'varchar(255)')
            , SqlText = s.value('(action[(@name)[1] eq "sql_text"]/value/text())[1]','nvarchar(max)')
            , UserName = s.value('(action[(@name)[1] eq "username"]/value/text())[1]','varchar(128)')
        FROM @xml.nodes('/RingBufferTarget/event') AS xm(s)
    ) t
    LEFT JOIN sys.databases d ON t.DatabaseID = d.database_id
ORDER BY t.UserName
    , t.EventDateStamp;

A: Thanks to @Tom V for identifying this blog post that identifies the need for a temporary table.
Adapting the ideas in the blog post, this now works very quickly:
/***************************

shred the Event Data into readable form

***************************/

DECLARE @xml XML;

SELECT TOP(1) @xml = CONVERT(xml, xet.target_data)
FROM sys.dm_xe_session_targets AS xet
    INNER JOIN sys.dm_xe_sessions AS xe ON (xe.address = xet.event_session_address)
WHERE xe.name = 'queries';

IF OBJECT_ID('tempdb..#xmlResults') IS NOT NULL
DROP TABLE #xmlResults;

CREATE TABLE #xmlResults
(
    RowNum INT NOT NULL
        PRIMARY KEY CLUSTERED
        IDENTITY(1,1)
    , xeXML XML NOT NULL
);

INSERT INTO #xmlResults (xeXML)
SELECT xm.s.query('.')
FROM @xml.nodes('/RingBufferTarget/event') AS xm(s)
OPTION (Optimize FOR (@xml = Null)); -- Useful for SQL 2008

SELECT *
FROM #xmlResults

SELECT t.EventName
    , DateStamp = DATEADD(HOUR, -6, t.EventDateStamp)
    , DatabaseName = d.name
    , t.ErrorNumber
    , t.ErrorSeverity
    , t.ErrorState
    , t.ErrorMessage
    , t.CollectSystemTime
    , t.ClientAppName
    , t.ClientHostName
    , t.PlanHandle
    , t.SqlText
    , t.UserName
FROM (
        SELECT EventName =          xeXML.value('(event/@name)[1]','varchar(500)')
            , EventDateStamp =      xeXML.value('(event/@timestamp)[1]','datetime')
            , DatabaseID =          xeXML.value('(event/data[(@name)[1] eq "source_database_id"]/value/text())[1]','varchar(255)')
            , ErrorNumber =         xeXML.value('(event/data[(@name)[1] eq "error"]/value/text())[1]','varchar(255)')
            , ErrorSeverity =       xeXML.value('(event/data[(@name)[1] eq "severity"]/value/text())[1]','varchar(255)')
            , ErrorState =          xeXML.value('(event/data[(@name)[1] eq "state"]/value/text())[1]','varchar(255)')
            , ErrorMessage =        xeXML.value('(event/data[(@name)[1] eq "message"]/value/text())[1]','varchar(255)')
            , CollectSystemTime =   xeXML.value('(event/action[(@name)[1] eq "collect_system_time"]/text/text())[1]','varchar(255)')
            , ClientAppName =       xeXML.value('(event/action[(@name)[1] eq "client_app_name"]/value/text())[1]','varchar(255)')
            , ClientHostName =      xeXML.value('(event/action[(@name)[1] eq "client_hostname"]/value/text())[1]','varchar(255)')
            , PlanHandle = CONVERT(xml, xeXML.value('(event/action[(@name)[1] eq "plan_handle"]/value/text())[1]','varchar(255)')).value('(plan/@handle)[1]', 'varchar(255)')
            , SqlText =             xeXML.value('(event/action[(@name)[1] eq "sql_text"]/value/text())[1]','nvarchar(max)')
            , UserName =            xeXML.value('(event/action[(@name)[1] eq "username"]/value/text())[1]','varchar(128)')
        FROM #xmlResults xm
    ) t
    LEFT JOIN sys.databases d ON t.DatabaseID = d.database_id
ORDER BY t.UserName
    , t.EventDateStamp;


text:
Q: Parse.com security : Access object of another app if you know the objectId Is it possible to get data of an object/user on Parse.com, if the objectId of the ParseObject is known? I want to know about it as a security concern, if it is possible for some other app to access objects from my app if the objectId is known?

A: It doesn't matter what you have, if you're not on the ACL, you can't pull the data.  Make sure you're setting your ACLs up properly to protect your data.  Parse's docs are pretty decent in this regard:
https://parse.com/docs/ios_guide#security-recommendations/iOS
If you don't have any ACLs setup then everything defaults to Public Read/Write.  This means YES.  Another client would need access to your parse keys, but if they were able to find this, they would be able to access anything that isn't protected.


text:
Q: How to remove text from a list box I am trying to make an app in Visual Basic that allows an user to type in text and add it to the list as well as remove items from the list. My problem so far is that I can't remove the items, I can add them, just not remove them. My code is as follows:
Public Class Form1
Public Listed As String
Private Sub btnAdd_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)                        Handles btnAdd.Click
    Dim Prompt As String = "Enter Items To Add Here"
    Listed = InputBox(Prompt) 'Listed is the text from the input box
    lstBox.Items.Add(Listed).ToString() 'lstBox is ListBox1

End Sub

Private Sub btnRemove_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)             Handles btnRemove.Click
    With lstBox
        .SelectedItem.Remove(Listed)
    End With
End Sub
End Class

A: ListBox items do not have a Remove method. You should use the Remove method of the ListBox's Items collection.
lstBox.Items.Remove(lstBox.SelectedItem) ' Removes the currently selected item from lstBox

A: Private Sub btnRemove_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)               Handles btnRemove.Click
    With lstBox
        .Items.Remove(lstBox.SelectedItem)
      '/.Items.Remove(lstbx.SelectedItems)
    End With
End Sub


text:
Q: Post Monarch Trade? What kind of trade goods from dwarven caravans can I expect if I become a capital? Will they send me steel (or at least steel goods)? How about gold, silver, etc.? Silk, clay? I assume the wont send me stone, except as blocks.

A: Only one of my forts ever became a Mountainhome with a King, and since then I've avoided this honor like the plague: the dwarven caravan dropped to near-elven levels of (lack of) goods. The other two caravans were unaffected, but the dwarven one dropped to only 2 wagons from 5-6, and started bringing utterly useless goods.
Guessing in the dark, I presume your issue is that you would like the caravan to bring certain items? Because that's what trade agreements are for. You can order bars and stones, with your chosen level of priority, and the next caravan will bring some... at an overprice, which starts at 110-130%, for priority 1, and goes up to 200-220% for topmost priority.
Some things to keep in mind when ordering goods:

*

*the level of priority seems to translate directly into the number of brought items: order silver bars with priority 2? You get 2 silver bars. Especially with bars, you might be better off gambling on standard caravan autogeneration (or setting traps and mining goblinite).
It's pretty good to use on stone, which you'd normally not get (except clay boulders), and it absolutely shines on leather and cloth: these are counted by the bin, not by the item; ordering every type of leather at priority 1 will result in merchants bringing a bin of 10 hides for each type, which translates into > 250 tanned hides, at relatively small overpricing - a skin which used to cost 6☼ now costs 7☼, big deal.

*overpricing stacks. If you order, say, both iron bars and iron anvils, the 3 bars used to make the anvil get overpriced, and then the anvil itself gets overpriced. I made the mistake of ordering both, and ended up with a ~250% price hike, for priority 2 bars and priority 1 anvil.

A: Having a monarch and/or being the capital currently has no effect on trade.
The goods available to your civilization are determined at World Gen, and (as of now), those materials do not change over the course of play.


text:
Q: Error in default function template arguments when trying to convert C++11 code to C++03 I am trying to convert C++11 code to C++03 and stuck on a default template argument.
#include <type_traits>
#include <boost/utility/enable_if.hpp>
#include <boost/type_traits/is_const.hpp>
#include <boost/type_traits/conditional.hpp>
#include <boost/spirit/home/support/string_traits.hpp>

template<bool B, class T = void>
struct enable_if {};

template<class T>
struct enable_if<true, T> { typedef T type; };

template<typename T>
struct is_char
{
    typedef typename  enable_if<sizeof (T) == sizeof (char)>::type eif;
};

template<bool B, class T, class F>
struct conditional { typedef T type; };

template<class T, class F>
struct conditional<false, T, F> { typedef F type; };

template <typename ObjType,
        typename PtrType,
        typename CharType =
            typename conditional<boost::is_const<PtrType>::value,
                                      const typename ObjType::char_type,
                                      typename ObjType::char_type>::type,
        typename is_char<PtrType>::type >
CharType* char_ptr_cast(PtrType* p)
{ return reinterpret_cast<CharType*>(p); }

int main ()
{}

I am getting following error:
> /usr/lib/gcc/x86_64-redhat-linux/4.4.7/../../../../include/c++/4.4.7/c++0x_warning.h:31:2:
> error: #error This file requires compiler and library support for the
> upcoming ISO C++ standard, C++0x. This support is currently
> experimental, and must be enabled with the -std=c++0x or -std=gnu++0x
> compiler options.
>
> test.cc:35: error: no default argument for anonymous
>
> **default template arguments may not be used in function templates without -std=c++0x or -std=gnu++0x**

Could you please help me to resolve these errors?

A: Default template arguments for function templates were added in C++11. If you can't use C++11, or your compiler doesn't support it properly, you can't define typename CharType = /* whatever */. The way towards C++03 compliance without retyping that long meta-function is to refactor CharType into its own trait, and use that.
template<typename ObjType, typename PtrType>
struct CharType {
    typedef typename conditional<boost::is_const<PtrType>::value,
                                 const typename ObjType::char_type,
                                 typename ObjType::char_type>::type
    type;
};

template <typename ObjType typename PtrType>
typename CharType<ObjType, PtrType>::type* char_ptr_cast(PtrType* p)
{ return reinterpret_cast<typename CharType<ObjType, PtrType>::type*>(p); }

Also, the <type_traits> header is a C++11 only header. Since you hit a #error directive following a failed standard's version check in the standard library, that is the most likely culprit. You cannot include it.


text:
Q: Running variance when time window is not constant I am trying to calculate a moving variance with a window of, let's say  4 years, for each one of the names A, B and C. The data is weekly:
> head(data1, 17)
         date name       value
1  1985-01-01    A -0.44008233
2  1985-01-01    B          NA #Observe that there are some NA's
3  1985-01-01    C  0.38682496
4  1985-01-08    A  0.41806540
5  1985-01-08    B -0.05460831
6  1985-01-08    C -0.52051435
7  1985-01-15    A  1.25769395
8  1985-01-15    B  0.80272053
9  1985-01-15    C -0.34501742
10 1985-01-22    A -0.43401839
11 1985-01-22    B  0.91113966
12 1985-01-22    C  1.07131717
13 1985-01-29    A -1.55395857
14 1985-01-29    B -0.43281709
15 1985-01-29    C  0.98034779
16 1985-02-05    A  1.70557396
17 1985-02-05    B  0.44688788

My approach so far is to dcast the data and then run rollapply() (zoo) column wise with a moving window of 192 = 4*12*4:
v <- dcast(data1, date ~ name, value.var = "value")
var <- rollapply(v[-1], width=4*12*4, var, fill=NA, by.column = T)
var <- cbind(v$date, var)
var[,1] <- as.Date(var[,1])

However, I realized that for some months I have four observations (eg. 7, 14, 21, 28 February) and for some I have five weekly observations (eg.1, 8, 15, 22 and 29 of January), so using a window of 4 years * 12 months * 4 weeks observations is not correct. I was thinking to add these extra observations on the time window (width), but I am not sure how (or if it is even possible), since these change depending on how many 5-weeks-per-month and how many 4-weeks-per-month observations there are inside the time window.
Additionally, I would like to have a NA when there are NA observations within the moving time window (this is handled automatically by var() anyway I think) and also I would like to ignore zero observations. For that I was thinking I could remove the zeroes before running the running variance function and then somehow put them back in in the end. So you can ignore that part, unless, of course, you have some good idea to do it in one step.
Sample data:
set.seed(486)
date <- rep(seq(as.Date("1985-01-01"), as.Date("2010-01-1"), by="weeks"), each=3)
N <- length(date)
name <- c("A","B","C")
value <- rnorm(N)
i<-which(value %in% sample(value, 25)) ;i
j<-which(value %in% sample(value, 150)) ;j
value[i] <- NA
value[j] <- 0
data1 <- data.frame(date, name, value)

A: I don't think that you should your rolling window should coincide of the number of weeks in your data. It is just a window over data to smooth it. One idea is to do the something with 2 windows and take the average value:
library(data.table)
library(zoo)
setDT(data1)[,var := {
           v1 <- rollapplyr(value,width=4*12*4, var, fill=N)
           v2 <- rollapplyr(value,width=4*12*5, var, fill=N)
           (v1+v2)/2},  name]

PS: Here I am using data.table because it is suitable for split(per group) and rebind operations.
Edit
You can also transform you weekly data to a daily one then you can calculate more accurate a roll in this basis. The idea is to create a daily index and merge it with your original data. This will create a new data.table with missing values. You replace the missing values with first non missing values using na.locf.
library(data.table)
library(zoo)
ID <-
data.table(
  date = seq(as.Date("1985-01-01"), as.Date("2010-01-1"), by="days"))
setkey(ID,date)

setDT(data1)[,date:=as.Date(date)][,
        {
          merge(ID,.SD,all.x=TRUE)[,value := na.locf(value)]
        },

        name]

A: 4 years has 208 weeks plus 5 days so it is not evenly divisible into weeks.  If we use 209 weeks then we are only out by 2 days in 4 years so let us try that.
First convert data1 to "zoo" class splitting the data into separate columns according to the value of the 2nd column. z will have one column for each of A, B and C.  Then define a variance function which excludes zeros and use it with rollapplyr
library(zoo)
z <- read.zoo(data1, split = 2) # 1305 x 3
var0 <- function(x) var(x[x != 0])
r <- rollapplyr(z, 209, var0)

Leaving it as a zoo object may be sufficient but this would convert it to a 4 column data frame with columns Index, A, B and C:
fortify.zoo(r)


text:
Q: bootstrap one page theme not working with embed video while full screen using iframe I have a one page bootstrap theme, problem is that, I embed vimeo video when I click full screen button then screen going to full but not whole screen, this let some right side

A: I think this is not an issue with Bootstrap (or the theme), but with how you embed the video from Vimeo.
By default Vimeo doesn't allow fullscreen (this due browser limitations in Webkit and Mozilla).
To fix this, use the following embed code:
<iframe src="//player.vimeo.com/video/VIDEO_ID" width="WIDTH" height="HEIGHT" frameborder="0" webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe>

source: https://developer.vimeo.com/player/embedding


text:
Q: Distribution random variable $W=\sum_{k=1}^{\infty}X_k/2^k$ $X_1$ $X_2$,... are independent random variables with: $$P(X_k = 0) = P(X_k = 1) = 1/2$$ for each $k=1,2,3,...$ What is the distribution random variable:
$$W = \sum_{k=1}^{\infty}\frac{X_k}{2^k}.$$
I started with:
$$P(W \in (0,1))=?,\quad P(W \in (1/2,1))=?,\quad \ldots\quad  P(W\in (1/2^k ,1))=?$$
And then I need to compute: $$P(W \le 1)=?, \quad P(W \le 1/2)=?,\quad \ldots \quad P(W \le 1/2^k)=?$$
How I compute this probabilities?
Thank you very much!

A: First of all note that: $$\sum_{k=1}^{\infty}\frac{1}{2^k}=1$$
So:$$W=\sum_{k=1}^{\infty}\frac{X_k}{2^k}\leq1$$
and then:
$$ P(0\leq W\leq1)=1$$
Now take $X_1$ out of the sum:
$$W=\frac{X_1}{2}+\sum_{k=2}^{\infty}\frac{X_k}{2^k}$$
The sum is now $\leq1/2$ so:
$$ P(0\leq W\leq1/2)=P(X_1=0)=1/2$$
$$ P(1/2\leq W\leq1)=P(X_1=1)=1/2$$
Proceeding in this way you can show that:
$$ P(k/2^n\leq W\leq(k+1)/2^n)=1/2^n$$
for every $0\leq k\leq2^n$.
If you recall the uniform distribution $U(0,1)$ has the property that:
$$P(a\leq U\leq(a+b))=b$$
You have that for every interval this holds also for $W$ so $$W\sim U(0,1)$$


text:
Q: Pyarrow: read stream into pandas dataframe high memory consumption I would like to to first write a stream into an arrow file and then later read it back into a pandas dataframe, with as little memory overhead as posible.
Writing data in batches works perfectly fine:
import pyarrow as pa
import pandas as pd
import random

data = [pa.array([random.randint(0, 1000)]), pa.array(['B']), pa.array(['C'])]
columns = ['A','B','C']
batch = pa.RecordBatch.from_arrays(data, columns)

with pa.OSFile('test.arrow', 'wb') as f:
    with pa.RecordBatchStreamWriter(f, batch.schema) as writer:
        for i in range(1000 * 1000):
            data = [pa.array([random.randint(0, 1000)]), pa.array(['B']), pa.array(['C'])]
            batch = pa.RecordBatch.from_arrays(data, columns)
            writer.write_batch(batch)

Writing 1 million rows as above is fast and uses about 40MB memory during the entire write. This is perfectly fine.
However reading back is not fine since the memory consumption goes up to 2GB, before producing the final dataframe which is about 118MB.
I tried this:
with pa.input_stream('test.arrow') as f:
    reader = pa.BufferReader(f.read())
    table = pa.ipc.open_stream(reader).read_all()
    df1 = table.to_pandas(split_blocks=True, self_destruct=True)

and this, with the same memory overhead:
with open('test.arrow', 'rb') as f:
   df1 = pa.ipc.open_stream(f).read_pandas()

Dataframe size:
print(df1.info(memory_usage='deep'))

Data columns (total 3 columns):
 #   Column  Non-Null Count    Dtype
---  ------  --------------    -----
 0   A       1000000 non-null  int64
 1   B       1000000 non-null  object
 2   C       1000000 non-null  object
dtypes: int64(1), object(2)
memory usage: 118.3 MB
None

What I would need is either to fix the memory usage with pyarrow or a suggestion which other format I could use to write data into incrementally, then read all of it into a pandas dataframe and without too much memory overhead.

A: Your example is using many RecordBatches each of a single row. Such a RecordBatch has some overhead in addition to just the data (the schema, potential padding/alignment), and thus is not efficient for storing only a single row.
When reading the file with read_all() or read_pandas(), it first creates all those RecordBatches before converting them to a single Table. And then the overhead adds up, and this is what you are seeing.
The recommended size for a RecordBatch is of course dependent on the exact use case, but a typical size is 64k to 1M rows.

To see the effect of the padding to 64 bytes per array (https://arrow.apache.org/docs/format/Columnar.html#buffer-alignment-and-padding), let's check the total allocated bytes vs the actual bytes represented by the RecordBatch:
import pyarrow as pa

batch = pa.RecordBatch.from_arrays(
    [pa.array([1]), pa.array(['B']), pa.array(['C'])],
    ['A','B','C']
)

# The size of the data stored in the RecordBatch
# 8 for the integer (int64), 9 for each string array (8 for the len-2 offset array (int32), 1 for the single string byte)
>>> batch.nbytes
26

# The size of the data actually being allocated by Arrow
# (5*64 for 5 buffers padded to 64 bytes)
>>> pa.total_allocated_bytes()
320

So you can see that just this padding already gives a big overhead for a tiny RecordBatch


text:
Q: VB user controls not resizing in windows 8 I'm updating a vb6 application to run in windows 8, and one of the issues is user control windows not resizing (via the window edge drag handles). It works fine under other OSes.
The same issue plagues the main project window.
The elements of the window are controlled in this function, but the window itself doesn't respond to resizing.
Private Sub UserControl_Resize()
If g_ShuttingDown Then Exit Sub
' Test for zero size
If ScaleWidth = 0 Or ScaleHeight = 0 Then Exit Sub

' Min size
'If ScaleWidth < iMIN_FORM_WIDTH Then UserControl.Width = iMIN_FORM_WIDTH
'If ScaleWidth < iMIN_FORM_HEIGHT Then UserControl.Height = iMIN_FORM_HEIGHT

' Form dimensions
Dim x, y, w, H As Long
x = ScaleLeft
y = ScaleTop
w = ScaleWidth
H = ScaleHeight

picTitleBar.Move 0, 0, w - 30, 240
imgTitleBar.Move 0, 0, picTitleBar.Width, 240
lblCaption.Move 45, 15
imgClose.Move picTitleBar.Width - imgClose.Width - 60, 60

chkVerbose.Move 15, picTitleBar.Top + picTitleBar.Height
cmdClear.Move chkVerbose.Left + chkVerbose.Width, chkVerbose.Top
chkPause.Move cmdClear.Left + cmdClear.Width, chkVerbose.Top

Messages.Move 15, chkVerbose.Top + chkVerbose.Height, w - 30, H - (chkVerbose.Top + chkVerbose.Height)

End Sub
Any ideas how I might get these windows to respond to the resize event properly?

A: maybe u need download new fixed dll for vb in win 8 or need access permision for vb6.exe to allow all actions .
and maybe u sholude be disabled win 8 theme to vb work good .
i have more problems with vb6in win8 but when i disabled themes in win 7 or win 8 many of my problems sloved .


text:
Q: Django Unique constraint failed for user field in model I've been trying to figure out how to save the user's id with in a model through a form, I keep getting UNIQUE constraint failed: vapp_numobject.user_id.
Here's my model:
class NumObject(models.Model):

    title= models.CharField(max_length=50)
    number= models.IntegerField()
    ident= models.IntegerField(blank=True, null=True)
    user= models.ForeignKey(User, on_delete= models.CASCADE)

    def __str__(self):
        return self.title

    def save(self, *args, **kwargs):
        super(NumObject,self).save(*args,**kwargs)

    def get_absolute_url(self):
        return reverse('posts:detail', kwargs={'id': self.id})

my forms.py:
class NumForm(forms.ModelForm):

    class Meta:
        model = NumObject
        fields = [
        'title',
        'number',
        ]

and my view that saves the form:
@login_required
def post_createnum(request):
    form= NumForm(request.POST or None, request.FILES or None)

    if form.is_valid():
        instance = form.save(commit=False)
        instance.user = request.user
        instance.save()
        return HttpResponseRedirect('/')

    context= {
        'form': form,
    }
    return render(request, 'num_form.html',context)

I'd like to be a able to sort a list of the NumObjects by user id, and I'm not sure if there's a better method in Django.  Any help is appreciated!
edit: I don't think it's quite the same as the other solution, since I'm trying to attach a user id to an object for querying later, instead of editing a users' id and saving it


text:
Q: php code to get listbox selected value in variable for where clause below is my select tag code..I need to get selected input in temp variable.
and use this variable to search.
FOR EX-
<select>
  <option value="volvo">Volvo</option>
  <option value="saab">Saab</option>
  <option value="vw">VW</option>
  <option value="audi" selected>Audi</option>
</select>

Now I selected Saab from listbox. then get this value in variable in temp
and use this temp variable in search query.
<?php
$temp = "Saab";
$book_no2 = $temp;
$receipt = $database->getRows("SELECT receipt_no FROM scheme_master WHERE book_no2 = :book_no2", array(':book_no2'=>$book_no2));
?>

<select name="book" onChange="showUser(this.value)">
<?php foreach ($book as $load_book){ ?>
<option  value=""></option>
    <option  value="<?php echo $load_book["book_no"]; ?>"><?php echo $load_book["book_no"]; ?></option>
<?php }?>
</select>

<?php
$book_no2 = $load_book["book_no"];
$receipt = $database->getRows("SELECT receipt_no FROM scheme_master WHERE book_no2 = :book_no2", array(':book_no2'=>$book_no2));
?>

A: You should you form and get the selected book from global $_POST variable, but make sure you properly escaped all the variables coming from the client side (e.g. using mysql_real_escape_string PHP function).
    <?php
    $book_no2 = mysql_real_escape_string($_POST['book']);
    $receipt = $database->getRows("SELECT receipt_no FROM scheme_master WHERE book_no2 = :book_no2", array(':book_no2'=>$book_no2));

?>
<form method="POST">
    <select name="book" onChange="showUser(this.value)">
        <?php foreach ($book as $load_book){ ?>
            <option  value=""></option>
            <option  value="<?php echo $load_book["book_no"]; ?>"<?php if ($load_book["book_no"] == $temp):?> selected="selected"<?php endif?>><?php echo $load_book["book_no"]; ?></option>
        <?php }?>
    </select>
    <input type="submit" value="Send" />
</form>

A: Plz see ...this will resolve my problem....
<select  name="book"  onChange="showUser(this.value)">
    <option value="<?php if(isset($_GET['edit'])){ echo $data['book']; }?>"><?php if(isset($_GET['edit'])){echo $data['book'];}?></option>
    <?php foreach ($book as $load_book){ ?>
    <option  value=""></option>
        <option  value="<?php echo $load_book["book_no"]; ?>"><?php echo $load_book["book_no"]; ?></option>
    <?php }?>
    </select>

    <?php
    $book_no2 = $load_book["book_no"];
    $receipt = $database->getRows("SELECT DISTINCT receipt_no FROM scheme_master WHERE book_no2 = :book_no2", array(':book_no2'=>$book_no2));
    ?>

A: Make your first file
<form action="second page" method="post"
 <select name="car">
  <option value="volvo">Volvo</option>
  <option value="saab">Saab</option>
  <option value="vw">VW</option>
  <option value="audi" selected>Audi</    option>
 </select>
<input type="submit">
</form>

Then pass this to your temp var
$temp=$_POST[`car`];


text:
Q: Screen sessions that run on boot immediately die I have a server running CentOS 7 (for compatibility reasons), set to run a script on boot that contains a bunch of commands to dispatch in screen sessions. So systemd runs the script, and the script runs a few screen -dm <process> commands. I know I should be using systemd units for these processes, but I personally like having one single file that runs on boot, because it's easier to edit that than to be managing multiple systemd units. Additionally, one of them is a Minecraft server, which runs its own "shell", and in order to properly save the server's world you have to end the process gracefully from within the console.
This worked fine until about a week ago. For some reason, every single screen session immediately exits with the status "Dead ???" and I have to use screen -wipe and then run the script myself. Once I do that, the screens work fine.
I know this is a very odd scenario, but I feel like there's something stupid I'm doing or did that caused this. Does anybody have any insight as to why this might happen so suddenly? Thank you for your consideration.


text:
Q: Python - What am I doing wrong with my generators? I'm trying to yield a series of generators to another generator via helper functions. I guess I'm trying to mimic flat_map() like in RxPy. Is there a way to accomplish this? I am getting an output that is printing the generators, not the items yielded by the generators.
class User(object):
    def __init__(self, id, name):
        self.id = id
        self.name = name

    def __str__(self):
        return "{0}-{1}".format(self.id, self.name)

users = [
    User(0,"Hero"),
    User(1,"Dunn"),
    User(2,"Sue"),
    User(3,"Chi"),
    User(4,"Thor"),
    User(5,"Clive"),
    User(6,"Hicks"),
    User(7,"Devin"),
    User(8,"Kate"),
    User(9,"Klein"),
]

friendships = [
    (0,1),
    (0,2),
    (1,2),
    (1,3),
    (2,3),
    (3,4),
    (4,5),
    (5,6),
    (5,7),
    (6,8),
    (7,8),
    (8,9)
]

def user_for_id(user_id):
    for user in users:
        if user.id == user_id:
            yield user

def friends_of(user):
    for friendship in friendships:
        if friendship[0] == user.id or friendship[1] == user.id:
            for other_user_id in friendship:
                if other_user_id != user.id:
                    yield user_for_id(other_user_id)

for friend in friends_of(users[3]):
    print(friend)

OUTPUT:
<generator object user_for_id at 0x7f2d33ee48e0>
<generator object user_for_id at 0x7f2d33ee4990>
<generator object user_for_id at 0x7f2d33ee4938>

A: Your chaining generators together and only iterating over one of them. If you want to get the actually friends, you'll need to iterate over friend, even if it's a single value. Generators are NOT iterators. Because your friends_of function returns a generator expression, you either need to iterate over it or pass it to next.
>>> for friend in friends_of(users[3]):
...     for obj in friend:
...             print(obj.name)
...
Dunn
Sue
Thor

You can get around the second loop by passing the generator to next() and printing the resulting name property. I should note that this code is NOT the same as the code I previously mentioned, because this only looks at the first value returned by second generator expression.
>>> for friend in friends_of(users[3]):
...     print(next(friend).name)
...
Dunn
Sue
Thor

If you've having difficulty understanding generators I would highly suggest looking into the materials published on david beazley's website.
http://dabeaz.com/generators/index.html - Generator tricks for system programmers
http://dabeaz.com/generators-uk/index.html - Generator tricks for system programmers v2
http://dabeaz.com/finalgenerator/index.html - Generators the final frontier
His videos and slides will give you a much better idea as to how generators work in python.
As somebody else explained, in Python 3 you can use "yield from":
def friends_of(user):
    for friendship in friendships:
        if friendship[0] == user.id or friendship[1] == user.id:
            for other_user_id in friendship:
                if other_user_id != user.id:
                    yield from user_for_id(other_user_id)

for friend in friends_of(users[3]):
    print(friend.name)

The deep nesting of the previous block of code is a bad sign though. It should be rewritten so that it is more readable.


text:
Q: Sessions in struts2 application I have created a web application in which I need to maintain the session
if a user session is there, and then and only then will it allow the user to see the jsp.
I have worked with jsp servlets before, but I'm new to struts2.
Here I am setting username in my action class:
Revised Code
private HttpSession session;

public void setSession(HttpSession session) {
    // TODO Auto-generated method stub0
    this.session = session;
}

public HttpSession getSession() {
    return session;
}

public String getLoginStatus(){
    session = request.getSession();
    session.setAttribute("userName", loginBean.getUsername());
    return SUCCESS;
}

Now, when I am redirected to next page after an action, it shows the session value once. After that, on every page, I am finding null values in session.
<%
    String userName = (String)session.getAttribute("userName");
    System.out.println(userName);

    if(userName == null || userName.equals("") ){
        response.sendRedirect("login.jsp");
    }

%>

I read somewhere that the scope of an action class session is limited to one page - how could I solve this problem?
Any example will be very helpful to me.

A: To maintain a session use SessionAware interface  in your action class and implement int
public void setSession(Map m) it will take the attribute as a key value pair in map
which can be be access from any where just buy retrieving the key.
for example Action class
import org.apache.struts2.interceptor.SessionAware;

import com.opensymphony.xwork2.ActionSupport;

public class LogingEx extends ActionSupport implements SessionAware{
    private static final long serialVersionUID = 1L;

    private String stuname,stuage,country;
    private int stumarks;
    Map m;

    public String getStuname() {
        return stuname;
    }
    public void setStuname(String stuname) {
        this.stuname = stuname;
    }

    public String getStuage() {
        return stuage;
    }
    public void setStuage(String stuage) {
        this.stuage = stuage;
    }

    public String getCountry() {
        return country;
    }
    public void setCountry(String country) {
        this.country = country;
    }

    public int getStumarks() {
        return stumarks;
    }
    public void setStumarks(int stumarks) {
        this.stumarks = stumarks;
    }

    public void setSession(Map m)
    {
        this.m=m;
    }

    public String execute()
    {
        m.put("a",stuname);
        m.put("b", stuage);
        m.put("c",stumarks);
        m.put("d",country);

        return SUCCESS;
    }

}

SOURCE: http://www.java4s.com/struts-tutorials/example-on-struts-2-sessionaware-interface/

A: There are a few problems with the code you currently have.

*

*You should use an Interceptor to enforce that the user is logged in, rather than trying to enforce it in the JSP. JSP should only be for presentation, not for flow control.

*You should avoid scriptlets (blocks of code) in JSP. That was deprecated a really long time ago and is widely considered to be a very poor practice in an MVC application.

*You can access session values in your JSP directly. You do not need to implement the SessionAware interface in your action unless you need access to the session inside of the action itself.

*You should redirect the user to a login action, not directly to a JSP page, otherwise you are bypassing the Struts2 framework and losing out on the benefits of using the framework.

Login Example
Below is some example code for creating a basic login system using the Struts2 framework.
Login Required
This part is optional, but in general, not all pages in a web application will require the user to be logged in. Therefore, let's create an interface called LoginRequired. Any action that implements this marker interface will redirect to the login page if the user is not already logged in.
Note: You can use an annotation instead, if you prefer, but for this example I will use the interface.
public interface LoginRequired {}

The Interceptor
The interceptor will handle forcing the user to login for any requested action which implements the LoginRequired interface.
public class LoginInterceptor extends AbstractInterceptor {
    @Override
    public String intercept(final ActionInvocation invocation) throws Exception {
        Map<String, Object> session = ActionContext.getContext().getSession();

        // sb: feel free to change this to some other type of an object which
        // represents that the user is logged in. for this example, I am using
        // an integer which would probably represent a primary key that I would
        // look the user up by with Hibernate or some other mechanism.
        Integer userId = (Integer) session.get("userId");

        // sb: if the user is already signed-in, then let the request through.
        if (userId != null) {
            return invocation.invoke();
        }

        Object action = invocation.getAction();

        // sb: if the action doesn't require sign-in, then let it through.
        if (!(action instanceof LoginRequired)) {
            return invocation.invoke();
        }

        // sb: if this request does require login and the current action is
        // not the login action, then redirect the user
        if (!(action instanceof LoginAction)) {
            return "loginRedirect";
        }

        // sb: they either requested the login page or are submitting their
        // login now, let it through
        return invocation.invoke();
    }
}

You will also need a LoginAction which displays and processes the login page and a LogoutAction which invalidates or clears the session.
The Configuration
You will need to add the interceptor to your stack and also create a global result mapping for "loginRedirect".
<interceptors>
    <interceptor name="login" class="your.package.LoginInterceptor"/>

    <!-- sb: you need to configure all of your interceptors here. i'm only
         listing the one we created for this example. -->
    <interceptor-stack name="yourStack">
        ...
        <interceptor-ref name="login"/>
        ...
    </interceptor-stack>
</interceptors>

<global-results>
    <!-- sb: make this the path to your login action.
         this could also be a redirectAction type. -->
    <result name="loginRedirect" type="redirect">/login</url>
</global-results>

A: I find no reason to use this kind of Map to authorize user. If your requirement is only validate the user against session then I would recommend to use Filter than some map in some class, the problem with this kind of map is to remove the session objects once session is invalidated, of course you can use HttpSessionListener to make it work but I guess it's best to validate via Filter than Map.
Apart from it you can take a look at many security framework (like Apache Shiro) to make your task simpler and more robust.

A: Has your Action class already implemented the SessionAware interface?
EDIT:
Try this(It's a struts2 style solution):
public class anAction implements SessionAware{
    private Map<String, Object> session;
    public Map<String, Object> getSession() {
         return session;
    }
    public void setSession(Map<String, Object> session) {
         this.session = session;
    }
    public String getLoginStatus(){
         session.put("userName", "test");  //Hard code here for testing.
         return SUCCESS;
    }
}

Then use your jsp code to get the userName on page. I've tested this approach on my machine and it works.
EDIT2:
BTW, such login check can be done easily and elegant with "Interceptor" provided by Struts2 Framework.

A: SessionAware implemention not required.
public class LoginAction extends Actionsupport
{
  private Map<String, Object> session;
  //Getter and Setter method
   public String execute() throws Exception {
      session=ActionContext.getContext().getSession();
      session.put("userName", "test");
     return super.execute();
   }
}

A: Following journaldev article has more detail in the same line of Steven response above http://www.journaldev.com/2210/struts-2-interceptor-tutorial-with-custom-authentication-interceptor-example


text:
Q: Custom logic using Laravel with BackPack I would like to add a new entity in my DB and I have stuck thinking how should it be implemented in context of model relations and Laravel BackPack fields.
There was Actors and Directors models and they were using many-to-many relations with Movie model.
Now I would like to add Role entity as actor could be also a director in the same film. I created Persons model and bind it to Movie model like this (person_movie table with such fields: movie_id, person_id, role_id).
Questions:
1. What kind of relation could it be?
2. How could it be implemented in BackPack Laravel?
3. Are there any approved solutions?


text:
Q: Check if any element in list exists in a string Here is an example that I would like to print TRUE since Drug is in the string. If disease was in the string, I would like it to print TRUE as well. For all other cases I want to print FALSE
mystring =  "Drug   CID006338583    AC1O3UYX    Stitch  1.515E-3    1.000E0 4.989E-2    5.235E-1    4   63  PTGES,SLC15A1,KLK8,IL7R"
check_if_in_mystring = ['Drug', 'Disease']

if check_if_in_mystring in mystring:
    print("TRUE")
else:
    print("FALSE")

A: Your example is correct you can use 'in' operator on string, just add a loop on 'check_if_in_mystring' to iterate over every element you want to check, like below example.
mystring =  "Drug   CID006338583    AC1O3UYX    Stitch  1.515E-3    1.000E0 4.989E-2    5.235E-1    4   63  PTGES,SLC15A1,KLK8,IL7R"
check_if_in_mystring = ['Drug', 'Disease']

for element in check_if_in_mystring:
    if element in mystring:
        print("TRUE for {}".format(element))
    else:
        print("FALSE for {}".format(element))

output:
TRUE for Drug
FALSE for Disease

A: This snippet will detect if any one of check_if_in_mystring is in mystring:
any(word in mystring for word in check_if_in_mystring)

For the exact behavior from the question:
print(str(any(word in mystring for word in check_if_in_mystring)).upper())

A: Try this:
>>> my_string = "Drug   CID006338583    AC1O3UYX    Stitch
1.515E-3    1.000E0 4.989E-2    5.235E-1    4   63  PTGES,SLC15A1,KLK8,IL7R"

>>> print("TRUE" if "Drug" in my_string or "Disease" in my_string else
"FALSE")

TRUE

>>> my_string = "Some other random string"

>>> print("TRUE" if "Drug" in my_string or "Disease" in my_string else
"FALSE")

FALSE

>>> my_string = "Has the word Disease"

>>> print("TRUE" if "Drug" in my_string or "Disease" in my_string else
"FALSE")

TRUE

strings support the in operator, so you can just check if Drug or Disease are in my_string.

A: converting string to list and checking in list can be one solution,
as solved below.
mystring =  "Drug   CID006338583    AC1O3UYX    Stitch  1.515E-3    1.000E0 4.989E-2    5.235E-1    4   63  PTGES,SLC15A1,KLK8,IL7R"
check_if_in_mystring = ['Drug', 'Disease']
mystring1 = mystring.split() #convertin string to list, seprated by white space
for item in check_if_in_mystring:
    if item in mystring1:
        print(item)
        print("TRUE")
    else:
        print(item)
        print("FALSE")

Output:printing work and its presence in mystring
Drug
TRUE
Disease
FALSE

A: Alex Taylor's on the right track, but the any clause can be greatly simplified:
>>> mystring =  "Drug   CID006338583    AC1O3UYX    Stitch  1.515E-3    1.000E0 4.989E-2    5.235E-1    4   63  PTGES,SLC15A1,KLK8,IL7R"
>>> check_if_in_mystring = ['Drug', 'Disease']
>>> any(word in mystring for word in check_if_in_mystring)
True
>>> mystring =  "Poodle   CID006338583    AC1O3UYX    Stitch  1.515E-3    1.000E0 4.989E-2    5.235E-1    4   63  PTGES,SLC15A1,KLK8,IL7R"
>>> any(word in mystring for word in check_if_in_mystring)
False

These approaches loop across the list of words in check_if_in_mystring, and any(...) returns True as soon as the first word in mystring expression is True. If the for word in check_if_in_mystring loop finishes without finding a True value, then any(...) returns False.

A: You may also use:
mystring.contains(anotherstring)


text:
Q: Using CSS to Moving Columns Based on Screen Width Here's a link to the page that's in development:
http://cybercacher.com/test/about-me/
If you scroll down to the very bottom you will see a list of links - there's 4 columns in the normal view.  When you make the screen smaller, it puts all of them into one column.
I do want it to put them into a single column on an iPhone, for example.  However, based on the screen size it should show them as 4 columns, then 2 columns, then 1 column.
Right now it's only showing as 4 columns or as 1 column, but it won't show like this:
I've tried playing around with the CSS to see how to do this but can't seem to figure it out.  I'd prefer to do this with just CSS if possible.  Any help would be greatly appreciated!

A: I see:
col-lg-3 col-md-3 col-sm-3

Try to use:
col-sm-6 col-md-3

instead.


text:
Q: Call an ASP.NET MVC application's URL from javascript I'm new to ASP.NET MVC. After reading many different examples I still can't get this done.
I have some JS scripts bundled and one out of the bundle (because I'm using a different main script per page)
(_Layout.cshtml)

@Scripts.Render("~/bundles/modernizr")
@Scripts.Render("~/bundles/jquery")
@Scripts.Render("~/bundles/datatables")
@RenderSection("scripts", required: false)

And in my view
(index.cshtml)

@section Scripts
{
    <script src="@Url.Content("~/Scripts/index.js")"></script>
}

In javascript code I am trying to call a specific URL of my application
(index.js)

$('#table').DataTable({
    ajax: '@Url.Action("List", "Documents")'
});

Of course in my application a controller is definend with the name DocumentsController and with a List method, returning the correct JSON.
Still it seems no-one is ever replacing my url

If I include my index.js in the bundle, nothing changes.
Where is the mistake?
Who and when is replacing that URL?
Thank you

A: You can't use Razor code inside a *.js file because they're served directly as static files and aren't processed by ASP.NET (nor *.ts files because they're transpiled to *.js at build-time).
What you can do instead is to render Razor-generated JavaScript in your View/Page and have your TypeScript or JavaScript expect that data to be available.
Like so:
Index.cshtml
<script type="text/javascript">
var scriptUrls = {
    listDocuments: '@Url.Action("List", "Documents")';
};
</script>

Index.ts (if using TypeScript)
interface PageUrls {
    readonly listDocuments: string;
};

declare var scriptUrls: PageUrls;

//

$('#table').DataTable({
    ajax: scriptUrls.listDocuments
});

Index.js
$('#table').DataTable({
    ajax: scriptUrls.listDocuments
});


text:
Q: MySQL 5.7: Query fica mais rápida com order by Estou fazendo alguns testes no banco de dados MySQL 5.7, e me deparei com uma situação que não consigo entender:
Quando faço a seguinte consulta:
select
*
from
    funcionario
where
    (data_admissao between '2020-01-01 23:59:59' and '2022-07-25 23:59:59')
    order by nome;

Quando executo sem "order by nome" a consulta executa em 6s, já com o "order by nome" a consulta executa em 86ms.
OBS:

*

*Não existe índice para a coluna "nome".

*A tabela utiliza Engine = InnoDB

*Executei o EXPLAIN, mas como é uma consulta simples, não trouxe nenhuma informação significativa:
1   SIMPLE  funcionario     ALL                 117432  0.01    Using where; Using filesort

*Fiz o mesmo teste no banco de dados MySQL 8, e não obteve nenhuma diferença com o "order by nome", utilizando a mesma base de dados, com a mesma estrutura.
Estou tentando entender a situação, pois quero migrar para o MySQL 8, e gostaria de saber se existe alguma configuração ou estrategia que faça o MySQL 5.7 ter uma diferença com o order by.


text:
Q: Django template var in Javascript Let's take a dictonary:
mydict = {
  'color': "blue",
  'brand': "Ford",
  'year': 1969
}

We pass this dict to our template, then, in the template, we have a select list with options according to our dictionary keys (color, brand, year).
Now, I want to change some text in my rendered template regarding the selected option.
So we have some Jquery that is getting the value of the selected option, like this:
$('#myselect').change(function() {
        var selected = $( "#myselect option:selected" ).text();
    });

Now that we have the selected text, I would like to use it as a key to display a value from our dictionary.
Something like this
$('#myselect').change(function() {
            var selected = $( "#myselect option:selected" ).text();
            $('#mytext').text('{{ mydict.selected }}');
        });

But I guess mixing Django var and JS var like this, is not going to work...
Any idea how I can do this ?

A: Based on Martins comment, here is what I did:
In the template:
<select id="myselect">
  <option value="color">color</option>
  <option value="brand" selected="">brand</option>
  <option value="year">year</option>
</select>

{% for key,value in mydict.items %}
  <small id="{{key}}" class="messages" style="display:none;">
    {{ value }}
  </small>
{% endfor %}

Then some JS:
$('#myselect').change(function() {
        var selected = $( "#myselect option:selected" ).text();
        $('.messages').hide();
        $('#' + selected).show();

    });


text:
Q: When Linear Search is better than Binary Search for unsorted array? And which sorting algorithm goes with Binary Search to sort the array first? I understand that an unsorted array needs to be sorted first before applying Binary Search. So consider time complexity comparison of a Sorting algorithm + Binary search vs Linear Search.

A: Binary search is better when total numbers of elements are < 10e6
Linear Search has O(n) complexity where as Binary search has O(logn).
10e6 = 7.


text:
Q: Is there a sign() function in xPath Is there a sign() function available in xPath? So that the following are all true:
sign(-2) == -1
sign(-1) == -1
sign( 0) ==  0
sign(+1) ==  1
sign(+2) ==  1

A: No, there isn't. The workaround depends on which version of XPath you are using.


text:
Q: Why does iptables restart cause connectivity timeout for about a minute? I have a centos 6.5 64bit router with 3 nics.
The box is configured to route 2 networks.
netA - eth1 [ about 10 clients ]
netB - eth2 [ about 100 clients ]
provider - eth0 [ fiber to isp ]
I have a custom script that initializes the firewall and also sets marks in mangle table for qos purposes.
The script initializes by flushing all rules in all tables.
The -F -X drill for filter nat mangle and then it begins to compose the rules.
I also have the nf_conntrack module loaded and my script does not unload it.
Note that I don't use the official rhel firewall scripts.
Everything works until I run the script for various reasons (modify certain qos requirements, filter certain users, ports etc whathaveyou).
At that time my ssh connection to the box freezes and i can't even ping it.
Of course there's no internet connectivity and my lan is frozen.
Funny thing the netA computers are only cut off for a few seconds but the netB lan looses connectivity for about a minute or two.
Then everything is back to normal.
Where do I start ?


text:
Q: How create a react app with a specific version using the npx command? I want to create a React app using the command
npx create-react-app my-app

But I want to make sure I can choose the React version.
I want a version that can't use hooks, so I want to force a React
version before 16.8 (in which hooks were released).
How or where do I find the version to use?
I have followed a tutorial that gave me a command like
npx create-react-app reactjs-app --scripts-version 1.1.5

How can I create an app with for example React version 16.7?
My goal is to get the latest version before which hooks were released.

A: According the documentation the syntax for npx is:
npx [options] <command>[@version] [command-arg]...

If you want react version 16.7 you have to find out which version of create-react-app installs react 16.7 because the version numbers are not the same. If I'm correct version 3.4.1 of create-react-app installs the latest version of react before they introduce hooks.
can simply run:
npx create-react-app@3.4.1 my-app

A: Some packages may use a different name for the package and the tool, causing some forms of the version specifier to fail when the plain command works:
$ npx uglifyjs --version
uglify-js 3.14.4

$ npx uglifyjs@3.10.0 --version
npm ERR! code ETARGET
npm ERR! notarget No matching version found for uglifyjs@3.10.0.
npm ERR! notarget In most cases you or one of your dependencies are requesting
npm ERR! notarget a package version that doesn't exist.
[..]
Install for [ 'uglifyjs@3.10.0' ] failed with code 1

In this case, using -p / --package, or specifying the package name instead, will allow npx to work as expected:
$ npx --package uglify-js@3.10.0 uglifyjs --version
npx: installed 1 in 0.631s
uglify-js 3.10.0

$ npx uglify-js@3.10.0 --version
npx: installed 1 in 0.524s
uglify-js 3.10.0
undefined

(nb: the first npx uglifyjs only works when inside a project that has had uglify-js added to the package.json file.)


text:
Q: Iterate through nested lists, replacing each instance of a string with a successive letter of the alphabet, beginning again from 'A' for each sublist I have a list with nested lists:
xlist = [[, , , , 'X', , 'X', 'X', , 'X', ,], ['X', , , 'X', , 'X', 'X', 'X',], [, , , 'X', , 'X', ,'X', , , , 'X',]]

I want to replace each occurrence of 'X' within a sublist with a letter of the alphabet, in order of occurrence, to end up with this:
alist = [[, , , , 'A', , 'B', 'C', , 'D', ,],['A', , , 'B', , 'C', 'D', 'E',], [, , , 'A', , 'B', ,'C', , , , 'D',]]

The empty values are important as the list matches another list with the same structure. There is only 1 layer of nested lists and all 'X' values are in sublists.
This has really stumped me so thank you for the help!

A: You can use next for that:
from string import ascii_uppercase

xlist = [['', '', '', '', 'X', '', 'X', 'X', '', 'X', '', ''], ['X', '', '', 'X', '', 'X', 'X', 'X', ''], ['', '', '', 'X', '', 'X', '','X', '', '', '', 'X', '']]

def fill_in_x(lst):
    letters = iter(ascii_uppercase)
    return [next(letters) if item == 'X' else item for item in lst]

output = map(fill_in_x, xlist)

for sublst in output:
    print(sublst)

# ['', '', '', '', 'A', '', 'B', 'C', '', 'D', '', '']
# ['A', '', '', 'B', '', 'C', 'D', 'E', '']
# ['', '', '', 'A', '', 'B', '', 'C', '', '', '', 'D', '']

A: I think something like this might do the job:
alphabet = "ABCDEFGHIJKLMNOPQRSTUVWYXZ"

for i, arr in enumerate(xlist):
    char_index = 0

    for j, char in enumerate(arr):
        if char == "X":
            xlist[i][j] = alphabet[char_index]
            char_index += 1

Or if you don't want to mutate the first list:
alphabet = "ABCDEFGHIJKLMNOPQRSTUVWYXZ"

alist = []

for arr in xlist:
    list_entry = []
    char_index = 0

    for char in arr:
        if char == "X":
            list_entry.append(alphabet[char_index])
            char_index += 1
        else:
            list_entry.append(char)

    alist.append(list_entry)


text:
Q: awk pairwise differences I run into this problem a lot with data, if I have some integers, I frequently want to look at differences between adjacent integers, I usually solve this in Ruby or Python, but I think such a thing could be done in awk, and I'd prefer that.
I have a table of data such as:
201309,694
201310,699
201311,700
201312,705
201401,713
201402,740

And I would like to find the adjacent differences, that is:
201310-201309,699-694
201311-201310,700-699
201312-201311,705-700
201401-201312,713-715
201402-201401,740-713

I found the function getline in the awk manpage, but I haven't been able to use it successfully.

A: This one-liner produces the output with the minus signs:
awk -F, '{if (NR>1) {print $1 "-" a "," $2 "-" b} a=$1 ; b=$2}' numbers
201310-201309,699-694
201311-201310,700-699
201312-201311,705-700
201401-201312,713-705
201402-201401,740-713

This version shows the actual differences:
awk -F, '{if (NR>1) {print $1-a, $2-b } a=$1 ; b=$2}' numbers
1 5
1 1
1 5
89 8
1 27

In both cases, the awk program begins with an option to set the field separator to a comma (-F,).  Then, for each line in the file, an if statement is executed:  if we are past the first line ((NR>1) then the differences are printed.  The next two commands (a=$1 ; b=$2) update the variables that store the last values.

A: No need for getline.  Just keep track of the columns in the AWK script, e.g.
#!/usr/bin/awk -f

BEGIN {
    FS="," # We separate on the comma character
}

{
    if(NR > 0) { ## NR is the current line number
            print $1 "-" old[1] "," $2 "-" old[2]
    }
    for(field = 1; field <= 2; field++) {
            old[field] = $(field)
    }
}

I assume you want to post "thisline_field1-lastline_field1,thisline_field2-lastline_field2" as a literal string; if you want to subtract, it would be print $1 - old[1] "-" $2 - old[2]


text:
Q: How to make lines the same length? The code is a bit of a pain to paste here, because it is very repetitive.  Right now, the code in JavaScript creates 8 lines of 12 random letters each, based on a function with Math.random() that generates different letters.  When those letters appear on the page, the problem is that, obviously, the letters each have a different length.  Therefore, the lines are not all the same length and the result appears rather messy, because some lines end before/after others.
Is there a way (in JS or CSS, whichever) to make sure that the lines are all exactly the same length?

A: you can use text-justify in the css for that. assuming that the generated text is in a p with a class of sampleText.
.sampleText{text-align:justify}


text:
Q: python kernel dead when performing SVD on a sparse symmetrical matrix I would like to reproduce the SVD method mentioned in a standford lecture on my own dataset. The slide of the lecture is as following

My dataset is of the same type, which is a word co-occurrence matrix M with a size of
<13840x13840 sparse matrix of type '<type 'numpy.int64'>'
with 597828 stored elements in Compressed Sparse Column format>

generated and processed from CountVectorizer(), note that this is a symmetric matrix.
However, when I tried to extract features from SVD, however, none of the following code works,
1st try:
scipy.linalg.svd(M)

I have tried the matrix from sparse csr todense() and toarray(), my computer taken quite a few minutes, and it displays kernel stops. I also played around with different parameter settings
2nd try:
scipy.sparse.linalg.svds(M)

I have also tried to change the matrix type from int64 to float64, however, the kernel dead after 30 seconds or so.
Anyone could suggest me a way to conduct SVD on this matrix in any way?
Thank you so much

A: Seems that the matrix is to stressful for the memory. You have several options:

*

*Perform an adaptive SVD,

*Use modred,

*Use the SVD from dask.

The latter two should work out of the box.
All these options will load only what the memory can.


text:
Q: Can I use factory functions to bind Rows and Columns in "sap.ui.table.Table" control? I am using XML views to create views in my SAPUI5 project. I was trying to implement factory functions to use for Columns & Rows of a sap.ui.Table control. Column factory seems to be working fine but for some reason Row factory never gets executed.
View:
<table:Table xmlns:table="sap.ui.table"
  columns="{
    path: 'oModel>/columns',
    factory: '.colFactory'
  }"
  rows="{
    path: 'oModel>/rows',
    factory: '.rowFactory'
  }"
>
  <!-- ... -->
</table:Table>

Controller:
// Column required from "sap/ui/table/Column"
// Row required from "sap/ui/table/Row"

colFactory: function(sId, oContext) {
  // ...
  return new Column({/*...*/});
},
rowFactory: function(sId, oContext) {
  // ...
  return new Row({/*...*/});
},

I have implemented a dynamic binding of both Rows and Columns as per a specific requirement. Can someone please suggest or help me here? Can get my head around thinking what is missing or wrong.

A: The use of factory function is intentionally left out for sap.ui.table.Table in order to deal with huge amounts of data in contrast to sap.m.Table. The grid table (sap.ui.table.Table) reuses its existing DOM element when the user scrolls, which is incompatible with how factory functions work.
If you really need to use a factory function, I'm afraid there is no other way than implementing sap.m.Table instead (although the performance will suffer). If not, define templates in the Column controls.
Please review also the documentation topic Tables: Which One Should I Choose?