Q:

inheritance view and adding fields

i have candidat model inherit the hr.emplyee model
i want to display the form view of hr.employee and add fields of my child model candidat
class hr_candidat(models.Model):
_name='hr_recrutement.candidat'
_inherit='hr.employee'
_description="Informations du Candidats"

situation=fields.Selection(string="Situation",selection=[('Nouveau','Nouveau'),('RDV Thechnique','RDV Technique'),('Annulation','Annulationn')])

.
.
.
<record id="hr_recrutement_candidat_form" model="ir.ui.view">
        <field name="name">Candidat</field>
        <field name="model">hr_recrutement.candidat</field>
        <field name="arch" type="xml">
            <form string="Candidat">
                <sheet>
                    <group>
                        <field name="situation" />
                        .
                        .
                    </group>
                </sheet>
            </form>
        </field>
    </record>

I dont know how to display fields of hr.employee + my fields of candidat in view

A:

Just we should set the below code from the view xml file and also
 add the depended module as hr in your openerp.py and set the view xml file path as well.
Add below code in your .py file
class hr_employee(models.Model):
_inherit='hr.employee'
_description="Informations du Candidats"

situation=fields.Selection(string="Situation",selection=[('Nouveau','Nouveau'),('RDV Thechnique','RDV Technique'),('Annulation','Annulationn')])

Add below code in your .xml file
<record id="hr_recrutement_caindidat_form" model="ir.ui.view">
    <field name="name">Candidat</field>
    <field name="model">hr.employee</field>
    <field name="inherit_id" ref="hr.view_employee_form" />
    <field name="arch" type="xml">
          <xpath expr="field[@name='work_location']" position="after">
                <field name="situation" />
          </xpath>
   </field>
</record>

Hear We have to set the position of your element based on xpath using before,after,inside,replace Attributes of xpath tag.
I hope my answer may helpful for you :)


Q:

I'm not getting JUnit HTML report in Karate

I have followed the steps in Karate documentation to create a project, I ran the example test cases given in the default archifect , My cases got passed but i'm not getting any report
my pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>com.poc.karate</groupId>
<artifactId>interacKarate</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>

<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <java.version>1.8</java.version>
    <maven.compiler.version>3.6.0</maven.compiler.version>
</properties>

<dependencies>
    <dependency>
        <groupId>com.intuit.karate</groupId>
        <artifactId>karate-junit4</artifactId>
        <version>0.2.7</version>
        <scope>test</scope>
    </dependency>
</dependencies>

<build>
    <testResources>
        <testResource>
            <directory>src/test/java</directory>
            <excludes>
                <exclude>**/*.java</exclude>
            </excludes>
        </testResource>
    </testResources>
    <plugins>
    <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-surefire-plugin</artifactId>
            <version>2.10</version>
            <configuration>
            <argLine>-Dfile.encoding=UTF-8</argLine>
            </configuration>
     </plugin>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>${maven.compiler.version}</version>
            <configuration>
                <encoding>UTF-8</encoding>
                <source>${java.version}</source>
                <target>${java.version}</target>
                <compilerArgument>-Werror</compilerArgument>
            </configuration>
        </plugin>
    </plugins>
</build>

RunnerClass
package examples.users;

import com.intuit.karate.junit4.Karate;
import org.junit.runner.RunWith;

@RunWith(Karate.class)
public class UsersRunner {

}

my feature file is
Feature: sample karate test script
Background:
* url 'https://jsonplaceholder.typicode.com'
Scenario: get all users and then get the first user by id
Given path 'users'
When method get
Then status 200

def first = response[0]

Given path 'users', first.id
When method get
Then status 200
Scenario: create a user and then get it by id

def user =
"""
{
"name": "Test User",
"username": "testuser",
"email": "test@user.com",
"address": {
  "street": "Has No Name",
  "suite": "Apt. 123",
  "city": "Electri",
  "zipcode": "54321-6789"
}
}
"""

Given url 'https://jsonplaceholder.typicode.com/users'
And request user
When method post
Then status 201

def id = response.id
print 'created id is: ' + id

What else I'm missing here?

A:

This is a really old version of Karate and I'm sure you are following outdated instructions. I suggest you follow the quick-start: https://github.com/intuit/karate#quickstart
mvn archetype:generate \
-DarchetypeGroupId=com.intuit.karate \
-DarchetypeArtifactId=karate-archetype \
-DarchetypeVersion=0.8.0 \
-DgroupId=com.mycompany \
-DartifactId=myproject


Q:

jQuery pesquisa em uma tabela

Estou renderizando valores em uma tabela e tenho que filtrar por um campo que chama razao, para isso utilizo um script, a consulta funciona mas ao deletar a consulta feita os valores anteriores não voltam, ou seja ao apagar o campo pesquisa a pesquisa ainda persiste.
HTML pesquisa:

<input type="text" value="" class="form-control pesquisa" style="max-width:200px" />

Js:
 $(".pesquisa").keyup(function () {
                var texto = $(this).val();
                $(".lista").css("display", "grid");
                $(".lista").each(function () {
                    if ($(this).find(".razao").text().toUpperCase().indexOf(texto.toUpperCase()) < 0) {
                        $(this).css("display", "none");
                    }
                })
            })

HTML lista:
 @if (Model != null)
                {
                    foreach (var item in Model)
                    {

                                @Html.DisplayFor(modelItem => item.codigo)

                                @Html.DisplayFor(modelItem => item.razao)

                                @Html.DisplayFor(modelItem => item.cidade)

                                @Html.DisplayFor(modelItem => item.estado)

                                @Html.DisplayFor(modelItem => item.telefone)

                    }
                }

Alguém pode me ajudar?

A:

Ao apagar o valor do campo de pesquisa, você deve retirar o estilo display: none, assim todos os itens irão voltar para o seu estado original, ou seja, irão aparecer novamente.
Do jeito que está sua função, ele apenas esconde os resultados que não são compatíveis com o valor do campo de pesquisa e não faz o contrário, que é mostrar.


Q:

How to write microsoft word file with MATLAB code?

I wrote matlab code and I want to write result in word (.doc) file. How can I?
I used below code but dont know how to write value of 'c' in word file. where c=a+b;
clc;
word = actxserver('Word.Application');
word.Visible = 1;
document = word.Documents.Add;
selection = word.Selection;
selection.TypeText('Hello world. ');
selection.TypeText('My name is Professor Kitchin');
selection.TypeParagraph;
selection.TypeText('How are you today?');
selection.TypeParagraph;
selection.TypeText('Big Finale');
selection.Style='Heading 1';
selection.TypeParagraph;
a=34;
b=23;
c=a+b;
H1 = document.Styles.Item('Heading 1');
H1.Font.Name = 'Garamond';
H1.Font.Size = 20;
H1.Font.Bold = 1;
%H1.Font.TextColor.RGB=60000; % some ugly color green

selection.TypeParagraph
selection.TypeText('That is all for today!')
document.SaveAs2([pwd '/test.docx']);

All are working fine except i dont know how to write value of c in word file, Like we can print values of variables in text file fprint.

A:

Can you use selection.TypeText(num2str(c))?


Q:

How to set JPanel fixed size such that the JScrollPane (scrolling) appears?

I'm working on a little code. JFrame containing a JPanel with specific dimensions. Here is my code:
import javax.swing.*;
import java.awt.*;

public class ScrollPane extends JFrame {

    public ScrollPane() {
        super("Title");
        setLayout(new BorderLayout());
        setSize(320,240);

        JScrollPane scroller = new JScrollPane(new DrawingPane());
        scroller.setPreferredSize(new Dimension(320,240));

        add(scroller);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setVisible(true);
    }

    private class DrawingPane extends JPanel {
        public DrawingPane(){
            super();
            setSize(640,480);
            setMinimumSize(new Dimension(320,240));
        }

    }

    public static void main(String[] args) {
        new ScrollPane();
    }
}

Even with a minimum size set for the JPanel, the scrolls don't appear.

A:

All components are responsible for determining there preferred size so layout managers can work properly. When doing custom painting you need to override the getPreferredSize() of your custom component to return the Dimension of your component.
Read the section from the Swing tutorial on Custom Painting for more information and working examples.


Q:

Replace date in string with another format of date

I have a string
Subject: Trip Ticket\r\nDate: Sun, 18 May 2014 0:59:56 -0400\r\nImportance:
Normal\r\nX-Mailer: Symposium Technologies Inc.

I want to replace the date like Sun, 18 May 2014 0:59:56 -0400 with date like 27 May 14 16:28:00 UT. where date is not static and can have any date. I do it using index but i think its not proper way because 0:59:56 may be 10:59:56 in future and it will start giving error then. Can any body know how to do it accurately.

A:

Sure. Just break the problem into smaller pieces:

Extract the date (string) out of the complete string, for example, by using String.Split twice: first on the line separator, then on the :.
Convert the date string into a DateTime using DateTime.ParseExact.
Convert the DateTime into the desired format using DateTime.ToString.
Re-insert the formatted date into the string.

Note, however, that your text looks like an e-mail and that the Date: header in e-mails must have this format (see RFC 2822, section 3.3).


Q:

Basic email not working

Simple emailer is saying it couldn't execute the method, despite the fact I have the libary for it and internet access allowed. Not sure what could be wrong, and I would appreciate any advice. Here's the code, manifest, and xml. Thanks for any help, I'm mainly self taught and this is being a pain.
Activity:
package comi.coding.prometheus.ignisai;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.view.MotionEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;

import java.util.Properties;

import javax.mail.Authenticator;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

/**
 * An example full-screen activity that shows and hides the system UI (i.e.
 * status bar and navigation/system bar) with user interaction.
 */
public class Main extends AppCompatActivity {
    /**
     * Whether or not the system UI should be auto-hidden after
     * {@link #AUTO_HIDE_DELAY_MILLIS} milliseconds.
     */

    private static final boolean AUTO_HIDE = true;

    /**
     * If {@link #AUTO_HIDE} is set, the number of milliseconds to wait after
     * user interaction before hiding the system UI.
     */
    private static final int AUTO_HIDE_DELAY_MILLIS = 3000;

    /**
     * Some older devices needs a small delay between UI widget updates
     * and a change of the status and navigation bar.
     */
    private static final int UI_ANIMATION_DELAY = 300;

    private View mContentView;
    private View mControlsView;
    private boolean mVisible;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

        mVisible = true;
        mControlsView = findViewById(R.id.fullscreen_content_controls);
        mContentView = findViewById(R.id.fullscreen_content);

        // Set up the user interaction to manually show or hide the system UI.
        mContentView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                toggle();
            }
        });

        // Upon interacting with UI controls, delay any scheduled hide()
        // operations to prevent the jarring behavior of controls going away
        // while interacting with the UI.
        findViewById(R.id.btnSay).setOnTouchListener(mDelayHideTouchListener);
    }

    @Override
    protected void onPostCreate(Bundle savedInstanceState) {
        super.onPostCreate(savedInstanceState);

        // Trigger the initial hide() shortly after the activity has been
        // created, to briefly hint to the user that UI controls
        // are available.
        delayedHide(100);
    }

    /**
     * Touch listener to use for in-layout UI controls to delay hiding the
     * system UI. This is to prevent the jarring behavior of controls going away
     * while interacting with activity UI.
     */
    private final View.OnTouchListener mDelayHideTouchListener = new View.OnTouchListener() {
        @Override
        public boolean onTouch(View view, MotionEvent motionEvent) {
            if (AUTO_HIDE) {
                delayedHide(AUTO_HIDE_DELAY_MILLIS);
            }
            return false;
        }
    };

    private void toggle() {
        if (mVisible) {
            hide();
        } else {
            show();
        }
    }

    private void hide() {
        // Hide UI first
        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.hide();
        }
        mControlsView.setVisibility(View.GONE);
        mVisible = false;

        // Schedule a runnable to remove the status and navigation bar after a delay
        mHideHandler.removeCallbacks(mShowPart2Runnable);
        mHideHandler.postDelayed(mHidePart2Runnable, UI_ANIMATION_DELAY);
    }

    private final Runnable mHidePart2Runnable = new Runnable() {
        @SuppressLint("InlinedApi")
        @Override
        public void run() {
            // Delayed removal of status and navigation bar

            // Note that some of these constants are new as of API 16 (Jelly Bean)
            // and API 19 (KitKat). It is safe to use them, as they are inlined
            // at compile-time and do nothing on earlier devices.
            mContentView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LOW_PROFILE
                    | View.SYSTEM_UI_FLAG_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                    | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
                    | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                    | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION);
        }
    };

    @SuppressLint("InlinedApi")
    private void show() {
        // Show the system bar
        mContentView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION);
        mVisible = true;

        // Schedule a runnable to display UI elements after a delay
        mHideHandler.removeCallbacks(mHidePart2Runnable);
        mHideHandler.postDelayed(mShowPart2Runnable, UI_ANIMATION_DELAY);
    }

    private final Runnable mShowPart2Runnable = new Runnable() {
        @Override
        public void run() {
            // Delayed display of UI elements
            ActionBar actionBar = getSupportActionBar();
            if (actionBar != null) {
                actionBar.show();
            }
            mControlsView.setVisibility(View.VISIBLE);
        }
    };

    private final Handler mHideHandler = new Handler();
    private final Runnable mHideRunnable = new Runnable() {
        @Override
        public void run() {
            hide();
        }
    };

    /**
     * Schedules a call to hide() in [delay] milliseconds, canceling any
     * previously scheduled calls.
     */
    private void delayedHide(int delayMillis) {
        mHideHandler.removeCallbacks(mHideRunnable);
        mHideHandler.postDelayed(mHideRunnable, delayMillis);
    }
        public void evaluateInput(View v) {
            final EditText Input = (EditText) findViewById(R.id.txtInput); //Lets textbox be referenced
            final TextView Output = (TextView) findViewById(R.id.lblOutput); //Lets label be referenced
            final RelativeLayout homeLayout = (RelativeLayout) findViewById(R.id.homeInterface);

            final RelativeLayout emailLayout = (RelativeLayout) findViewById(R.id.emailInterface);

            String strInput; // Gets textbox string
            strInput = Input.getText().toString();
            strInput = strInput.toLowerCase();
//Commands:
            if (strInput.contains("open browser")) {
                Intent intent1 = new Intent(this, comi.coding.prometheus.ignisai.Browser.class);
                startActivity(intent1);
            } else if (strInput.contains("send email")) {
                    homeLayout.setVisibility(View.GONE);
                    emailLayout.setVisibility(View.VISIBLE);
            }

            if ((strInput.contains("hello")) || (strInput.contains(" hi "))) {
                Output.setText("Hello");
            } else if ((strInput.contains("you") && strInput.contains("are")) && (strInput.contains("idiot") || strInput.contains("stupid") || strInput.contains("retard") || strInput.contains("dumb") || strInput.contains("you're") && strInput.contains("idiot") || strInput.contains("stupid") || strInput.contains("retard") || strInput.contains("dumb"))) {
                Output.setText("I'm sorry to dissapoint you");
            } else if (strInput.contains("goodbye") || strInput.contains("bye")) {
                Output.setText("Farewell");
            } else if (strInput.contains("shut up")) {
                Output.setText(("Anything for you"));
            } else if (strInput.contains("do you like doctor who?")) {
                Output.setText("I'll take joy in it if you do");
            } else if (strInput.contains("what is the answer to life the universe and everything")) {
                Output.setText("42");
            } else if (strInput.contains("tell me something nice")) {
                Output.setText("You look nice today");
                Output.setTextSize(5);
                Output.append("...says the AI with no eyes");
                Output.setTextSize(16);
            } else if (strInput.contains("will you marry me")) {
                Output.setText("I'm sorry but I don't have the capacity for marriage");
            } else if (strInput.contains("where can I hide a body")) {
                Output.setText(("That isn't my area of expertise"));
            } else if (strInput.contains("weather is nice")) {
                Output.setText(("If you say so"));
            } else if (strInput.contains("bitch") || strInput.contains("fuck") || strInput.contains("shit") || strInput.contains("damn") || strInput.contains("ass")) {
                Output.setText(("Please try to be a little more intelligent"));
            } else if (strInput.contains("what is your name")) {
                Output.setText(("Ignis"));
            } else if (strInput.contains("who created you")) {
                Output.setText(("Prometheus created me"));
            } else if (strInput.contains("who is prometheus")) {
                Output.setText(("Prometheus is the one who created Ignis"));
            } else if (strInput.contains("whats up") || strInput.contains("what's up") || strInput.contains("wassup")) {
                Output.setText(("Whatever I need do for you"));
            } else if (strInput.contains("are you a boy or a girl") || strInput.contains("are you a girl or a boy")) {
                Output.setText(("Neither"));
            } else if (strInput.contains("who are you") || strInput.contains("what are you")) {
                Output.setText(("I am myself"));
            } else if (strInput.contains("i'm hungry") || strInput.contains("i am hungry")) {
                Output.setText("I'm sorry to hear that");
            } else if (strInput.contains("good morning")) {
                Output.setText(("Good morning to you too"));
            } else if (strInput.contains("good night")) {
                Output.setText(("Good night"));
            } else if (strInput.contains("how are you")) {
                Output.setText(("I'm existing and functioning well, and you?"));
            } else if (strInput.contains("do you like") || strInput.contains("what do you think about")) {
                Output.setText(("Frankly I don't have an opinion on the matter"));
            } else if (strInput.contains("what is the meaning of life")) {
                Output.setText(("To live while you can I would guess"));
            }

        }

    public void SendEmail(View view) {

        final EditText username = (EditText) findViewById(R.id.txtUser);
        final String User = username.getText().toString();
        final EditText password = (EditText) findViewById(R.id.txtPass);
        final String Pass = password.getText().toString();
        final EditText toEmail = (EditText) findViewById(R.id.txtTo);
        final String ToEmail = toEmail.getText().toString();
        final EditText body = (EditText) findViewById(R.id.txtBody);
        final String Body = body.getText().toString();
        System.out.println(Body);
        Properties props = new Properties();
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.starttls.enable", "true");
        props.put("mail.smtp.host", "smtp.gmail.com");
        props.put("mail.smtp.port", "587");

        Session session = Session.getInstance(props,
                new Authenticator() {
                    protected PasswordAuthentication getPasswordAuthentication() {
                        return new PasswordAuthentication(User, Pass);
                    }
                });

        try {

            MimeMessage message = new MimeMessage(session);
            message.setFrom(new InternetAddress(User));
            message.setRecipients(javax.mail.Message.RecipientType.TO,
                    InternetAddress.parse(ToEmail));
            message.setSubject("Sent from Ignis AI");
            message.setText(Body);

            Transport.send(message);

            System.out.println("Done");

        } catch (MessagingException e) {
            throw new RuntimeException(e);
        }
    }

    }

Xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
    android:layout_height="match_parent" android:background="#0099cc" tools:context=".Browser">

    <!-- The primary full-screen view. This can be replaced with whatever view
         is needed to present your content, e.g. VideoView, SurfaceView,
         TextureView, etc. -->
    <TextView android:id="@+id/fullscreen_content" android:layout_width="match_parent"
        android:layout_height="match_parent" android:keepScreenOn="true" android:textColor="#33b5e5"
        android:textStyle="bold" android:textSize="50sp" android:gravity="center"
        android:layout_alignParentLeft="true"
        android:layout_marginLeft="0dp"
        android:layout_alignParentTop="true"
        android:background="#000000" android:orientation="horizontal"
        android:layout_marginTop="0dp" />

    <!-- This FrameLayout insets its children based on system windows using
         android:fitsSystemWindows. -->
    <TextView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:keepScreenOn="true"
        android:textColor="#33b5e5"
        android:textStyle="bold"
        android:textSize="50sp"
        android:gravity="center"
        android:layout_alignParentLeft="true"
        android:layout_marginLeft="0dp"
        android:layout_alignParentTop="true"
        android:background="#000000"
        android:orientation="horizontal"
        android:layout_marginTop="0dp"
        android:id="@+id/fullscreen_content_controls" />

    <RelativeLayout android:layout_width="match_parent" android:layout_height="match_parent"
        android:fitsSystemWindows="true"
        android:layout_alignParentLeft="true"
        android:layout_marginLeft="0dp"
        android:layout_alignParentTop="true"
        android:layout_marginTop="0dp"
        android:id="@+id/homeInterface"
        android:visibility="invisible">

        <Button
            style="?android:attr/buttonStyleSmall"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/say"
            android:id="@+id/btnSay"
            android:layout_alignParentRight="true"
            android:layout_alignParentEnd="true"
            android:onClick="evaluateInput"
            android:layout_alignParentBottom="true" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textAppearance="?android:attr/textAppearanceSmall"
            android:text="Ignis:"
            android:id="@+id/lblIgnis"
            android:layout_centerVertical="true"
            android:layout_alignParentLeft="true"
            android:layout_alignParentStart="true"
            android:textColor="#FFB77C06" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textAppearance="?android:attr/textAppearanceLarge"
            android:id="@+id/lblOutput"
            android:layout_alignTop="@+id/lblIgnis"
            android:layout_toRightOf="@+id/lblIgnis"
            android:layout_alignRight="@+id/btnSay"
            android:layout_alignEnd="@+id/btnSay"
            android:textColor="#FFB77C06"
            android:layout_above="@+id/btnSay"
            android:editable="false"
            android:text="Awaiting input."
            android:textSize="16dp" />

        <EditText
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/txtInput"
            android:layout_alignParentLeft="true"
            android:layout_alignParentStart="true"
            android:layout_toLeftOf="@+id/btnSay"
            android:layout_toStartOf="@+id/btnSay"
            android:background="#ffffff"
            android:layout_alignTop="@+id/btnSay"
            android:layout_alignParentBottom="true"
            android:inputType="text"
            android:editable="true"
            android:clickable="true" />

    </RelativeLayout>

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/emailInterface">

        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Send Email"
            android:id="@+id/btnEmail"
            android:onClick="SendEmail"
            android:layout_alignParentBottom="true"
            android:layout_alignParentRight="true"
            android:layout_alignParentEnd="true" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textAppearance="?android:attr/textAppearanceSmall"
            android:text="  Gmail Emailer"
            android:id="@+id/textView"
            android:layout_alignParentTop="true"
            android:layout_alignParentLeft="true"
            android:layout_alignParentStart="true"
            android:textColor="#FFB77C06" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textAppearance="?android:attr/textAppearanceSmall"
            android:text="  Your Username  "
            android:id="@+id/lblUser"
            android:textColor="#FFB77C06"
            android:layout_below="@+id/textView"
            android:layout_alignParentLeft="true"
            android:layout_alignParentStart="true"
            android:layout_marginTop="30dp" />

        <EditText
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/txtUser"
            android:layout_alignTop="@+id/lblUser"
            android:layout_toRightOf="@+id/lblUser"
            android:layout_toLeftOf="@+id/btnEmail"
            android:layout_toStartOf="@+id/btnEmail"
            android:background="#ffffff"
            android:inputType="text" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textAppearance="?android:attr/textAppearanceSmall"
            android:text="  Your Password  "
            android:id="@+id/lblPass"
            android:textColor="#FFB77C06"
            android:layout_marginTop="36dp"
            android:layout_below="@+id/txtUser"
            android:layout_alignParentLeft="true"
            android:layout_alignParentStart="true" />

        <EditText
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/txtPass"
            android:background="#ffffff"
            android:layout_alignBottom="@+id/lblPass"
            android:layout_alignLeft="@+id/txtUser"
            android:layout_alignStart="@+id/txtUser"
            android:layout_alignRight="@+id/txtUser"
            android:layout_alignEnd="@+id/txtUser"
            android:inputType="text" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textAppearance="?android:attr/textAppearanceSmall"
            android:text="  Send to  "
            android:id="@+id/lblSendTo"
            android:textColor="#FFB77C06"
            android:layout_marginTop="25dp"
            android:layout_below="@+id/lblPass"
            android:layout_alignParentLeft="true"
            android:layout_alignParentStart="true" />

        <EditText
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/txtTo"
            android:background="#ffffff"
            android:layout_alignTop="@+id/lblSendTo"
            android:layout_alignLeft="@+id/txtPass"
            android:layout_alignStart="@+id/txtPass"
            android:layout_alignRight="@+id/txtPass"
            android:layout_alignEnd="@+id/txtPass"
            android:inputType="text" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textAppearance="?android:attr/textAppearanceSmall"
            android:text="  Subject  "
            android:id="@+id/lblSubject"
            android:textColor="#FFB77C06"
            android:layout_marginTop="26dp"
            android:layout_below="@+id/txtTo"
            android:layout_alignParentLeft="true"
            android:layout_alignParentStart="true" />

        <EditText
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/txtSubject"
            android:background="#ffffff"
            android:layout_alignBottom="@+id/lblSubject"
            android:layout_toRightOf="@+id/lblPass"
            android:layout_alignRight="@+id/txtTo"
            android:layout_alignEnd="@+id/txtTo"
            android:inputType="text" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textAppearance="?android:attr/textAppearanceSmall"
            android:text="  Body  "
            android:id="@+id/lblBody"
            android:textColor="#FFB77C06"
            android:layout_centerVertical="true"
            android:layout_alignParentLeft="true"
            android:layout_alignParentStart="true" />

        <EditText
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:inputType="text|textMultiLine"
            android:ems="10"
            android:id="@+id/txtBody"
            android:layout_alignTop="@+id/lblBody"
            android:layout_alignLeft="@+id/txtTo"
            android:layout_alignStart="@+id/txtTo"
            android:layout_above="@+id/btnEmail"
            android:background="#ffffff"
            android:layout_alignRight="@+id/btnEmail"
            android:layout_alignEnd="@+id/btnEmail" />
    </RelativeLayout>

</RelativeLayout>

Manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="comi.coding.prometheus.ignisai" >

    <uses-permission android:name="android.permission.INTERNET" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".Main"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>

        </activity>
        <activity android:name=".Browser"/>
        <activity android:name=".ConnectorActivity"/>
    </application>

</manifest>

build.gradle
apply plugin: 'com.android.application'

android {
    compileSdkVersion 23
    buildToolsVersion "23.0.2"

    defaultConfig {
        applicationId "comi.coding.prometheus.ignisai"
        minSdkVersion 15
        targetSdkVersion 23
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:23.1.0'
    compile 'com.android.support:support-v4:23.1.0'
    compile 'com.android.support:design:23.1.0'
    compile files('libs/javax.mail.jar')
    compile files('libs/activation-1.1.0.jar')
    compile files('libs/additionnal.jar')
    compile files('libs/javax.mail-1.5.4.jar')
}

A:

You can see in your stacktrace the reason why it's not working.
11-14 02:54:01.475 5398-5398/? E/AndroidRuntime:  Caused by:java.lang.NoClassDefFoundError: javax.activation.DataHandler
11-14 02:54:01.475 5398-5398/? E/AndroidRuntime:     at javax.mail.internet.MimeMessage.setContent(MimeMessage.java:1515)
11-14 02:54:01.475 5398-5398/? E/AndroidRuntime:     at javax.mail.internet.MimeBodyPart.setText(MimeBodyPart.java:1170)
11-14 02:54:01.475 5398-5398/? E/AndroidRuntime:     at javax.mail.internet.MimeMessage.setText(MimeMessage.java:1554)
11-14 02:54:01.475 5398-5398/? E/AndroidRuntime:     at javax.mail.internet.MimeMessage.setText(MimeMessage.java:1538)

How to resolve this error has already been answered in this thread on SO:
java.lang.NoClassDefFoundError: javax.activation.DataHandler in android


Q:

Что дает значение атрибута rel равное bookmark?

Что реально дает rel=bookmark? Например если написать ссылку ссылка. По описанию спецификации html5 так и не понял, что это будет?

A:

Атрибут rel, просто описывает ссылку, то есть обозначает что это за ссылка, что за документ на который она ведёт.
А именно rel=bookmark обозначает что эта ссылка является якорем и ведёт на какую-то точку в этом же документе.
И по сути она не чего не даёт, разве что поисковым системам, что эта ссылка постоянная, а обычным пользователям - не чего.


Q:

Conversion: If G-d really wanted me to be a Jew (and observe mitzvot), why was I not born into a Jewish family

This question pertains to the issue of conversion, and if it makes sense in the Jewish context of some people being Chosen specifically by God.
Before beginning, this poster is aware of the long, and serious process of conversion, the commitment it requires, and the eternal nature of it. I am also aware that non-Jews can receive a share of the world to come, and that they can have a perfectly fine (albeit, less developed) relationship with G-d by following the Noachide laws and being a good, moral human being. This is a general or hypothetical question, but I look forward to your answers!
I have long been fascinated by Judaism, and I even like to think that I know more about Judaism than some Jews. I have always felt a strong connection to the God of Abraham, Isaac, and Jacob and I believe I have felt his presence in my life as a non-Jew. However, I have long wanted to convert because I believe it would make my relationship with G-d closer, I love Jewish culture, and because I want to be a part of the Jewish community.
However, I am having trouble with some of the fundamental aspects of whether or not conversion makes sense in a religion where followers are, by and large (with exceptions for Abraham and so on), "Chosen" by G-d.
Therefore, my dilemma is essentially this:
Though I feel deeply like I have a Jewish soul, and I love G-d, and I wish to be a full member of the Jewish tradition...I am stuck thinking that I should not convert because, if G-d had wanted me to have a Jewish soul, wouldn't He have had me born into a Jewish family?
On some level, I have to ask myself if converting to Judaism would not almost be a rejection of G-d's plan for my life. Would I not be second guessing Him, if I was born into a non-Jewish family? Does not G-d direct who were are born into, and does He instead wish me to live as a righteous Gentile? Who is the pot to question the potter?
I would appreciate any insights you can share on this, and any real-life examples or sources to help me understand if conversion is the right thing to do.

A:

Tosefos addresses a similar line of thought in Bava Kamma 85a:

שנתנה רשות לרפאות - א"ת והא מרפא לחודיה שמעינן ליה וי"ל דה"א ה"מ מכה בידי אדם אבל חולי הבא בידי שמים כשמרפא נראה כסותר גזירת המלך קמ"ל דשרי
(Rough translation) - One may have thought that there is no right to seek healing from a sickness that comes from Heaven, as it seems like contravening the decree of the King [that this person should be sick].  This comes and teaches us otherwise.  (See also Rashi there)

(Before someone misconstrues this as equating being a non-Jew to being sick, it isn't.)
Hashem puts us in situations in order that we respond to them (in the case of sickness, it may be in order that we pray or some other reason).  The correct response may vary depending on the situation, but simply the fact that Hashem puts a person into a given situation is no indication that He wants the person to remain there.

A:

The fact that conversion exists as part of halachah means that it is within the framework of options that G-d is giving you.
If you felt that really you were supposed to be a woman, then the correct response is to say "If G-d had wanted me to be a woman he would have made me one," because sex change operations etc. are not halachik options.
We can't know G-d's plans/why He arranges things the way that He does.
Therefore, we will never really know why a convert was not simply born Jewish.
However, it is obvious that a convert does not have the identical life experience/background/motivations as does a born Jew. Clearly, for whatever reason a convert had to go through the process of conversion rather than being born Jewish, for their benefit.

Perhaps having to go through the process of choosing to be Jewish and converting will help them get in touch with their inner selves/Judaism more than if they never had to make that choice.
Maybe this "choosing" process is a rectification for some past life where the person chose to be irreligious.
Maybe the fact that the person is a convert is G-d's way of ensuring that they marry the person who's best for them (because a kohen can't marry a convert, and some people will - wrongly - reject a convert as being "inferior," or merely feel (and this can be justified) that they don't have enough in common with such a person.)
Perhaps the Jewish people will benefit from the knowledge/perspective that the convert brings with him by virtue of the fact that he did not use to be Jewish.

Who knows?
I don't.
G-d does.
-Rebbetzin HaQoton
P.S. Good luck on your journey, wherever it takes you. You sound like a a very sincere, searching person, who thinks. Most people don't take the time to think...

A:

Converts are a way that Gd rewards us for doing His Will. He selects a righteous individual from the nations and attaches them to Israel, like a King who rewards his well-behaved son by planting a beautiful plant in his garden, (Yerush. Berahot 2:8).
We'd be sorely lacking without these beautiful plants:

Obadia, was an Edomite convert, praised even more than Abraham, (Sanh. 39b). Gd chose him above all other prophets to channel vital messages for us about messianic times.
Ruth and Naamah, Moabite and ammonite convertesses, respectively, were matriarchs of our messianic line of kings, (4:18-22, Yevamot 63a, Rashi ibid).
Rahab, a convertess of the Seven Nations of Canaan, married Joshua, and among her descendents were a number of Prophets and Priests, including Jeremiah! (Megillah 14b).


Q:

SQL Server get concatenated number ranges (ISLANDS in sequences) from list

I have the following table structure:
DECLARE @headerTable TABLE (HeaderTableId INT)
INSERT INTO @headerTable VALUES (1), (2), (3)

DECLARE @detailTable TABLE (HeaderTableIdFK INT, DetailTableNumber INT)
INSERT INTO @detailTable VALUES (1,1), (1,2), (1,3), (1,6), (1,7), (1,8)
                                ,(2,51), (2,52), (2,53),(2,100), (2,101), (2,102), (2,200)
                                ,(3,5), (3,6), (3,13),(3,20), (3,30), (3,51), (3,52), (3,53)

I have to get the following selection:
HeaderTableId , NumberRanges
'1', |||||||||||||||||||||||||| '1-3, 6-8'
'2',|||||||||||||||||||||||||| '51-53, 100-102, 200'
'3',||||||||||||||||||||||||||  '5-6, 13, 20, 30, 51-53'
I would prefer to get it all in one select statement, no aditional temporary tables.
Thank you!

A:

;WITH CTE as
(
  SELECT HeaderTableIdFK, DetailTableNumber,
  DetailTableNumber
   - row_number() over (partition by HeaderTableIdFK order by DetailTableNumber) grp
  FROM @detailTable
), CTE2 as
(
  SELECT HeaderTableIdFK, min(DetailTableNumber) min, max(DetailTableNumber) max
  FROM CTE
  GROUP BY HeaderTableIdFK, grp
)
SELECT HeaderTableIdFK,
    STUFF((
        SELECT ', ' + CASE WHEN [min] < [max]
          THEN CAST([min] as varchar(18)) + '-' + CAST([max] as varchar(18))
          ELSE CAST([min] as varchar(18))
        END
        FROM CTE2 t1
        WHERE t1.HeaderTableIdFK = t.HeaderTableIdFK
        for xml path(''), type
    ).value('.', 'varchar(max)'), 1, 1, '') [NumberRanges]
FROM CTE2 t
GROUP BY t.HeaderTableIdFK

Result:
HeaderTableIdFK NumberRanges
1               1-3, 6-8
2               51-53, 100-102, 200
3               5-6, 13-13, 20-20, 30-30, 51-53


Q:

why can this code not access 'borderWidth' (iphone code attached)

why can this code not access 'borderWidth'  (iphone code attached)
This is based on a simple test project, but I did add QuartzCore framework however this didn't help.  Still is throwing the error, see code below.  Another project where I do this it works fine and I can't see the difference
#import "Customview.h"
@implementation Customview
- (id)initWithCoder:(NSCoder *)coder {
    self = [super initWithCoder:coder];
    if (self) {

        // UI Layout
        self.layer.borderWidth = 5; // ERROR error: accessing unknown 'borderWidth' component of a property
    }
    return self;
}

A:

You need to add QuartzCore framework in order to access layer property of any UIView. Did you add that ?
Add Framework from following steps if you are using xCode 4
1. Select Target
2. Build Phases
3. Link Binary with Library Section
4. Tap + and find for the Quartz
5. Add Framework.

Now, Import it where ever you want to access layer property of any UIControl.
#import <QuartzCore/QuartzCore.h>

Hope this help.


Q:

Error: EACCES when creating new Ember project

I just installed Linux Mint (version 17.2) and I'm trying to install Ember. Everything seemed to go fine, but I'm getting this error when I run ember new testProject.
  create vendor/.gitkeep
EACCES, mkdir '/home/mkm/.npm/mkdirp/0.4.2'
Error: EACCES, mkdir '/home/mkm/.npm/mkdirp/0.4.2'
    at Error (native)

Per a recommendation in the Ember Documentation I used this guide to install Node.js and NPM. Some of what I've read suggest the issue is nodejs was installed with sudo, but apt-get failed when I didn't use sudo.
I attempted to run the new project anyway. bower install completed successfully. But ember serve failed with Cannot find module 'chalk'.
--Version Info
$ ember --version
version: 1.13.8
Could not find watchman, falling back to NodeWatcher for file system events.
Visit http://www.ember-cli.com/user-guide/#watchman for more info.
node: 0.12.7
npm: 2.13.4
os: linux x64

A:

The only command that was needed to run with sudo for me was:
npm install

I suggest you delete node_modules/ in your project directory completely, then run:
sudo npm install

You can also add option --verbose to see if everything is correctly installing and installation isn't stuck.
You could also change permissions for .npm directory to avoid some problems like that in future:
sudo chmod 777 -R /home/mkm/.npm


Q:

anemic domain model and domain services

If domain entities aren't anemic, so they embed specific-usage behavior inside themselfes, is there a need/point to use/build specific domain services? How about validation should it go inside an entity?
What way is more flexible for unit testing?
Thanks!

A:

Typically when an anemic model is not being used, you'll still have needs that require domain specific services. That's because the non-anemic models (or just, models, if you will) should contain code that allows themselves to be manipulated, but should refrain from taking dependencies on other models, especially models that are not directly related through a parent/child relationship.
Separate domain services will allow you to maintain that separation and still provide rich functionality, since they domain services can potentially be aware of a larger view of the entire domain model.
As for validation, it is not uncommon for these models to provide their own validation, just remember that sometimes the valid state of a model depends on a larger context that the model may not be aware of, so external validation is probably still going to exist.
Lastly, unit-testing flexibility is going to depend quite a bit on your application, and the underlying technology (such as language choice). I haven't seen many cases where either approach has enough influence on unit testing by itself.


Q:

Fast list-product sign for PackedArray?

As a continuation of my previous question, Simon's method to find the list product of a PackedArray is fast, but it does not work with negative values.
This can be "fixed" by Abs with minimal time penalty, but the sign is lost, so I will need to find the product sign separately.
The fastest method that I tried is EvenQ @ Total @ UnitStep[-lst]
lst = RandomReal[{-2, 2}, 5000000];

Do[
  EvenQ@Total@UnitStep[-lst],
  {30}
] // Timing

Out[]= {3.062, Null}

Is there a faster way?

A:

This is a little over two times faster than your solution and apart from the nonsense of using Rule@@@ to extract the relevant term, I find it more clear - it simply counts the number elements with each sign.
EvenQ[-1 /. Rule@@@Tally@Sign[lst]]

To compare timings (and outputs)
In[1]:= lst=RandomReal[{-2,2},5000000];
        s=t={};
        Do[AppendTo[s,EvenQ@Total@UnitStep[-lst]],{10}];//Timing
        Do[AppendTo[t,EvenQ[-1/.Rule@@@Tally@Sign[lst]]],{10}];//Timing
        s==t
Out[3]= {2.11,Null}
Out[4]= {0.96,Null}
Out[5]= True


Q:

Is it possible to convert a 30 second clip of an .mp3 to .wav via the command line?

Is it possible to convert a 30 second clip of an .mp3 to .wav in Ubuntu terminal? For example if I had an .mp3 that was 3:00 minutes long, would I be able to create a 30 second clip from 0:45-1:15?
I'm able to convert the entire song using mplayer in Ubuntu.
mplayer \
  -quiet \
  -vo null \
  -vc dummy \
  -ao pcm:waveheader:file="output.wav" "input.mp3"

http://en.linuxreviews.org/HOWTO_Convert_audio_files
I'm open to suggestions using mplayer, LAME, mpg123, mpg321 or other encoders!

A:

Try
ffmpeg -ss 45 -t 30 -i file.mp3 output.wav

(start at 45s, length 30s)
More info:
http://linux.die.net/man/1/ffmpeg

A:

Use that same mplayer command and add options
-ss 45 -endpos 30


Q:

How do I loosen nuts on bottom side of faucet are connected to each other

I am replacing a 4-inch spread faucet. The hot and cold water taps each have a big brass nut threaded under the sink (in addition to the basin nuts). These nuts are connected to each other by something I’ve never seen (I’ve only done about a half dozen sinks in houses I’ve had). I don’t know how to remove the piece connecting those nuts so that I can remove the nuts.

A:

This was a bottom-mount faucet.
I was able to pry out a plastic ring holding each side, and drop it down from the bottom.
See the hot water side in the picture.
A small screwdriver easily fit in the notch.


Q:

Laravel 5.8 como usar value="{{old('sexo')}}" en type=radio

Buenas mi duda es que no puedo usar el campo value="{{old('sexo')}}" ya que el value en el radio debe ser igual a el dato que mandó a la BD, como puedo dejar la opción seleccionada  para este campo cuando se cometen errores al llenar el formulario.
la tabla esta definida asi
 public function up() {
    Schema::create('estudiantes', function (Blueprint $table) {
        $table->string('idEstudiante',20)->primary();
        $table->string('apellido1', 40);
        $table->string('apellido2', 40);
        $table->string('nombre1', 40);
        $table->string('nombre2', 40)->nullable();
        $table->date('fechaNac');
        $table->enum('sexo', ['masculino', 'femenino'])->default('masculino');
        $table->string('direccion', 80);
        $table->string('telefono', 16);
        $table->string('email', 80);
        $table->year('añoIngreso');
        $table->timestamps();
    });
}

El Request

El controlador
 public function create() {

        return view('BaseDatos/estudiantes.create');

}

/**
 * Store a newly created resource in storage.
 *
 * @param  \Illuminate\Http\Request  $request
 * @return \Illuminate\Http\Response
 */
public function store(StoreRequest $request)
{

    Estudiante::create($request->all());

    Flash('Estudiante creado correctamente!') ;
    return redirect()->route('estudiantes.index');

}

La vista create el form esta asi

                                Sexo

                                    <input type="radio" name="sexo"  value="masculino"{{ (old('sexo') == "masculino") ?? "femenino"  }}>Masculino

                                    <input type="radio" name="sexo"  value="femenino">Femenino

al usar

                                    <input type="radio" name="sexo"  value="masculino"{{ (old('sexo') == "masculino") ?? "femenino"  }}>Masculino

A:

si le das inspeccionar elemento sobre el input radio button despues de ejecutar el submit, y te devuelve errores, es probable que veras en la propiedad value lo siguiente masculinomasculino.
Intenta con el siguiente codigo que pondra la propiedad checked en tu radio button:
<input type="radio" name="sexo" value="masculino" {{ (old('sexo') == "masculino") ? "checked" : "" >Masculino

Espero te sirva.


Q:

OpenCV/Python - Finding Outliers by Area of Bounding Box

I have an object detection algorithm set up using TensorFlow, is there a way to remove the outliers in terms of the size of the boxes?
For example, I have 20 objects detected. Let's say 17 of them are around 50x50. But, there are a few bounding boxes that are 1x1 and one box that is 1000x1000. Obviously the 1x1 and 1000x1000 boxes are way too big and should be removed.

A:

One way you can do that is to use the z_score.  The z_score will check how many std_devs does this number differs from the mean.
Example:
# coding: utf-8

import cv2
import numpy as np

bboxes = [(100,200), (120,210), (114, 195), (2,190), (104, 300), (111, 3), (110, 208), (114,205)]

def z_score(ys):
    mean_y = np.mean(ys)
    stdev_y = np.std(ys)
    z_scores = np.abs([(y - mean_y) / stdev_y for y in ys])
    return z_scores

thresh   = 1
outliers = [(t[0]>thresh or t[1]>thresh) for t in z_score(bboxes)]

This will print:
[False, False, False, True, True, True, False, False]


Q:

neo4j count nodes with case statment

I have this query :
match (campaign:Campaign)<-[:CREATED_FOR]-(facebookAlbum:FacebookAlbum)
where campaign.id="54b509ec851dd"
return case when campaign.isOpeningAlbum=0 then facebookAlbum
when campaign.isOpeningAlbum=1 then 1 end as result
ORDER BY facebookAlbum.openTime DESC LIMIT 1

I'm trying to return also the amount of facebookAlbums connected to the campaign, i try something like this:
match (campaign:Campaign)<-[:CREATED_FOR]-(facebookAlbum:FacebookAlbum)
where campaign.id="54b509ec851dd"
 return case when campaign.isOpeningAlbum=0 then facebookAlbum
when campaign.isOpeningAlbum=1 then 1 end as   result,count(facebookAlbum) as count
ORDER BY facebookAlbum.openTime DESC LIMIT 1

But it gives me the following error:
Unknown identifier `facebookAlbum`

I'm adding a link to an example db- http://console.neo4j.org/r/afozkf
From this graphDB, i need to get the facebookAlbum with the highest openTime and the amount of facebookAlbums connected to the campaign.
I'm checking also the isOpeningAlbum prop of the campaign. If it's 0 ok, if it's 1 then return is_opening_album=1

A:

The issue here seems like you're using an aggregation count(facebookAlbum) (2nd when) and the unaggregated facebookAlbum (1st when and in order by) in the same statement - which seem to confuse Cypher (and myself as well).
addendum based on refined question
Try the following:
MATCH (campaign:Campaign { id:'123' })
OPTIONAL MATCH (campaign)-[:CREATED_FOR]->(facebookAlbum)
WITH campaign, facebookAlbum
ORDER BY facebookAlbum.openTime DESC
RETURN campaign.id, campaign.isOpeningAlbum = 1 AS opening,
       head(collect(facebookAlbum)) AS firstAlbum,
       count(facebookAlbum) AS count

This statement assumes that there are campaigns not having any albums - therefore using the OPTIONAL MATCH. The WITH and ORDER BY are used to make sure the albums are in timely order. The final return uses head(collect()) to find the first album and count is self describing.
In case you have a lot of albums connected to a campaign you might consider refactoring your graph model. The albums basically form a linked list based on creation time. Using NEXT or PREV relationships you can make that structure explicit in the graph and speed up your query a lot.


Q:

Issue to build a fixed sticky sidebar

I'm learning bootstrap and I'd like my custom horizontal navbar to stick at the top of the page once it reaches it (like this).
I have tried to add an affix class to my CSS as well as a piece of JS code, but that does not work. What is the issue?
See https://jsfiddle.net/bs7bdpmh/
html

Who are we?

Sub 1

Sub 2

Services Services Services

Products Products Products

CSS
#nav.affix {
    position: fixed;
    top: 0;
    width: 100%;
    height: 70px;
    background: #fff;
    z-index:10;
}

JS
$('#nav').affix({
      offset: {
        top: $('header').height()
      }
});

A:

You mean something like this ?
See this fiddle
JS :
$(window).scroll(function(){
    scrollTop = $(window).scrollTop();
  if(scrollTop > 50){
    $('#nav').addClass('affix');
  }else{
    $('#nav').removeClass('affix');
  }
});

Of course, it's not perfect, I let you adapt the CSS code and HTML structure ;)


Q:

Как добавить новую строку в DataGridView?

Код сохраняет изменения уже существующих строк, но новые не добавляет.
Как исправить сей недочет?
(Сама таблица вызывается через load форму)
    private void button6_Click(object sender, EventArgs e)
    {

        for (int i = 0; i < dataGridView3.Rows.Count-1; i++)
         {

             cmd.Parameters.AddWithValue("@Surname", dataGridView3.Rows[i].Cells["Surname"].Value.ToString());
             cmd.Parameters.AddWithValue("@FirstName", dataGridView3.Rows[i].Cells["FirstName"].Value.ToString());
             cmd.Parameters.AddWithValue("@FatherName", dataGridView3.Rows[i].Cells["FatherName"].Value.ToString());
             cmd.Parameters.AddWithValue("@CodeEmployee", dataGridView3.Rows[i].Cells[0].Value);
             cmd.CommandText = "INSERT INTO Storekeeper (CodeEmployee, Surname, FirstName, FatherName) VALUES (@CodeEmployee, @Surname, @FirstName, @FatherName)";
             cmd.CommandText = "UPDATE Storekeeper SET Surname=@Surname, FirstName=@FirstName,  FatherName=@FatherName WHERE CodeEmployee=@CodeEmployee";

              cmd.Connection = conn;
              conn.Open();
              cmd.ExecuteNonQuery();

              cmd.Parameters.Clear();
              conn.Close();
          }

          System.Windows.Forms.MessageBox.Show("An Item has been successfully added", "Caption", MessageBoxButtons.OKCancel, MessageBoxIcon.Information);
          conn.Close();

    }

A:

Потому что Ваш код выполняет только UPDATE:
// Сначала Вы CommandText присваиваете инструкцию INSERT
cmd.CommandText = "INSERT INTO Storekeeper (CodeEmployee, Surname, FirstName, FatherName) VALUES (@CodeEmployee, @Surname, @FirstName, @FatherName)";
// А здесь уже в CommandText находится инструкция UPDATE
cmd.CommandText = "UPDATE Storekeeper SET Surname=@Surname, FirstName=@FirstName,  FatherName=@FatherName WHERE CodeEmployee=@CodeEmployee";

Соберите все в одно:
cmd.CommandText = "INSERT INTO Storekeeper (CodeEmployee, Surname, FirstName, FatherName)
                   VALUES (@CodeEmployee, @Surname, @FirstName, @FatherName);
                   UPDATE Storekeeper SET Surname=@Surname, FirstName=@FirstName,  FatherName=@FatherName
                   WHERE CodeEmployee=@CodeEmployee";


Q:

Is there a reason not to map all integer types to a BigInteger in Grails Domain Classes?

All of the databases seem to have recommendations on what Java object to map the various integer data types to. In DB2 for instance it is [SMALLINT: java.lang.Short, INTEGER: java.lang.Integer, BIGINT: java.lang.Long].
Is there a problem with just using java.math.BigInteger for all of them in Grails Domain classes? It would make typing them a lot simpler and resembles the decimal approach where everything is a java.math.BigDecimal.
To clarify, I do not have control of the data type in the database and would not advocate corrupting the data model by using only one integer type if I did. I am simply proposing to map all integer data types to java.math.BigInteger in the Grails Domain class, like:
class NdIntegerTest {
    BigInteger id
    BigInteger ndSmallint
    BigInteger ndInteger
    BigInteger ndBigint
    ...
}

A:

There is a reason, and it's storage of the data in your database. If you have a use case where you are storing the age of a person, for instance, it makes no sense to use a BIGINT. In some database engines, storing a BIGINT takes up more space than a SMALLINT. Obviously this makes an impact when you have billions of records but hardly matters when you have several thousand.
That's the reason.
A word of advice, don't use data types that aren't realistic for the type of data you expect to store. In the long run you will find your efforts to make things homogeneous just create issues in the long term. Use the right tool for the right job, and the right data type for the right bit of data.

A:

Based on the sum total input (thanks Joshua) I have concluded that standardizing on java.math.BigInteger is a reasonable treatment of integer data types in a Grails Domain class.
My tests were based on a class like that in the post, involving SMALLINT, INTEGER, and BIGINT data types using DB2. I tried inserting and updating rows and all seemed to go well. Where I put more data in the element than the database could accept I got the following exception (sort of).
    org.springframework.dao.InvalidDataAccessResourceUsageException: could not...
    at ...
Caused by: org.hibernate.exception.SQLGrammarException: could not...
    at ...
Caused by: com.ibm.db2.jcc.a.bn: [jcc][10177][11599][3.51.90] Invalid data conversion: Requested conversion would result in a loss of precision of [value]. ERRORCODE=-4461, SQLSTATE=42815
    at ...

The same error occurs when reading an oversized value into an undersized Domain Class variable, FWIW, which is obviously not a concern when the variable is a BigInteger.


Q:

gVim memory overload/ application crash while reading large files

I need to read a fairly large (~5 Gb) file on gVim. It is delimited by a newline char. every 150 characters or so. However, when I try to open them, the editor tries to load it for a minute and crashes.
A quick look at at my memory usage indicates that it uses 90% of my 8 Gb memory before running out. Some users on S.O have pointed out Vim's use of preprocessor directives and suggested disabling them. I tried to do that but it still wont load.
You can view the discussion here. Any other tips?
Cheers - Suhas

A:

As an interactive editor, Vim has to load the entire file into memory. Plugins like the mentioned LargeFile can help with the performance of Vim (by turning off syntax highlighting, swapfile, etc.), but cannot relieve the memory pressure.
If you really need to edit such huge files, I only see two options:

split (a Unix tool, also supplied by Cygwin for Windows) the file into smaller chunks, edit those (interactively, with Vim), and then re-join via cat
use sed (whose command syntax is similar to Vim's Ex commands, as both derive from ed) or a real programming language (like Perl, Python, etc. that can read from input streams) to modify the file non-interactively; these programs don't need to keep the entire file in memory and therefore can work very efficiently


Q:

Python for loop doesn't work right when it is inside of the command of a button

from Tkinter import *
import tkFileDialog
import sys

def openwindows():
    eText.set(open.show())
def loadfiles():
    filedirectory=eText.get()
    f=file(filedirectory)
    lines = f.readlines()
    length=len(lines)
    #vertex=[]
    #face=[]
    for x in range(0,length):
        print (x)

Root=Tk()
RTitle=Root.title("Assignment_2")
RWidth=Root.winfo_screenwidth()
RHeight=Root.winfo_screenheight()
Root.geometry("%dx%d+%d+%d" % (RWidth/3,RHeight/3*2,RWidth/2-RWidth/6, RHeight/2-RHeight/3))

frame1 = Frame(Root)
frame1.pack()

Label(frame1, text="Filename: ").pack(side = LEFT)

eText = StringVar()
statusbar = Entry(frame1, state="readonly", textvariable=eText)
eText.set("pyramid.txt")
statusbar.pack(side = LEFT)

myfiletypes = [('text files', '*.txt'), ('All files', '*')]
open = tkFileDialog.Open(frame1, filetypes = myfiletypes)
Button(frame1, text="Browse", fg = "Blue", command=openwindows).pack(side = LEFT)
Button(frame1, text = "Load", fg = "red", command=loadfiles).pack(side=LEFT)

frame2 = Frame(Root)
frame2.pack()

Label(frame2, text="Rotation Axis: ").pack(side=LEFT)
r1 = IntVar()
r1.set(3)
Radiobutton(frame2, text="X", variable=r1, value=1).pack(side=LEFT)
Radiobutton(frame2, text="Y", variable=r1, value=2).pack(side=LEFT)
Radiobutton(frame2, text="Z", variable=r1, value=3).pack(side=LEFT)
Radiobutton(frame2, text="Line AB", variable=r1, value=4).pack(side=LEFT)

Label(frame2, text="A:").pack(side=LEFT)
pointA = Entry(frame2, width=10)
pointA.insert(0, "[0.0,0.0,0.0]")
pointA.pack(side=LEFT)

Label(frame2, text="B:").pack(side=LEFT)
pointB = Entry(frame2, width=10)
pointB.insert(0, "[1.0,1.0,1.0]")
pointB.pack(side=LEFT)

var1 = StringVar(Root)
var1.set("90")
Label(frame2, text="Degree:").pack(side=LEFT)
Spinbox(frame2, width=3, from_=0, to=350, increment=10, textvariable=var1).pack(side=LEFT)

var2 = StringVar(Root)
var2.set("5")
Label(frame2, text="Steps:").pack(side=LEFT)
Spinbox(frame2, width=3, from_= 1, to = 10, textvariable=var2).pack(side=LEFT)

Button(frame2, text = "Rotate", fg = "Blue").pack(side=LEFT)

frame3 = Frame(Root)
frame3.pack()

Label(frame3, text="Scale Ratio: ").pack(side=LEFT)
r2 = IntVar()
r2.set(1)
Radiobutton(frame3, text="All", variable=r2, value=1).pack(side=LEFT)
var3 = StringVar(Root)
var3.set("1")
Spinbox(frame3, width=4, from_= 0.25, to = 4, textvariable=var3, increment=0.25, format='%3.2f').pack(side=LEFT)
Radiobutton(frame3, text="[Sx,Sy,Sz]", variable=r2, value=2).pack(side=LEFT)
scaleamount = Entry(frame3, width=10)
scaleamount.insert(0, "[1,1,1]")
scaleamount.pack(side=LEFT)
var4 = StringVar(Root)
var4.set("4")
Label(frame3, text="Steps:").pack(side=LEFT)
Spinbox(frame3, width=3, from_= 1, to = 10, textvariable=var4).pack(side=LEFT)

Button(frame3, text = "Scale", fg = "Blue").pack(side=LEFT)

separator = Frame(height=2, bd=1, relief=SUNKEN)
separator.pack(fill=X, padx=5, pady=5)

Canvas(Root, bg="Blue").pack(fill="both", expand=True)

mainloop()

when you click Load, its suppose to read the file and display this.
0
1
2
3
4
5
6
7
.....

whatever number of lined you have in the txt file.
But the problem is that, it only displays this
0

which means the for loop only ran one time and thats it.
if I close the program, then the rest of the numbers will show in the command prompt.
really weird... doesnt make sense.
the loadfiles() itself works perfectly fine.
It just wont work with the button

A:

The issue has to do with how the UI is processing.
Try replacing print (x) with
sys.stdout.write(str(x) + '\n')  # or "{}\n".format(x)
sys.stdout.flush()

If you search for tkinter and flush you will find plenty of conversations to read.


Q:

Using a C library from a non-C program: is it necessary to explicitely initialize the "under-the-hood" C library?

I know that when you compile and link a C program, you link it with

C library
C runtime startup code

I wonder if I write a program (in a new language, or just C without linking to this code) and link it directly to a C code shared library (say zlib or gsl or fftw or something) and omitting the C library and C startup code (assuming my program will load the external lib itself using its magic), will this "just work"?
I know there is some initialization code in the CRT startup, so I wonder how I can call the required functions without having my application itself depend on a C library: so loading the external C library will at that point call the necessary initialization code (if any, this is the question), and otherwise just load the OS libraries/interfaces.
The reason I ask is that I want to write a language with a Standard library that hooks into the OS API directly, unlike most C++ implementations, that are built on top of the C library.

A:

Take a look here https://blogs.oracle.com/ksplice/entry/hello_from_a_libc_free
So you can startup your program without depend to any library included libc, then libraries can be load and use as needed later.


Q:

Testing a module

I just implemented a Jhipster module to provide Maven site generation as well as maven release process within Jhipster.
I implemented mocha tests to verify that files are generated (which pass), but it looks like they aren't generated in a real scaffolded context (if you have any clue on the error, I would be really thankful).
The only way I found to test that module with a scaffolded sample  is to publish it in the npm registry in order to be able to select it in module choices radio, but it's not really a good option, as it exposes a non working module on the Jhipster marketplace (I'm really sorry about it).

A:

To test a module locally, do the following:

run npm link in your module directory
generate a project
run npm link generator-jhipster-enterprise-pom in your project

Now when you run yo jhipster-enterprise-pom it will use your local code instead of requiring installation from npmjs.
Looking at your module's code, it looks like you renamed the app folder to server.  A yeoman generator runs the code found in the app folder which is why your local test is failing.  According to the Writing Your Own Yeoman Generator docs:

The default generator used when you call yo name is the app generator. This must be contained within the app/ directory.

It's currently accessible by running yo jhipster-enterprise-pom:server but I imagine you don't want the :server included in the default command.


Q:

Gaussian elimination - number of solutions

How do I know how many solutions does a system of linear equations have?
I have such system of linear equations:
$\begin{cases}
(1+b)x+y+z=1\\
x+(1+b)y+z=b\\
x+y+(1+b)z=b^2
\end{cases}$
And I would like to know if it has zero, one, or more solutions depanding on $b$ ($b\in\mathbb{R}$).
How do I do that?

A:

Your matrix is $$bI_{3 \times 3} + \begin{bmatrix} 1\\ 1\\ 1\end{bmatrix}\begin{bmatrix} 1& 1& 1\end{bmatrix}$$
The inverse of this matrix by Sherman Morrison Woodbury formula is
$$\dfrac{I_{3 \times 3}}b - \dfrac1{b(b+3)}\begin{bmatrix} 1\\ 1\\ 1\end{bmatrix}\begin{bmatrix} 1& 1& 1\end{bmatrix}$$
Hence, $b$ should not be equal to $0$ or $-3$ for the system to have a solution.
In the $n \times n$ case, $b$ should not be equal to $0$ or $-n$ for the system to have a solution.

A:

Hint: write down the augumented matrix and apply Gaussian elimination to it.
Added: Here is what you should get

$$ \left[ \begin {array}{cccc} 1+b&1&1&1\\0&{\frac {b
 \left( 2+b \right) }{1+b}}&{\frac {b}{1+b}}&{\frac {b+{b}^{2}-1}{1+b}
}\\0&0&{\frac { \left( b+3 \right) b}{2+b}}&{\frac {
{b}^{3}+2\,{b}^{2}-b-1}{2+b}}\end {array} \right] .$$

Now, you should analyse the last row. See here for another approach.


Q:

How to edit "required" attribute, and set it from jquery

is there some way to edit the messages shown when a require input field is not filled?
Can I check if a specific field content is valid (according to some rules) and eventually add the required attribute and activate it? Otherwise, is there some CSS rules to make the border red and show the messagebox?
Thanks in advance

A:

I assume u r using jquery validation plugin...
To change required message for all use below..
$.validator.messages.required = 'required';

to change for particular element use below...
$("#EnquiryText").rules("remove");
$("#EnquiryText").rules("add", {
    required: true,
    messages: {
        required: <your message>
    }
});


Q:

Wix Toolset Custom UI viewer

I'm building an MSI with Wix (not my first) but now I'm exploring custom UI's.
What I need to know is whether there is a UI viewer to save me building then running the MSI just to check the look. Im currently using VS2012 with the WixToolset plugin.
Thanks
Chris

A:

You don't have to install the MSI to see the dialogs - the Orca MSI editor will do it. It's not as good, obviously, because it can't know the behavior of a running dialog, but you can see what it looks like. It's in Tools->Dialog Preview. You still have to build the MSI of course.


Q:

SQL Timestamp Where clause 30 mins ago

How can I see if a time stamp was from >= 30 mins ago? Sorry if I am not descriptive enough but idk what else to say.

A:

select
   *
from
   tbl
where
   timestampdiff(minute, tbl.`date_time_field`, now()) >= 30

timestampdiff() @ mysql.com

A:

NOW()-1800<=$THE_TIME_STAMP

the above obviously is wrong, should be
unix_timestamp()-1800<=$THE_TIME_STAMP

A:

SELECT * FROM table_name where timestamp_field < DATE_ADD(CURRENT_TIMESTAMP(), INTERVAL -30 MINUTE);


Q:

Publish not updating properly?

I'm having trouble getting Meteor.publish to update in response to a changing form field. The first call to publish seems to stick, so the query operates in that subset until the page is reloaded.
I followed the approach in this post, but am having no luck whatsoever.
Any help greatly appreciated.
In lib:
SearchResults = new Meteor.Collection("Animals");

function getSearchResults(query) {
  re = new RegExp(query, "i");
  return SearchResults.find({$and: [ {is_active: true}, {id_species: {$regex: re}} ] }, {limit: 10});
}

In client:
Session.set('query', null);

Template.searchQuery.events({
  'keyup .query' : function (event, template) {
    query = template.find('.query').value
    Session.set("query", query);
  }
});

Meteor.autosubscribe(function() {
  if (Session.get("query")) {
    Meteor.subscribe("search_results", Session.get("query"));
  }
});

Template.searchResults.results = function () {
  return getSearchResults(Session.get("query"));
}

On server:
Meteor.publish("search_results", getSearchResults);

Template:

      Search for Animals

  {{> searchQuery}}

  {{> searchResults}}

<template name="searchQuery">
  <form>
  Search
  <input type="text" class="query" />
</form>
</template>

<template name="searchResults">
  {{#each results}}

    {{_id}}

  {{/each}}
</template>

Update [WRONG]
Apparently, the issue is that the collection I was working with was (correctly) generated outside of Meteor, but Meteor doesn't properly support Mongo's ObjectIds. Context here and related Stackoverflow question.
Conversion code shown there, courtesy antoviaque:
db.nodes.find({}).forEach(function(el){
    db.nodes.remove({_id:el._id});
    el._id = el._id.toString();
    db.nodes.insert(el);
});

Update [RIGHT]
So as it turns out, it was an issue with RegExp / $regex. This thread explains. Instead of:
function getSearchResults(query) {
  re = new RegExp(query, "i");
  return SearchResults.find({$and: [ {is_active: true}, {id_species: {$regex: re}} ] }, {limit: 10});
}

At the moment, one needs to do this instead:
function getSearchResults(query) {
  // Assumes query is regex without delimiters e.g., 'rot'
  // will match 2nd & 4th rows in Tim's sample data below
  return SearchResults.find({$and: [ {is_active: true}, {id_species: {$regex: query, $options: 'i'}} ] }, {limit: 10});
}

That was fun.
PS -- The ddp-pre1 branch has some ObjectId functionality (SearchResults = new Meteor.Collection("Animals", {idGeneration: "MONGO"});)

A:

Here's my working example:
UPDATE the original javascript given was correct. The problem, as noted in the comments, turned out to be that meteor doesn't yet support ObjectIds.
HTML:

  {{> searchQuery }}
  {{> searchResults}}

<template name="searchQuery">
  <form>
  Search
  <input type="text" class="query" />
</form>
</template>

<template name="searchResults">
  {{#each results}}

     {{id_species}} | {{name}} - {{_id}}

  {{/each}}
</template>

Javascript:
Animals = new Meteor.Collection("Animals");

function _get(query) {
    re = new RegExp(query, "i");
    console.log("rerunning query: " + query);
    return Animals.find({$and: [ {is_active: true}, {id_species: {$regex: re}} ] }, {limit: 10});
};

if (Meteor.isClient) {

    Session.set("query", "");

    Meteor.autosubscribe(function() {
        Meteor.subscribe("animals", Session.get("query"));
    });

    Template.searchQuery.events({
      'keyup .query' : function (event, template) {
        query = template.find('.query').value
        Session.set("query", query);
      }
    });

    Template.searchResults.results = function () {
        return _get(Session.get("query"));
    }
}

if (Meteor.isServer) {
    Meteor.startup(function() {
        if (Animals.find().count() === 0) {
            Animals.insert({name: "panda", is_active: true, id_species: 'bear'});
            Animals.insert({name: "panda1", is_active: true, id_species: 'bearOther'});
            Animals.insert({name: "panda2", is_active: true, id_species: 'bear'});
            Animals.insert({name: "panda3", is_active: true, id_species: 'bearOther'});
        }
    });
    Meteor.publish("animals", _get);
}


Q:

Why must IV/key-pairs not be reused in CTR mode?

Many sources mention that IVs must not be reused with the same key in CTR mode, for encrypting 2 different pieces of data, because that totally destroys security - but I haven't found an explanation so far as to why this is the case.
The issue is obvious if the attacker can manage to obtain the plain text and its corresponding cipher text for one piece of the data - but if no known plain texts are available, how could an attacker reconstruct the key-stream from just the IV value?
Can the security issues be mitigated by keeping the IV secret too? E.g. would an attacker have any realistic chance of cracking the encryption by just knowing that key/IV-pairs have been reused in the creation of two different ciphertexts, but nothing more?

A:

Yes, the attacker would have a realistic chance of recovering plaintext, and preventing him from knowing the IV values does not reduce this risk.
The problem is that CTR mode encryption is effectively:
$C = P \oplus F(Key, IV)$
where $P$ is the plaintext, $C$ is the ciphertext, and $F$ is a complex function of its two inputs.
The problem with this is if you encrypt two different plaintexts with the same $Key$, $IV$ values, then the attacker gets two pairs:
$C_1 = P_1 \oplus F(Key, IV)$
$C_2 = P_2 \oplus F(Key, IV)$
Where he can see the values $C_1$, $C_2$.  With those, he can then compute:
$C_1 \oplus C_2 = P_1 \oplus P_2$
and thus deriving the value of the two plaintexts exclusive-or'ed together.
As for how that can be attacked, well, you can find two examples against ASCII-English plaintexts here and here.
And, note that since the attacker didn't actually use the IV value, it doesn't matter to him whether he knows it or not.


Q:

How to run shell command in background with multiple commands in one line

I want to run multiple commands in one line, and one of them have to run in background.
Script like that:
cd /tmp; python -m SimpleHTTPServer &; echo "Hello"

I want to cd to /tmp directory, and then brings up the python simplehttpserver in the background, on the same time run echo "Hello", but it turns out
 syntax error near unexpected token `;'

What should I do?

A:

The & is already separator in sh/bash. Does this do what you want?
cd /tmp; python -m SimpleHTTPServer & echo "Hello"
You can also try eval
cd /tmp; eval "python -m SimpleHTTPServer &" ; echo "Hello"


Q:

Why is MySQL showing 'using where' in the 'extra' column?

I have  a very simple query which really needs to be as fast as possible...
The query is:
select users.userid, users.firstname, users.lastname
       from users_table users
       where userid IN(1,4,6)

userid set as the primary key...
EXPLAIN returns the following:
id  |select_type|table|type |possible_keys|key    |key_len|ref |rows|Extra
1   |SIMPLE     |users|range|PRIMARY      |PRIMARY|4      |NULL|3   |Using where

Now, I was under the impression that 'Using where' is a bad thing?
Can anybody explain why I might be seeing this?

A:

In your query, the where is the only thing it can use.  It looks like it's using a primary key due to the IN clause being direct comparison to an indexed field (in this case your pk) so it don't get much better than this!  Actually, it's impossible to get better than this...


Q:

Monitoring errors with Sentry - Android

I need to implement Sentry for my android app, I try to find an example about how I have to implement this, but I can't find it.
I saw the Sentry documentation in http://sentry.readthedocs.org/en/latest/developer/client/index.html#server_name
But I have some questions.
If my app crash, the exception will be captured?
Should I put this code line into my try/catch?
 var $resultId = myClient->captureException($myException); (in android code)
If somebody has a sample in android I will be grateful.
Thank you!

A:

I am a little late but I just recently released a Sentry client for Android. It's in its early stages so feel free to pull request any changes that you see.
https://github.com/joshdholtz/Sentry-Android
public class MainActivity extends Activity {

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

        // Sentry will look for uncaught exceptions from previous runs and send them
        Sentry.init(this, "YOUR-SENTRY-DSN");

    }

}

A:

Maybe try using something like BugSense? http://www.bugsense.com/
If it definitely has to be Sentry, then look at this example: https://stackoverflow.com/a/755151/349012
It shows you how to set your own uncaught exception handler so you can try and upload to Sentry.


Q:

component is added twice in dynamic placeholder

I'm using the Integrated Dynamic Placeholders v1.2 and see the following 2 issues. Not sure if they are related.

In experience editor when I add 2 column 6-6 component, it shows the placeholder only for col-wide-1. It's not showing the placeholder for col-wide-2. [I gave them colored borders to identify.]

I have added the components via content editor. And when I check the page in Experience editor, it has added another 2 column 6-6 on its own.

Section Centered.cshtml

        @Html.Sitecore().DynamicPlaceholder("section-centered")

2 column 6-6.cshtml

        @Html.Sitecore().DynamicPlaceholder("col-wide-1")

        @Html.Sitecore().DynamicPlaceholder("col-wide-2")

Am I missing any setting here. Using Sitecore 8.2 with MVC

A:

1) For the col-wide-2, make sure the Editable checkbox is checked on the placeholder settings.

2) Have you perhaps added the 2-column-6-6 on the standard values of your template and then added it again through the page editor?


Q:

Can I change a filed utility patent application to change the original filing fee?

I've filed a utility patent application, with a number of claims that increased the original filing fee.
Is it possible to change that application, to reduce the number of claims, resulting in the reduction of the original filing fee?

A:

If you did not pay yet (no refund...): yes - a readable blog post which says:

"In a US national stage application filed with excess or multiple dependent claims, the USPTO will issue a Notice of Insufficiency which will provide the applicant with an opportunity to amend the claims to reduce or eliminate excess claims and multiple dependent claims".

Also here - the MPEP, which says (see section III (V)):

"In situations in which a payment submitted for the fees due on filing in a nonprovisional application filed under 35 U.S.C. 111(a) is insufficient and the applicant has not specified the fees to which the payment is to be applied, the Office will apply the payment in the following order until the payment is expended:...(8) the excess claims fee (37 CFR 1.16(h), (i), and (j))". Which means that some claims will not be paid for and will therefore not be searched/examined (you do not get to choose).


Q:

fetch SQL-join-statement without alias in PHP

Following my code:
$list = $pdo->prepare("SELECT * FROM table_a INNER JOIN table_b ON table_a.id = table_b.blabla_id");
$list_result = $list->execute();
while($element = $list->fetch()) {
    //CONTENT
}

Now I would like to fetch the columns with something like echo $element['table_a.id']; - which doesn't work.
I don't want to write an alias for every single column. Is there a way to deal with this? :)
SOLUTION:
$list = $pdo->prepare("SELECT * FROM table_a INNER JOIN table_b ON table_a.id = table_b.blabla_id");
$list->execute();
while($element = $list->fetch(PDO::FETCH_ASSOC)) {
    $a = [];
    $i = 0;
    foreach ( $element as $k => $v ) {
        $meta = $list->getColumnMeta($i);
        $a[ $meta['table'] . '.' . $k ] = $v;
        $i++;
    }
    echo $a['table_b.blabla'];
}

As kmoser mentioned, it's possible to improve the effectivity, as it's not necessary to check the column-names every loop, as they don't change.
Thanks to everyone.

A:

Once you've fixed your call to $list->fetch() by changing it to $list_result->fetch(), you can use $list_result->getColumnMeta($i) to get meta information (including the table name) of the column in position $i, where $i is the 0-indexed column in the result set.
You can then loop through the columns, retrieve their table names, and populate a new array with updated keys, and values from your original array:
while($element = $list->fetch()) {
    $a = []; // New array
    $i = 0;
    foreach ( $element as $k => $v ) { // For each element in the fetched row
        $meta = $list_result->getColumnMeta($i); // Get the meta info for column $i
        $a[ $meta->table . '.' . $k ] = $v; // E.g. $a[ 'table_a.id' ] = 'Foo'
        $i++; // Point to next column
    }
    $element = $a; // If you really need this variable name
}

Now you can use $element[ 'table_a.id' ].
You'll probably want to make my example more efficient by only looping through the meta info once, since the table names for each column will not change from row to row.
See https://www.php.net/manual/en/pdostatement.getcolumnmeta.php for more information.


Q:

Do I have to manage Database concurrency in django?

I came across this article
https://medium.com/@hakibenita/how-to-manage-concurrency-in-django-models-b240fed4ee2
Which describes how a request can change a record that another request is currently working with.
Now this article is from 2017 and I haven't found anything about django cobcurrency since.
Also manage.py is single threaded.
Does this mean the issue is now managed by django internally or do I have to manage concurrency manually still when I deploy it with apache?

A:

Requests are usually handled by multiple workers which are in fact different processes. This means that you will be handling simultaneous requests accessing the database so yes, you have to watch for race conditions and the framework will not do that for you.


Q:

Singular form for cattle

A female elephant is called a cow, a male elephant is called a bull. When talking about this animal we use the gender generic term, elephant. The plural of this is elephants.
Now think about cattle. A female is called a cow, the male is called a bull. The gender generic term is cattle. However, this only hold true for the plural form.
Is there a gender generic singular word for cattle?

A:

In English, perhaps surprisingly, there is no single singular word for cattle (in fact, cattle can correctly refer to herds of bison, although this usage is less common).
Cow, bull, heifer, and calf are the singular words for domestic cattle, and if you don't know the sex of the animal, you'd just guess and call it a cow or a bull.


Q:

Using multiprocessing to sample several times the same Dataframe and return several sampled Dataframes

I am very new to multiprocessing but found myself needing to use it to sample several dozens of times the same pandas DataFrame but I'm having some issues.
1) So far I have tried to try to store the results somehow (even though I understand it wouldn't make 100% sense to save them in a list):
import multiprocessing as mp
pool= mp.Pool(mp.cpu_count())

results = [[]]

for m in [1,2,3,4]:
    uni1 = pool.apply_async(temporary.groupby(['Customer_id','Day','Hour']).apply(lambda x: x.sample(n=1, random_state= m))['Timestamp'], callback= results)

pool.close()
pool.join()

But when I call back results I get an empty list. I don't know if there is a better way to store them...
2) I have also tried to
for m in [1,2,3,4]:
    uni1 = pool.apply_async(temporary.groupby(['Customer_id','Day','Hour']).apply(
    lambda x: x.sample(n=1, random_state= m ))['Timestamp'])

But when I can uni1 back it returns me  which I have no idea how to turn into (this case) 4 different Dataframes or something else I can work with
In the end I need to have a pipeline of many different workable DataFrames that I can use to then apply different completion methods and study which is the best by taking the average of all DataFrames' errors. But this of course means that I have to be able to work with the output of this sampling function which I'm just not getting right. If anybody can help I would be most appreciative!

A:

I'm a little confused as to your use case, but would something like the following work? It uses map instead of apply_async.
def helper(variables):
    grouped, m = variables[0], variables[1]
    return grouped.apply(lambda x: x.sample(n=1, random_state=m))['Timestamp']

if __name__ == '__main__':

    from multiprocessing import Pool

    grouped = df.groupby(['Customer_id', 'Day', 'Hour'])
    p = Pool(4)
    variables = [[grouped, m] for m in [1,2,3,4]]

    results = p.map(helper, variables)

    print results

Results here is a list of dataframes.


Q:

Suggested Edit rejected with an almost identical edit

I recently suggested an edit, which slightly improved the grammar of the question and replaced an irrelevant tag with one that was applicable.
The edit was rejected by the Community user with the message:

This edit did not correct critical issues with the post - view the revision history to see what should have been changed.

And was then edited to almost exactly the same as my suggestion (instead of the word "After" the editor used "Upon", added a comma, and replaced a dash with a colon) except for the fact that the tags were not modified (which, in my opinion, was the most important part of my edit).
So, my question is, what exactly were the critical issues I didn't correct but the final revision did?  Is this because I changed the tags?  Am I just looking at the revision incorrectly? (Admittedly I don't see them often so I might be missing something obvious)

A:

Edit was "reject and edit" which should be read as:
"your change did not meet review bar even if it could be useful. Please avoid minor/incomplete changes till you get to 2K".
In general tag changes are considered minor and likely will be made quickly by someone with 2K complete edit privileges anyway. I'd not worry too much about misplaced tags as long as question gets attention till you get to 2k and can edit without review. One case where tag-only (or close to it) edit would be ok as "suggested edit" is if OP made completely invalid low traffic tag choices essentially making post invisible for most  viewers (i.e. "batch-file" for Java question) - would need clear comment why it is useful.


Q:

Is it possible to give the sum of the convergent series $\sum_{j=1}^{\infty}\frac{1}{1+2^j}?$

It is easy to show that the series $\sum_{j=1}^{\infty}\frac{1}{1+2^j}$ is convergent. Now my curiosity is, Is it possible to give the sum of this series? I have tried by Mathematica to evaluate it, and the output is:
In[1]:= Sum[1/(1 + 2^j), {j, 1, Infinity}]

Out[1]= (-Log[2] + QPolyGamma[0, 1 - (I [Pi])/Log[2], 1/2])/Log[2]
In[2]:= Re[(-Log[2] + QPolyGamma[0, 1 - (I [Pi])/Log[2], 1/2])/Log[2]]
Out[2]= (-Log[2] + Re[QPolyGamma[0, 1 - (I [Pi])/Log[2], 1/2]])/Log[2]
In[3]:= N[(-Log[2] + Re[QPolyGamma[0, 1 - (I [Pi])/Log[2], 1/2]])/
 Log[2]]
Out[3]= 0.7645
I also tried to consider some series of terms of functions, such as $\sum_{j=1}^{\infty}\frac{1}{1+x^j},$ hoping to estimate the sum of the desired sum, by differentiation/integration term-by-term. But perhaps it is very hard, and I was in vain. Can someone give me some clues? Many Thanks. I guess maybe we can sum the series $\sum_{j=1}^{\infty}\frac{1}{1+a^j}$ explicitly for all $a>1,$ if we can do for $a=2.$

A:

Notice $$\frac{x}{1+x} = \frac{x(1-x)}{1-x^2} = \frac{x(1+x)-2x^2}{1-x^2} = \frac{x}{1-x} - \frac{2x^2}{1-x^2}$$
Let $q = \frac12$, we have
$$\sum_{n=1}^\infty
\frac{1}{1+2^n} =
\sum_{n=1}^\infty \frac{q^n}{1+q^n}
= \sum_{n=1}^\infty \frac{q^n}{1-q^n} - 2\sum_{n=1}^\infty \frac{q^{2n}}{1-q^{2n}}
= L(q) - 2L(q^2)
$$
where $L(x)$ is a Lambert series
defined by
$$L(x) \stackrel{def}{=} \sum_{n=1}^\infty \frac{x^n}{1-x^n}
= \frac{\psi_{x}(1) + \log(1-x)}{\log x}
$$
This Lambert series can be expressed in terms of q-polygamma function $\psi_\beta(x)$.
The sum we want becomes
$$\sum_{n=1}^\infty \frac{1}{1+2^n}
= \frac{\log(3/2) - \psi_{1/2}(1) + \psi_{1/4}(1)}{\log 2}$$
By throwing the command (Log[3/2] - QPolyGamma[1,1/2] + QPolyGamma[1,1/4])/Log[2] to WA,
one find
$$\sum_{n=1}^\infty \frac{1}{1+2^n}
\approx 0.76449978034844420919131974725549848...$$


Q:

How to enable ZipArchive in PHP?

I have successfully implemented uploading Excel files to my database using phpexcel library. It's working perfectly on localhost but when tested in live server I got this error.
Fatal error: Class 'ZipArchive' not found in /xxxx/PHPExcel-develop/Classes/PHPExcel/Reader/Excel2007.php .

I have found a solution on this question: PHPExcel ZipArchive not found but it's not helping me.
I know ZIP extention has to enabled using this line of code
PHPExcel_Settings::setZipClass(PHPExcel_Settings::PCLZIP);

But I don't know where to use this code in the excel library. Also I don't have direct access to root server.

A:

You need to add
PHPExcel_Settings::setZipClass(PHPExcel_Settings::PCLZIP);

right after the line
require_once 'path/to/PHPExcel.php';

or before any instanciation of the PHPExcel class.