text:
Q: Android: resume app from previous position How can I resume my app from its previous position.
Note that it is still active, just paused. So if I click the androids current app button, or the app icon it resumes fine.
But who do I do this from my widget..
I have the following:
// Create an Intent to launch Activity
Intent intent = new Intent(context, LoginForm.class);
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, 0);

This obviously launches the LoginForm as opposed to just resuming the application.
Does anyone know how to do this?
Edit:
Just to clarify, I dont want anything special. I basically want to mimic pressing the android icon launcher.

A: You've basically answered your own question ;-)
Just simulate what Android does when you launch the app:
Intent intent = new Intent(context, LoginForm.class);
intent.setAction(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_LAUNCHER);
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, 0);

or you could try this (assuming LoginForm is the root activity of your application and that there is an instance of this activity still active in the task stack):
Intent intent = new Intent(context, LoginForm.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, 0);

Setting FLAG_ACTIVITY_NEW_TASK should just bring an exising task for the application from the background to the foreground without actually creating an instance of the activity. Try this first. If it doesn't work for you, do the other.

A: Use this it is same as android doing for your launcher activity
Intent notificationIntent = new Intent(context, SplashActivity.class);
        notificationIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP);
        notificationIntent.setAction(Intent.ACTION_MAIN);
        notificationIntent.addCategory(Intent.CATEGORY_LAUNCHER);
        PendingIntent clickActionIntent = PendingIntent.getService(context, 0, notificationIntent, 0);


text:
Q: How to implement a mathJax into webView I have a webView that represents a web page with MathJax equations. I heard that you can add a js script into your webView or something like that. How can I add a MathJax into my webView so equations will be represented right.
browser.loadDataWithBaseURL(basicUrl, styles + content, "text/html", "utf-8", "");
browser.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);

The browser is a webView where I load the content. Styles is basically a string with a css styles for webView, a content is a html that I need to display. basicUrl is a url of the page that this webView represents

redpajama_set_name: RedPajamaStackExchange


text:
Q: Java subclass constructor inherited member I have a question as to why does this piece of code, when executed, prints out the value 0. I don't exactly understand what happens in the SubClass constructor, and why is it that when I erase the overridden method implicitValue, it prints out 10. Does the SubClass constructor make use of the SuperClass constructor?
Thank you.
class SuperClass {
    protected int superClassValue;

    public SuperClass() {
        superClassValue = implicitValue();
    }

    public int implicitValue() {
        return 10;
    }

    public int getValue() {
        return superClassValue;
    }
}

class SubClass extends SuperClass {
    private int subClassValue;

    public SubClass() {
        subClassValue = 20;

    }

    public int implicitValue() {
        return subClassValue;

    }
}

class Example {
    public static void main(String argv[]) {
        SubClass ss = new SubClass();
        System.out.println("The value is " + ss.getValue());

    }
}

A: TL;DR
Problem is that implicitValue from SubClass is used by superclass implicit SuperClass constructor (super()) via implicitValue() method, before subClassValue = 20; will be executed in SubClass constructor, so it returns default value of subClassValue which for int field is 0.

Does the SubClass constructor make use of the SuperClass constructor?

Yes, subclass constructor at start always invokes superclass constructor, so code
public SubClass() {
    subClassValue = 20;
}

is same as
public SubClass() {
    super();//superclass constructor
    subClassValue = 20;
}

But lets take a look at your code. You are printing result of getVlaue() method which exists in your superclass
public int getValue() {
    return superClassValue;
}

As you see it returns value of superClassValue. Before you invoke getVlaue() you are creating ss instance, so you are invoking code
super();//superclass constructor
subClassValue = 20;

which means you are invoking constructor of superclass which looks like
public SuperClass() {
    superClassValue = implicitValue();
}

so this.superClassValue is initialized with returned value of implicitValue() method, but because of dynamic binding (late binding) JVM will try to search for implementation of this method starting from actual class of this which is SubClass, and since this class has its own overridden version it will be invoked
public int implicitValue() {
    return subClassValue;
}

but subClassValue wasn't set to anything yet
super();// <-- we are still here
subClassValue = 20;// this line was not executed yet

so subClassValue still has its default value 0, which means that
superClassValue = implicitValue(); //will be initialized with 0;

so
public int getValue() {
    return superClassValue;
}

will return 0.

A: *

*In your case: SuperClass constructor will be called by default.

*Logic for new SubClass().
It will call the constructor of the SuperClass first. When the constructor of the SuperClass is being called - A value return from the implicitValue() will be assigned to the variable superClassValue - The method implicitValue() being called is the method Of the SubClass (NOT the implicitValue() of SupperClass as you thought - Polymorphism feature of OOP).
When the implicitValue() of the SubClass is being called, the field subClassValue is not initialized yet so the field subClassValue still be ZERO. That is the reason you see Zero in the output.

*When you remove override the implicitValue from the SubClass. the implicitValue() being called is the implicitValue() of the SupperClass --> This is why you see 10 in the output.

A: Yes, the subclass constructor implicitly calls the superclass constructor if such a call is not explicitly given.  But it prints 0 because of the fact that the implicitValue method is overridden in SubClass.

*

*The superclass constructor is called.  Here, the SuperClass part of the object is created.  All variables are initialized.  Because there is no explicit value given, the compiler gives superClassValue the default value, 0.  The superclass constructor then calls implicitValue(), which calls the subclass's method.  This method returns superClassValue, which was initialized to 0.  This value is explicitly assigned back to superClassValue.

*The subclass initializes its subClassValue to 10.

*The getValue() method is called, and it returns superClassValue, which is 0.  The value is 0 is printed.

If you were to remove the implicitValue method in SubClass, then it would inherit SuperClass's version of the method, which returns 10.
If you were to modify the implicitValue method in SubClass to return 5, then it would initialize superClassValue to 5, and it would print The value is 5.

A: It sounds like something is wrong with your Override method or subclass. Because it sounds like when it is implements a variable the value is not getting instantiated so it is defaulting to 0 and then when you remove it the super class takes over resulting in you getting the value 10.


text:
Q: Why subpackage has been imported implicitly in Python? I've a python package named a with two files in it __init__.py and b.
a/
a/__init__.py
a/b.py

The content of files:
# a/__init__.py
from .b import *

and
# a/b.py
c = 1

When I import a in Python, why I can use a.b directly? I'm confused because I do not import b explicitly in a/__init__.py.
If I use a empty a/__init__.py, then there's no b in a's namespace. So it seems from .b import * (or from .b import c) also import b, why?
I've check the Python document and several posts in SO, but didn't find related issues.

I want all things from b but not b itself in a, then I could modify a/__init__.py to
# a/__init__.py
from .b import *
del b

Is this good?


text:
Q: Looping through scraped data and outputting the result I am trying to e the BBC football results website to get teams, shots, goals, cards and incidents. I currently have 3 teams data passed into the URL.
I writing the script in Python and using the Beautiful soup bs4 package. When outputting the results to screen, the first team is printed, the the first and second team, then the first, second and third team. So the first team is effectively being printed 3 times, When I am trying to get the 3 teams just once.
Once I have this problem sorted I will write the results to file. I am adding the teams data into data frames then into a list (I am not sure if this is the best method).
I am sure if is something to do with the for loops, but I am unsure how to resolve the problem.
Code:
from bs4 import BeautifulSoup
import urllib2
import pandas as pd

out_list = []
for numb in('EFBO839787', 'EFBO839786', 'EFBO815155'):

url = 'http://www.bbc.co.uk/sport/football/result/partial/' + numb + '?teamview=false'
teams_list = []
inner_page = urllib2.urlopen(url).read()
soupb = BeautifulSoup(inner_page, 'lxml')

for report in soupb.find_all('td', 'match-details'):
            home_tag = report.find('span', class_='team-home')
            home_team = home_tag and ''.join(home_tag.stripped_strings)

            score_tag = report.find('span', class_='score')
            score = score_tag and ''.join(score_tag.stripped_strings)

            shots_tag = report.find('span', class_='shots-on-target')
            shots = shots_tag and ''.join(shots_tag.stripped_strings)

            away_tag = report.find('span', class_='team-away')
            away_team = away_tag and ''.join(away_tag.stripped_strings)

            df = pd.DataFrame({'away_team' : [away_team], 'home_team' : [home_team], 'score' : [score],  })
            out_list.append(df)

for shots in soupb.find_all('td', class_='shots'):

              home_shots_tag = shots.find('span',class_='goal-count-home')
              home_shots = home_shots_tag and ''.join(home_shots_tag.stripped_strings)

              away_shots_tag = shots.find('span',class_='goal-count-away')
              away_shots = away_shots_tag and ''.join(away_shots_tag.stripped_strings)

              dfb = pd.DataFrame({'home_shots': [home_shots], 'away_shots' : [away_shots] })
              out_list.append(dfb)

for incidents in soupb.find("table", class_="incidents-table").find("tbody").find_all("tr"):

                   home_inc_tag = incidents.find("td", class_="incident-player-home")
                   home_inc = home_inc_tag and ''.join(home_inc_tag.stripped_strings)

                   type_inc_goal_tag = incidents.find("td", "span", class_="incident-type goal")
                   type_inc_goal = type_inc_goal_tag and ''.join(type_inc_goal_tag.stripped_strings)

                   type_inc_tag = incidents.find("td", class_="incident-type")
                   type_inc = type_inc_tag and ''.join(type_inc_tag.stripped_strings)

                   time_inc_tag = incidents.find('td', class_='incident-time')
                   time_inc = time_inc_tag and ''.join(time_inc_tag.stripped_strings)

                   away_inc_tag = incidents.find('td', class_='incident-player-away')
                   away_inc = away_inc_tag and ''.join(away_inc_tag.stripped_strings)

                   df_incidents = pd.DataFrame({'home_player' : [home_inc],'event_type' : [type_inc_goal],'event_time': [time_inc],'away_player' : [away_inc]})

                   out_list.append(df_incidents)

print "end"

print out_list

I am new to python and stack overflow, any suggestions on formatting my questions is also useful.
Thanks in advance!

A: Those 3 for loops should be inside your main for loop.
out_list = []
for numb in('EFBO839787', 'EFBO839786', 'EFBO815155'):
  url = 'http://www.bbc.co.uk/sport/football/result/partial/' + numb + '?teamview=false'
  teams_list = []
  inner_page = urllib.request.urlopen(url).read()
  soupb = BeautifulSoup(inner_page, 'lxml')

  for report in soupb.find_all('td', 'match-details'):
              # your code as it is

  for shots in soupb.find_all('td', class_='shots'):
              # your code as it is

  for incidents in soupb.find("table", class_="incidents-table").find("tbody").find_all("tr"):
              # your code as it is

It works just fine - shows up a team just once.
Here's output of first for loop:
[{'score': ['1-3'], 'away_team': ['Man City'], 'home_team': ['Dynamo Kiev']},
{'score': ['1-0'], 'away_team': ['Zenit St P'], 'home_team': ['Benfica']},
{'score': ['1-2'], 'away_team': ['Boston United'], 'home_team': ['Bradford Park Avenue']}]

A: This looks like a printing problem, at what indentation level are you printing out_list ?
It should be at zero indentation, all the way to the left in your code.
Either that, or you want to move out_list into the top most for loop so that it's re-assigned after every iteration.


text:
Q: GraphQl Mutation: addUser not creating user I'm refactoring a Google Books app from a Restful API to GraphQL, and I am stuck on a mutation not behaving the way I expect.
When a user fills out the form found on Signup.js the Mutation ADD_USER should create a user within Mongoose, this user should have a JWT token assigned to them, and user should be logged in upon successful execution of the Mutation.
Actions observed:
•   Mutation is being fired off from the front end. When I open developer tools in the browser I can see the Username, Email and Password being passed as variables.
•   I have tried console logging the token, and keep getting an undefined return
•   When I try to run the mutation in the GraphQL sandbox I get a null value returned.
•   When I console log the args in resolvers.js no value appears on the console, which tells me the request is not reaching the resolver.
SignupForm.js (React FE Page)
import React, { useState } from "react";
import { Form, Button, Alert } from "react-bootstrap";
import { useMutation } from "@apollo/client";
import { ADD_USER } from "../utils/mutations";
import Auth from "../utils/auth";

const SignupForm = () => {
  // set initial form state
  const [userFormData, setUserFormData] = useState({
    username: "",
    email: "",
    password: "",
  });
  // set state for form validation
  const [validated] = useState(false);
  // set state for alert
  const [showAlert, setShowAlert] = useState(false);

  const [addUser] = useMutation(ADD_USER);

  const handleInputChange = (event) => {
    const { name, value } = event.target;
    setUserFormData({ ...userFormData, [name]: value });
  };

  const handleFormSubmit = async (event) => {
    event.preventDefault();

    // check if form has everything (as per react-bootstrap docs)
    const form = event.currentTarget;
    if (form.checkValidity() === false) {
      event.preventDefault();
      event.stopPropagation();
    }

    try {
      ///Add user is not returning data. payload is being passed as an object

      const response = await addUser({
        variables: { ...userFormData },
      });

      if (!response.ok) {
        throw new Error("OH NO!SOMETHING WENT WRONG!");
      }

      const { token, user } = await response.json();
      console.log(user);
      Auth.login(token);
    } catch (err) {
      console.error(err);
      setShowAlert(true);
    }

    setUserFormData({
      username: "",
      email: "",
      password: "",
    });
  };

Mutation.js
export const ADD_USER = gql`
  mutation addUser($username: String!, $email: String!, $password: String!) {
    addUser(username: $username, email: $email, password: $password) {
      token
      user {
        username
        email
      }
    }
  }
`;

typeDefs.js
const { gql } = require("apollo-server-express");

const typeDefs = gql`
  input SavedBooks {
    authors: [String]
    description: String
    bookId: String
    image: String
    link: String
    title: String
  }
  type Books {
    authors: [String]
    description: String
    bookId: ID
    image: String
    link: String
    title: String
  }
  type User {
    _id: ID
    username: String
    email: String
    password: String
    savedBooks: [Books]
  }
  type Auth {
    token: ID!
    user: User
  }
  type Query {
    me: User
  }
  type Mutation {
    ##creates a user profile through the Auth type, that way we can pass a token upon creation
    addUser(username: String!, email: String!, password: String!): Auth

    login(email: String!, password: String!): Auth

    saveBook(bookData: SavedBooks): User

    deleteBook(bookId: ID!): User
  }
`;
module.exports = typeDefs;

resolvers.js
const { User, Book } = require("../models");
const { AuthenticationError } = require("apollo-server-express");
const { signToken } = require("../utils/auth");

const resolvers = {
  Query: {
    me: async (parent, args, context) => {
      if (context.user) {
        return User.findOne({ _id: context.user._id }).populate("books");
      }

      throw new AuthenticationError("You need to log in");
    },
  },
};
Mutation: {
  //try refactoring as a .then
  addUser: async (parent, args) => {
    //create user profile
    await console.log("resolver test");
    console.log(args);
    const user = await User.create({ username, email, password });
    //assign token to user
    const token = signToken(user);
    return { token, user };
  };

  login: async (parent, { email, password }) => {
    const user = User.findOne({ email });
    if (!user) {
      throw new AuthenticationError("Invalid Login Credentials");
    }
    const correctPw = await profile.isCorrectPassword(password);
    if (!correctPw) {
      throw new AuthenticationError("Invalid Login Credentials");
    }
    const token = signToken(user);
    return { token, user };
  };

  saveBook: async (parent, { bookData }, context) => {
    if (context.user) {
      return User.findOneAndUpdate(
        { _id: context.user._id },
        { $addToSet: { savedBooks: bookData } },
        { new: true }
      );
    }
    throw new AuthenticationError("You need to log in");
  };

  deleteBook: async (parent, { bookId }, context) => {
    if (context.user) {
      return User.findOneAndUpdate(
        { _id: contex.user._id },
        //remove selected books from the savedBooks Array
        { $pull: { savedBooks: context.bookId } },
        { new: true }
      );
    }
    throw new AuthenticationError("You need to log in");
  };
}
module.exports = resolvers;

auth.js
const jwt = require("jsonwebtoken");

// set token secret and expiration date
const secret = "mysecretsshhhhh";
const expiration = "2h";

module.exports = {
  // function for our authenticated routes
  authMiddleware: function ({ req }) {
    // allows token to be sent via  req.query or headers
    let token = req.query.token || req.headers.authorization || req.body.token;

    // ["Bearer", "<tokenvalue>"]
    if (req.headers.authorization) {
      token = token.split(" ").pop().trim();
    }

    if (!token) {
      return req;
    }

    // verify token and get user data out of it
    try {
      const { data } = jwt.verify(token, secret, { maxAge: expiration });
      req.user = data;
    } catch {
      console.log("Invalid token");
      return res.status(400).json({ message: "invalid token!" });
    }

    // send to next endpoint
    return req;
  },
  signToken: function ({ username, email, _id }) {
    const payload = { username, email, _id };

    return jwt.sign({ data: payload }, secret, { expiresIn: expiration });
  },
};

Basically, I have combed from front to back end looking for where I introduced this bug, and am stuck. Any suggestions or feedback is greatly appreciated.

A: I was able to figure out the issue. First, a syntax error on resolver.js was preventing my mutations from being read.
Next, I made the following adjustment to handleFormSubmit on SignupForm.js
  try {
      ///Add user is not returning data. payload is being passed as an object

      const {data} = await addUser({
        variables: { ...userFormData },
      });
     console.log(data)
      console.log(userFormData)

      **Auth.login(data.addUser.token);**
    } catch (err) {
      console.error(err);
      setShowAlert(true);
    }

That way my FE was properly accounting for what my Auth Middleware was passing back after successful user creation. Thanks for your help xadm, being able to talk this out got me thinking about where else to attack the bug.


text:
Q: Can Erlang R16B02 be built on OSX 10.10.5 with OpenSSL? I need to build Erlang R16B02 on OSX 10.10.5 with support for SSL so I can use crypto application. I have already installed OpenSSL 0.9.8 with Homebrew. Running openssl > version yields the following:
$ openssl
OpenSSL> version
OpenSSL 0.9.8zg 14 July 2015

I am able to get Erlang R16B02 built and installed, but I consistently get the same error when trying to start the crypto application:
1> crypto:start().
** exception error: undefined function crypto:start/0
2>
=ERROR REPORT==== 1-Feb-2016::14:19:17 ===
Unable to load crypto library. Failed with error:
"load_failed, Failed to load NIF library: 'dlopen(~/.asdf/installs/erlang/R16B02/lib/erlang/lib/crypto-3.1/priv/lib/crypto.so, 2): Symbol not found: _AES_cbc_encrypt
  Referenced from: ~/.asdf/installs/erlang/R16B02/lib/erlang/lib/crypto-3.1/priv/lib/crypto.so
  Expected in: flat namespace
 in ~/.asdf/installs/erlang/R16B02/lib/erlang/lib/crypto-3.1/priv/lib/crypto.so'"
OpenSSL might not be installed on this system.

=ERROR REPORT==== 1-Feb-2016::14:19:17 ===
The on_load function for module crypto returned {error,
                                                 {load_failed,
                                                  "Failed to load NIF library: 'dlopen(~/.asdf/installs/erlang/R16B02/lib/erlang/lib/crypto-3.1/priv/lib/crypto.so, 2): Symbol not found: _AES_cbc_encrypt\n  Referenced from: ~/.asdf/installs/erlang/R16B02/lib/erlang/lib/crypto-3.1/priv/lib/crypto.so\n  Expected in: flat namespace\n in ~/.asdf/installs/erlang/R16B02/lib/erlang/lib/crypto-3.1/priv/lib/crypto.so'"}}

I have tried calling other functions, like crypto:module_info(), but I always get the same error. I have built Erlang R16B02 with various flags using asdf. Here a couple combinations I tried:
Building with options: --enable-dynamic-ssl-lib --prefix=~/.asdf/installs/erlang/R16B02

Building with options: --with-ssl=/usr/local/opt/openssl --prefix=~/.asdf/installs/erlang/R16B02 # with-ssl points to the OpenSSL install

Building with options: --with-ssl --prefix=~/.asdf/installs/erlang/R16B02

All of these resulted in the same error. One strange thing I noticed when I was trying to figure out how to get Erlang built with SSL was the --enable-darwin-64bit and the --enable-darwin-universal flags caused the build to fail. This seems odd as I am building on OSX, so it seems like these flags would be required.
So to recap:

*

*I am using asdf (shouldn't really matter though)

*With all the successfully builds I get the error above when invoking any function in the crypto module

*I have Erlang 17 built with OpenSSL and the crypto application

Update
I came across this https://gist.github.com/ThePicard/7378417 so I tried a couple of the options listed there for the configure script but I still got the same error.
Update 2
otool -L ~/.asdf/installs/erlang/R16B02/lib/erlang/lib/crypto-3.1/priv/lib/crypto.so prints this:
~/.asdf/installs/erlang/R16B02/lib/erlang/lib/crypto-3.1/priv/lib/crypto.so:
    /usr/lib/libSystem.B.dylib (compatibility version 1.0.0, current version 1213.0.0)


text:
Q: Handle user control dropdownlist selected index change event in aspx page I have create the user control and add the same in aspx code behind. I want to handle the selected index change event for dropdownlist in aspx page. Kindly help me to do this.

        <asp:Label ID="lbl_parent" runat="server" Text="Parent Node" CssClass="control-label"></asp:Label>

        <asp:DropDownList ID="ddl_parent" runat="server" CssClass="form-control" AutoPostBack="true">
        </asp:DropDownList>

phContactDetails.Controls.Add(LoadControl("~/UserControl/WUC_DisLabelControl.ascx"));

foreach (var control in phContactDetails.Controls)
            {
                var usercontrol = control as WUC_DisLabelControl;
                DropDownList ddl_parenrt = ((DropDownList)usercontrol.FindControl("ddl_parent"));
                ddl_parenrt.SelectedIndexChanged += new EventHandler(ddlparent_SelectedIndexChanged);
}

protected void ddlparent_SelectedIndexChanged(object sender, EventArgs e)
        {
            throw new NotImplementedException(); //Not Firing
        }

A: You have not added SelectedIndexChanged event on dropdown.
Add SelectedIndexChanged="ddlparent_SelectedIndexChanged" on dropdown.
<asp:DropDownList ID="ddl_parent" runat="server" CssClass="form-control" AutoPostBack="true" OnSelectedIndexChanged="ddlparent_SelectedIndexChanged">
</asp:DropDownList>


text:
Q: How to parse JsonObject List without knowing the key with Gson? I'm having a bit trouble with parsing this JsonObject as I don't know the keys that will come and I'm using Gson. Here is an example of the json:
"calendar": {
         "201rj5-9": {
                "year": "2015",
                "month": "9",
         },
         "20tfh15-9": {
                "year": "2015",
                "month": "9",
         },
         [...]
}

A: This looks like a Map, thus you could use a HashMap for your calendar field:
public class Root {
    HashMap<String, Entry> calendar;

    public static class Entry {
        String year, month;
    }
}

And just the matching Gson code for completeness:
Root root = new Gson().fromJson(json, Root.class);


text:
Q: Writing a test class for a read only Visualforce page I am trying to write a test class for a Visualforce page, which returns a list of associated records to the contact object. The test class is throwing no errors, however is also not covering the Extension either.
I have an understanding that I have to create test data in the Test class, then call the standard controller, and then run an instance of the extension.
EDIT: this was failing due to a trigger on the same object. Note to self - CHECK TEST RESULTS outside of developer console!!
Thanks in advance!
VF:
<apex:page showHeader="false" standardStylesheets="false" standardController="contact" extensions="studentResultsExtension">

<button class="btn btn-default pull-right" onclick="selectElementContents(document.getElementById('courseEnrollments') );">
  Copy Table</button>

Course Enrollment Information

        Qualification
        End Date
        Unit Code
        Unit Name
        Result
        Grade
        Trainer

    <apex:repeat value="{!couEnr}" var="ce">

        {!ce.Qualification__c}
        <apex:outputText value="{0, date, MMMM d','  yyyy}"><apex:param value="{!ce.Course_End_Date__c}" /></apex:outputText>
        {!ce.Unit_Code__c}
        {!ce.Unit_Description__c}
        {!ce.Total_Grade_Result__c}
        {!ce.Total_Weighted_Grade__c}
        {!ce.Course_Trainer__c}

    </apex:repeat>

</apex:page>

APEX Extension:
public with sharing class studentResultsExtension {

public list <Course_Enrollment__c> couEnr {get;set;}
public ID contactID {get;set;}

public studentResultsExtension(ApexPages.StandardController controller) {

    contactID = ApexPages.currentPage().getParameters().get('Id');

    couEnr = [SELECT id,name,Course_End_Date__c,Course_Trainer__c,Qualification__c,Survey_ID__c,Total_Grade_Result__c,Total_Weighted_Grade__c,Unit_Code__c,Unit_Description__c FROM course_enrollment__c WHERE contact__c = :contactID];
}
}

Test Class
@istest
public class testStudentResultsExtension {
public static testMethod void TestStudentResults(){

    test.startTest();
    Id ceRecordType = [Select Id, Name from RecordType where name = 'Higher Education' limit 1].Id;

    Account testAccount = new Account();
    testAccount.Name='Test Company Name123';
    insert testAccount;

    Contact testContact = new Contact();
    testContact.firstname='test';
    testContact.lastname='contact';
    testContact.account=testAccount;
    insert testContact;

    Course_enrollment__c testCourseEnrollment = new Course_Enrollment__c();
    testCourseEnrollment.RecordTypeId=ceRecordType;
    testCourseEnrollment.contact__r.id=testContact.Id;
    insert testCourseEnrollment;

    PageReference pageRef = Page.studentResults;
    Test.setCurrentPage(pageRef);

    pageRef.getParameters().put('id', String.valueOf(testContact.Id));
    ApexPages.StandardController sc = new ApexPages.StandardController(testContact);
    studentResultsExtension viewEnrollments = new studentResultsExtension(sc);

    system.assert(sc != null);

    List<Course_enrollment__c> couEnr  = new List<Course_Enrollment__c>{};
        couEnr = [SELECT id,name FROM Course_Enrollment__c WHERE Contact__r.id = :testContact.Id];

    test.stopTest();
}
}

A: You have a number of minor problems with your code. I'm not sure why you didn't see any errors, but I would expect your code to crash with a System.NullPointerException or perhaps a DmlException if Contact__c is required:
testCourseEnrollment.contact__r.id=testContact.Id;

Contact__r here is null, so you're not actually assigning that contact to the record. Instead, use the normal Contact__c notation:
testCourseEnrollment.Contact__c=testContact.Id;

As a matter of practicality, if you're ever using __r.Id, you're probably doing something wrong.
Also, I'd recommend not using getParameters when you're using a StandardController. The following code is equally effective:
public with sharing class studentResultsExtension {

public list <Course_Enrollment__c> couEnr {get;set;}
public ID contactID {get;set;}

    public studentResultsExtension(ApexPages.StandardController controller) {
        contactID = controller.getId();
        couEnr = [SELECT id,name,Course_End_Date__c,Course_Trainer__c,Qualification__c,Survey_ID__c,Total_Grade_Result__c,Total_Weighted_Grade__c,Unit_Code__c,Unit_Description__c FROM course_enrollment__c WHERE contact__c = :contactID];
    }
}

Again, even if the parameter were null, you should still automatically get 100% coverage.
I should also mention that, while not super-critical, there's no point in testing basic system functionality:
system.assert(sc != null);

It is literally impossible to reach this line of code and have sc be null. It can't happen.
Similarly:
    couEnr = [SELECT id,name FROM Course_Enrollment__c WHERE Contact__r.id = :testContact.Id];

Isn't testing your extension, it's testing the ability of the system to execute a query (and there's that __r.Id again).
Also, this query is problematic:
Id ceRecordType = [Select Id, Name from RecordType where name = 'Higher Education' limit 1].Id;

If someone later creates another record type on another object with the same name, you might get the wrong one. Use the following instead:
Id ceRecordType = Course_Enrollment__c.SObjectType.getDescribe()
    .getRecordTypeInfosByName().get('Higher Education').getRecordTypeId();

To properly test your controller, make sure that:
System.assertEquals(1, viewEnrollments.couEnr.size());

Finally, it could just be that you can't see the coverage for some reason. Perhaps the code coverage didn't update correctly. Try going to Setup > Develop > Test Execution, and clear your code coverage first, and then run your test.

A: The main issue is could be this line: testContact.account=testAccount;
where you are inserting contact. Here contact will not be associated with the Account. You have to assign AccountId instead of Account object.
Correct code will be as follows:
Contact testContact = new Contact();
testContact.firstname='test';
testContact.lastname='contact';
testContact.accountId=testAccount.id;
insert testContact;

and 2nd issue will be testCourseEnrollment.contact__r.id=testContact.Id;
it should be testCourseEnrollment.contact__c = testContact.Id;
finally, I do not find the reason of putting test.startTest(); at the beginning of the method and test.stopTest(); at the end of the method.


text:
Q: Can we deploy the spring-boot jar inside the tomcat server? I'm a bit new to spring boot environment and doing an poc on it. I know it might sound strange but i have this question like whether an spring-boot jar can be deployed in an tomcat server. The reason i'm asking this is that i read somewhere that spring-boot jar will come with embedded tomcat and also the .class files will be stored in different path compared to normal jars. So now if i deploy this jar in an tomcat server will it work same or do we need to do some extra configurations to make it work ?

A: You can not deploy Jar to tomcat and expect it to load your web application. War has its own directory and file structure defined which is read by tomcat and load the application accordingly. It can not understand jar file as web application and run it.
Now spring boot jar uses totally different approach to start the embedded server and load your application. It is not same as war deployed on tomcat but spring boot takes care of handling embedded server to serve the request.
If you want to deploy your spring-boot app as war, you can do that by changing few things in your project mentioned here.


text:
Q: Unable to change max_input_time in php.ini In Ubuntu I'm trying to change the max_input_time to -1
In php.ini I see the following section:
; max_input_time
;   Default Value: -1 (Unlimited)
;   Development Value: 60 (60 seconds)
;   Production Value: 60 (60 seconds)

Currently I'm seeing the value as being 60. When I inserted the following command:
max_input_time = -1

And restart Apache, I see the value has remained the same. My question is, how do I change max_input_time to -1 in php.ini?
Thanks

A: just comment the line
;max_input_time = 60

and it will return to its default value


text:
Q: How to get element offset on angular 2
I heve this html structure which represents a list of elements like a
  tree. and on another part have some favorites element from this list.
  What I want to achieve is when I click a favorite element to scroll to
  the element in the list and mark it as selected. I have problems
  calculating the offset top of the element relative to the tree-view
  componentcause I have a treenode elementRef and I try to go on it's
  parents but when he reach the final treenode in the tree structure the
  parentElement is null. How can I compute the exact offset of the
  element so I can scroll to it ? I don't want to incluje JQuery in my
  project for this

<tree-view class="unit-subunit-list" ng-reflect-tree-data="[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]" ng-reflect-tree-options="[object Object]"><tree class="tree-view" ng-reflect-nodes="[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]" ng-reflect-options="[object Object]" ng-reflect-focused="false">

      <treenode ng-reflect-node="[object Object]">

        <treenodecontent ng-reflect-node="[object Object]"></treenodecontent><treenodetemplate><unit-subunit-item ng-reflect-node-model="[object Object]">

        keyboard_arrow_up

        Olympics

</unit-subunit-item></treenodetemplate>

          <treenode ng-reflect-node="[object Object]">

        <treenodecontent ng-reflect-node="[object Object]"></treenodecontent><treenodetemplate><unit-subunit-item ng-reflect-node-model="[object Object]">

            Administrator

</unit-subunit-item></treenodetemplate>

  </treenode><treenode ng-reflect-node="[object Object]">

        <treenodecontent ng-reflect-node="[object Object]"></treenodecontent><treenodetemplate><unit-subunit-item ng-reflect-node-model="[object Object]">

            Astronaut

            Description

</unit-subunit-item></treenodetemplate>

  </treenode><treenode ng-reflect-node="[object Object]">

        <treenodecontent ng-reflect-node="[object Object]"></treenodecontent><treenodetemplate><unit-subunit-item ng-reflect-node-model="[object Object]">

            Lead

            Description

</unit-subunit-item></treenodetemplate>

  </treenode>

  </treenode>

  </tree></tree-view>


text:
Q: Explanation of spaces of functions in PDE Let's consider following equation:
The problem
$$
\begin{cases}
-\operatorname{div}\left( p\left(x\right) \nabla{u} \right) + q(x)u = f \quad\text{... on } \Omega \\
u = h(x) \quad\text{... on } \partial\Omega
\end{cases}
$$
where

*

*$u \in W^{1,2}(\Omega)$

*$u-u_0 \in W^{1,2}_0 \text{, so that } u_0 \in W^{1,2}(\Omega) : Tu_0 = h \in L^2(\partial\Omega)$ (T is a trace)

*$f \in L^2(\Omega)$

*$p,q \in L^\infty(\Omega)$

has the following solution:
$$
\forall v \in W^{1,2}_0(\Omega): \int_\Omega \left( p(x) \nabla u \nabla v + q(x)uv \right)\,dx = \int_\Omega f v \, dx
$$

I know that $L^p$ spaces are Lebesgue integrable and they have a following norm:
$$
|| \cdot ||_p = \left( \int_\Omega |f|^p d\lambda \right)^{\frac{1}{p}}
$$
I also know, that Sobolev spaces are the completion of the $C^\infty(\overline{\Omega})$ and they have the norm:
$$
|| \cdot ||_{k,p} = \left( \sum_{|\alpha| \leq k} \int_\Omega |D^\alpha f |^p d\lambda \right)^{\frac{1}{p}}
$$

But, I don't understand, why $u$ belongs to $W^{1,2}$ specifically, why $h$ and f belong to $L^2$ and why $p$ and $q$ belong to $L^\infty$. Could you, please, explain it to me a little intuitively? (e.g. show me some examples where $L^1$ space wouldn't be suitable instead of $L^2$ etc.)

A:
Why not $L^1$:

In studying elliptic equation, it is most convenient to consider $L^p$ space for $1<p<\infty$. The reason is that one does not have nice $L^p$-estimates
$$\|u\|_{W^{2,p}(\Omega)}\le C (\|f\|_{L^p(\Omega)} + \|u\|_{L^p(\Omega)}$$
for $p=1$ (Here we assume that $p(x)$ is nice). Note that the above estimates is crucial in establishing the existence and uniqueness of solution (Fredholm theory) to your system. One can roughly see how this fails when $p=1$ in this question.

Condition on $p(x)$:

Actually in the easiest cases we even assume that $p$ is continuous, so that the above $L^p$-estimates can be established using perturbation theory. On the other hand, it is natural to assume that $p$ is in $L^\infty$, so that the PDE is uniformly elliptic. See more discussions here
The above discussion is in Gilbarg and Trudinger, chapter 9.


text:
Q: Not able to use file from resources folder when file is packaged inside Jar I have Java Gradle project and I am using third party library in my project which requires license.
I added license_.cxl on following path.
src/main/resources/license_.cxl

Before using any third party lib function I need to setLicense(String licenseFilePath).
When I test the code using IntelliJ IDEA its working fine.
But when I create jar file and try to execute the same function, its giving me error - "Unable to set License, License file not found: src/main/resources/license_.cxl"
Then I added license_.cxl on custom folder(outside project directory) and hardcoded that path in my code then its working fine when I execute code by running jar file.
So I started checking third party code. I saw their code is trying to create new license file using provided path.
I tried may stackoverflow solution to provide resources folder license_.cxl file path but nothing works for me other than keeping file on custom directory to run code using jar file.
Looks like issue is third party code is not able to create a new license file from the path where license_.cxl file is packaged inside my jar file.
How I can resolve the issue so that I can test the code by running jar file without keeping license_.cxl to custom directory.
Updated - following is the dir structure when I unzip jar file and license_.cxl file is inside BOOT-INF\classes folder.


text:
Q: JS - Функция запоминает каждую предыдущею ячейку и добавляет выбранную Проблема в том что функция запоминает каждую предыдущею ячейку и добавляет к ней выбранную, и меняет текст в ней тоже. А мне надо для каждой ячейки отдельно.
Подскажите в чем проблема или подправьте код.
Спасибо.

                Type
                Name
                Time

                1	*	*

                2	*	*

                3	*	*

                4	*	*

        Change: <input id="changes" type="checkbox" name="" onclick="eventsInTable()">

        Get text for change: <input id="changeText" type="text" name="" value="">

        <button id="applyToChanges">Apply</button>

//Выбор ячейки и замена текста
var changeText = function(e){
    var inputChangeText, applyChanges;
    inputChangeText = document.getElementById('changeText');
    applyChanges = document.getElementById('applyToChanges');

    inputChangeText.value = e.target.textContent; //получить текст с ячейки

    //замена текста
    applyChanges.addEventListener('click', function(){
        e.target.textContent = inputChangeText.value;
    }, false);
}
//доступ к изменение текста
function eventsInTable(){
    var checkBoxChanges = document.getElementById('changes');
    var table = document.getElementById('tableCinema');

    if (checkBoxChanges.checked) {
        table.addEventListener('click', changeText, false);
    } else {
        table.removeEventListener('click', changeText, false);
        alert("You haven't access to change");
    }
}

A: Проблема в многократном исполнении:
applyChanges.addEventListener('click', function(){
    e.target.textContent = inputChangeText.value;
}, false);

и выстреливании всех накопившихся обработчиков с соответствующими захваченными е.


text:
Q: Python String Slicing Tutorial I am currently studying Python at school. I don't understand what the book is trying to explain and my instructor isn't very helpful. The book gives the following example:
usr_text = input('Enter a string: ')
print()

first_half = usr_text[:len(usr_text)//2]
last_half = usr_text[len(usr_text)//2:]

print('The first half of the string is "{}"'.format(first_half))
print('The second half of the string is "{}"'.format(last_half))

I don't understand what
[:len(usr_text)//2]

&
[len(usr_text)//2:]

does. Would anyone mind explaining what's happening there and why it's used? Thank you!


text:
Q: beamer: position section head in a fixed position Consider this example:
\documentclass{beamer}
\AtBeginSection[]{
  \begin{frame}
    \vspace{3cm}
    \centering
    \begin{beamercolorbox}[sep=8pt,center,shadow=true,rounded=true]{title}
      \Large\insertsectionhead\par%
    \end{beamercolorbox}
    \vfill
  \end{frame}
  }

\AtBeginSubsection[]{
  \begin{frame}
    \vspace{3cm}
    \centering
    \begin{beamercolorbox}[sep=8pt,center,shadow=true,rounded=true]{title}
      \Large\insertsectionhead\par%
      \vspace{0.5cm}
      \large\insertsubsectionhead\par%
    \end{beamercolorbox}
    \vfill
  \end{frame}
  }
\begin{document}
\section{Section 1}
\subsection{Subsection 1 A}
\end{document}

I use \vspace with the intention to fix the positions of section and subsection heads. However, when viewed in a slide mode, the section head is changing position when moving from section title page to subsection title page.
How to solve?

A: The problem is that  by default the frame content is vertically centered and needs to be aligned to the top. This can be achieved by mean of the [t] option given globally as in \documentclass[t]{beamer} or individually for a particular frame as in \begin{frame}[t].
MWE
\documentclass[t]{beamer}
\AtBeginSection[]{
  \begin{frame}
    \vspace{3cm}
    \centering
    \begin{beamercolorbox}[sep=8pt,center,shadow=true,rounded=true]{title}
      \Large\insertsectionhead\par%
    \end{beamercolorbox}
    %\vfill
  \end{frame}
  }

\AtBeginSubsection[]{
  \begin{frame} % or  \begin{frame}[t] (if not set globally)
    \vspace{3cm}
    \centering
    \begin{beamercolorbox}[sep=8pt,center,shadow=true,rounded=true]{title}
      \Large\insertsectionhead\par%
      \vspace{0.5cm}
      \large\insertsubsectionhead\par%
    \end{beamercolorbox}
    %\vfill
  \end{frame}
  }
\begin{document}
\section{Section 1}
\subsection{Subsection 1 A}
\end{document}


text:
Q: MYSQL, Include Null Results Want a null row where no data exist
Hello.  This is in regards to MySQL Workbench 6.3.
I'm trying to return a list of results for every item listed in my select statement, which would include those items that don't actually exist.  So if i list 5 items in my select statement and only 3 exist, i'd like to get 5 rows returned, 3 actual rows with data and 2 more rows that only show null. Can someone please show me how to edit my query below to show this ? Thank you !
select emails from table where email in (dog, frog, cat, tiger, lizard);

Actual Result (only the 3 emails that actual exist show)
dog
cat
tiger

Desired Result
dog
null
cat
tiger
null

A:
The desired results are not possible.. You can't expect MySQL to
  return the selected records in the order they went in the IN()
  operator.

So i think you better off when you change the desired result to something you know sometiming was not found in the table, i think you are looking for.
Query
 SELECT
    search_emails.email
  , (
      CASE
         WHEN t.email IS NOT NULL
         THEN 'true' ELSE 'false'
      END
    ) AS found
FROM (
  SELECT 'dog' AS email
  UNION
  SELECT 'frog' AS email
  UNION
  SELECT 'cat' AS email
  UNION
  SELECT 'tiger' AS email
  UNION
  SELECT 'lizard' AS email
) AS search_emails
LEFT JOIN
 t
ON
 t.email = search_emails.email

Result
| email  | found |
| ------ | ----- |
| dog    | true  |
| cat    | true  |
| tiger  | true  |
| frog   | false |
| lizard | false |

see demo

A: select emails from table where email in (dog, frog, cat, tiger, lizard) OR email IS NULL

be sure that the values provided for IN (...) are provided as strings.


text:
Q: Apache Telnet Client does not recevie non-ASCII characters I've been trying to useorg.apache.commons.net.telnet.TelnetClient and I am having trouble to receive non-ASCII characters (in my case polish chars like ą,ę,ć,ź and few others). The problem is not on server side - when I use default Ubuntu telnet implementation or Putty I have no problem receiving non-ASCII characters. My code looks something like this (simplified a bit for readability):
    TelnetClient telnetClient = new TelnetClient();
    telnetClient.connect("169.254.24.223", 23);

    while (true) {
        int readCharInt = telnetClient.getInputStream().read();
        if (readCharInt != -1) {
            String s = String.valueOf((char) readCharInt);
            System.out.print(s);
        } else {
            System.out.println("EOS");
            break;
        }
    }

I used Wireshark to take a closer look. When using the Apache telnet client, packets do not contain non-ASCII characters at all, and while using default Ubuntu telnet they do contain them:
Apache telnet
Default ubuntu telnet
I've been wondering if the Apache client turns on some mode for the server to send only characters that can be encoded on 7 bits. I've tried several terminal types or to subnegotiate binary transmission but without success:
int[] msg = {TelnetCommand.DO,TelnetOption.BINARY};
telnetClient.sendSubnegotiation(msg);

A: I'm not sure why sub negotiation does not work but I found a workaround.
Try to add SimpleOptionHandler with option 0 (BINARY) to TelnetConnection. It will cause that this option will be enabled from the start.
TelnetClient tc = new TelnetClient();
// 1st param 0 means BINARY option
SimpleOptionHandler simpleOptionHandler = new SimpleOptionHandler(0, true, false, true, false);
tc.addOptionHandler(ttopt);


text:
Q: how to write a test class for trigger for sending mail ?plz help me out! trigger LeaveUpdatetrigger on Leave__c (after update,before delete) {

    if(trigger.isInsert || trigger.isUpdate){
        for(Leave__c lv : trigger.new){
            Leave__c lev = [Select Name,EmployeeName__r.Name from Leave__c where EmployeeName__c =:lv.EmployeeName__c limit 1];
            EmailTemplate et = [SELECT Id,Subject,HtmlValue, Body FROM EmailTemplate WHERE DeveloperName =:'Update_to_Hr_on_Leave_modification'];
             system.debug('--EmailTemplate--'+et);
            String body = et.HtmlValue;
            body = body.replace('{!Leave__c.EmployeeName__c}',lev.EmployeeName__r.Name);
            Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
            mail.toAddresses = new String[] { 'saudsyed20@gmail.com' };
                mail.setSubject(et.subject);
            mail.setHtmlBody(body);

            mail.setplainTextBody(et.body);
            // mail.setTargetObjectIds(lv.id);
            mail.setTemplateId('00X2v000001H9oK'); //Id of the Email Template
            Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
        }
    }
     if(Trigger.isBefore || trigger.isdelete){
        for(Leave__c lv : trigger.old)
        {
            Leave__c lev = [Select Name,EmployeeName__r.Name from Leave__c where EmployeeName__c =:lv.EmployeeName__c limit 1];

            EmailTemplate et = [SELECT Id,Subject,HtmlValue, Body FROM EmailTemplate WHERE DeveloperName =:'Update_to_HR_on_Leave_deletion'];
            //system.debug('--EmailTemplate--'+et);
            String body1 = 'TEST';
            String body =et.HtmlValue;
            body = body.replace('{!Leave__c.EmployeeName__c}',lev.EmployeeName__r.Name);
            Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
            mail.toAddresses = new String[] { 'saudsyed20@gmail.com' };
                mail.setSubject(et.subject);
            mail.setHtmlBody(body);
            mail.setplainTextBody(et.body);
          mail.setTemplateId('00X2v000001H9oe');//Id of the Email Template
            Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
        }
    }
}

A: Fields need to be assigned, whichever trigger you use,
you can write class like this or also you can look there:
https://trailhead.salesforce.com/en/content/learn/modules/apex_testing/apex_testing_triggers
OR
https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_code_coverage_intro.htm
FOR EXAMPLE:
@isTest
public class ProcessSurveyTestClass {

    Static testmethod void MyTest(){
        ProcessSurvey__c Pss = new ProcessSurvey__c();
    Pss.CariKodu__c = 'MSO2455';
    Pss.Email__c = 'blabla@blabla.com';
    insert Pss;
    }
}


text:
Q: NASM Instruction segment conflicting override Unlike the others, I did use some proper segment registry (such like ds and es), but I still got a 'Instruction has conflicting segment overrides' error.
 And here's my code:
mov byte [es:di],[ds:si]
What's wrong with it?
(By the way, don't tell me to use movsb or movsw. I tried and they did not work the way I want.)


text:
Q: Regex to parse a simple odata query I'm trying to create a regex to parse the following 2 strings
Country eq 'United States' and Value eq 1234.45M and CreatedOn eq '2013-06-05T06:04:23.2111146Z'
Value eq 1234.45M and Status eq 'Active' and CategoryID eq 1 and Country eq 'United States'

Basically these are OData query strings specified in $filter.
Note that this is for providing limited Odata support and hence the example strings have only eq and and.
This is what I have so far
(\w+)\seq\s\'{0,1}([0-9a-zA-Z,*=@#$&()-_+=!]*)\'{0,1}

This works for the most part except that when I have a space in a quoted string such as
'United States' (note the space between United and States), it picks up only 'United
I tried adding a \s to the range of characters to capture like so
(\w+)\seq\s\'{0,1}([0-9a-zA-Z,*\s=@#$&()-_+=!]*)\'{0,1}

but this throws the captured groups out of whack since the string itself can contain spaces to separate the name and value (Value eq 1234) <-- Note the spaces separating the Value and eq
Any guidance in fixing/recreating the regex above would be most appreciated.
UPDATE:I also need to support additional filter operations such as ('or','startswith','endswith','substringof').
Example:
$filter = Country eq 'United States' and Value eq 1234.45M and substringof('Alfreds', CompanyName) eq true or startswith(CompanyName, 'Alfr') and endswith(CompanyName, 'Futterkiste')

A: You can match it with this regex
(\w+)\s*eq\s*'?([^']*)'?(?=\s*and|$)

Your code would be
var lst=Regex.Matches(input,regex)
                      .Cast<Match>()
                      .Select(x=>
                            new
                             {
                                 name=x.Groups[1].Value,
                                 value=x.Groups[2].Value
                             });

Now you can iterate over lst
foreach(var v in lst)
{
    v.name;
    v.value;
}

A: Try using this regex:
(\w+\seq\s'?[\w\s\.\:\-]+'?)(?= and |$)

Look for the example here.
I am expecting a typo in your sample data:

Country eq 'United States' and Value eq 1234.45M and CreatedOn eq
  '2013-06-05T06:04:23.2111146Z' and  Value eq 1234.45M and Status
  eq 'Active' and CategoryID eq 1 and Country eq 'United States'

A: Please try this regex:
(\w+)\seq\s\'?([^\']+)\'?

A: I think you should do this in two parts (Sorry for pseudocode, the question was at the beginning in general, and I'm not a .net guy (But I tested it in php)) :
input = "Country eq 'United States' and Value eq 1234.45M and CreatedOn eq '2013-06-05T06:04:23.2111146Z'"
splitted = split ("and", input);

And then do what I assumed was a replacement (because of capturing groups) :
foreach (splitted as s) {
    print (regex.replace ("#(\w+)\seq\s(.*)\s?$#", '$1 = $2', s));
}

In case php is easier to understand than my pseudocode, here is the code :
$string = "Country eq 'United States' and Value eq 1234.45M and CreatedOn eq '2013-06-05T06:04:23.2111146Z'";
$splitted = explode ('and', $string);

$regex = "#(\w+)\seq\s(.*)\s?$#";
foreach ($splitted as $s) {
    echo preg_replace ($regex, '$1 = $2<br />', $s);
}


text:
Q: Matching number except 1 and 0 How I can get all number except first 0 and 1, for example from 043241.124.22, I need to get 43241.24.22.
I have written code
Pattern p = Pattern.compile("[2-9]");
String[] split = number.split("\\.")
String n = "";
Matcher m = p.matcher(split[0])
m.find();
n += split[0].substring(matchere.start()) + "."
....

but I think it can do by one or two line

A: Use replaceAll(), scanning for a 0 or 1 digit leading other digits, i.e.

*

*a 0 or 1 digit: [01]

*not preceded by a digit: (?<=^|\D) or (?<!\d)

*and followed by at least one digit: (?=\d)
Regex to find those is: (?<=^|\D)[01](?=\d)
Java code is:
String n = number.replaceAll("(?<=^|\\D)[01](?=\\d)", "");

See IDEONE for working code.

A: You should use  loop. Hope this will help.
Pattern p = Pattern.compile("[2-9]");
String[] split = number.split("\\.");
String n = "";
for(int i=0;i<split.length;i++)
{
Matcher m = p.matcher(split[i]);
m.find();
n += split[i].substring(m.start())+".";

}
System.out.println(n);


text:
Q: Returning all possible vertex coloring combinations in Python I am required to write a method three_color(graph) that will take a graph in as an input, and return all possible vertex colorings of the graph, including those that are invalid. We are representing graphs using dictionaries, and the  output should be a list of dictionaries.
three_color({"A" : ["B"], "B" : ["A"]}) should return

{"A" : 1, "B" : 1}, {"A" : 1, "B" : 2}, {"A" : 1, "B" : 3}, {"A" : 2, "B" : 1}, {"A" : 2, "B" : 2}, {"A" : 2, "B" : 3}, {"A" : 3, "B" : 1}, {"A" : 3, "B" : 2}, {"A" : 3, "B" : 3}

I'm having issues coming up with a solution on how to write this method, as we are not allowed to use any libraries aside from copy to help us.
I'm new to python, so I'm not sure if there is a simple solution I am overlooking. And assistance, or guidance, is greatly appreciated.
This is what I've been trying to work with:
def three_color(graph):
    vertices = []
    colorings = []
    color = {}
    for key in graph:
        vertices.append(key)
    for v in vertices:
        color[v] = 1
    colorings.append(copy.copy(color))

    for v in vertices:
        for v2 in vertices:
            for i in range(1,4):
                for j in range(1,4):
                    color[v] = i
                    color[v2] = j
                    colorings.append(copy.copy(color))

    #Get rid of duplicates
    new_c = []
    for c in colorings:
        if c not in new_c:
            new_c.append(c)

    return new_c

I'm aware this is completely wrong, but I cannot think through these for loops properly.

A: Because this is a homework question, I'll give a pseudocode solution, and you can implement it yourself, and hopefully learn more that way.
I'm partial to recursion, so I'll use it in this solution.
take a graph as an argument:
    if the graph is empty, return the graph
    recursively color all the elements except the first, store the result as "tail"
    store the first element of the list as "head"
    for every element of tail, refered to as "element":
        add "head, color 1" + element to a final results list
        add "head, color 2" + element to a final results list
        add "head, color 3" + element to a final results list
    return final results


text:
Q: Pode me ajudar a otimizar essa consulta SQL? Eu estou tendo um problema com essa consulta sql. O tempo de retorno dela ta sendo em media 10 segundos e ta usando 100% da cpu. Provavelmente por que ela usa muitas subquery. Porem eu não estou conseguindo otimizar ela. Alguem tem alguma ideia de q caminho posso seguir ?
SELECT id_post, midia, texto, tb_usuario.id, tb_usuario.nome, user, avatar, tipo, tb_comm_post.id_categoria, tb_comm_post.data_criacao, tb_comm_categorias.nome, cor1, cor2,
    (SELECT COUNT(*) FROM tb_liked_comunidade WHERE tb_liked_comunidade.id_post = tb_comm_post.id_post AND flag = 1) as n_like,
    (SELECT COUNT(*) FROM tb_liked_comunidade WHERE tb_liked_comunidade.id_post = tb_comm_post.id_post AND flag = -1) as n_dislike,
    (SELECT flag FROM tb_liked_comunidade WHERE tb_liked_comunidade.id_usuario = ? AND tb_liked_comunidade.id_post = tb_comm_post.id_post) as flag,
    (SELECT COUNT(*) FROM tb_comentario_comunidade WHERE tb_comentario_comunidade.id_post = tb_comm_post.id_post) as n_comentarios
    FROM tb_comm_post
    JOIN tb_usuario ON tb_usuario.id = tb_comm_post.id_autor
    JOIN tb_comm_categorias ON tb_comm_post.id_categoria = tb_comm_categorias.id_categoria
    WHERE tb_comm_post.exibir = 1
    ORDER BY tb_comm_post.data_criacao DESC
    LIMIT 5 OFFSET ?

Onde ta o ponto de interrogação "?" é que o dado vem na hora da execução da query

A: O motivo da lentidão é que para cada linha do seu select você está executando 4 selects. Imagine você executar 4 subselect vezes 10mil linhas...
Eu criaria uma procedure, ou incluiria essas etapas na procedure existente:
...

DECLARE

a NUMBER;
b NUMBER;
c NUMBER;
d NUMBER;

BEGIN

a:= (SELECT COUNT(*) FROM tb_liked_comunidade WHERE tb_liked_comunidade.id_post = tb_comm_post.id_post AND flag = 1) as n_like,
b:= (SELECT COUNT(*) FROM tb_liked_comunidade WHERE tb_liked_comunidade.id_post = tb_comm_post.id_post AND flag = -1) as n_dislike,
c:= (SELECT flag FROM tb_liked_comunidade WHERE tb_liked_comunidade.id_usuario = ? AND tb_liked_comunidade.id_post = tb_comm_post.id_post) as flag,
d:= (SELECT COUNT(*) FROM tb_comentario_comunidade WHERE tb_comentario_comunidade.id_post = tb_comm_post.id_post) as n_comentarios

SELECT
a AS n_like,
b AS n_dislike,
c AS flag,
d AS n_comentarios,
id_post, midia, texto, tb_usuario.id, tb_usuario.nome, user, avatar, tipo,
tb_comm_post.id_categoria, tb_comm_post.data_criacao, tb_comm_categorias.nome, cor1, cor2

FROM tb_comm_post

INNER JOIN tb_usuario
    ON tb_usuario.id = tb_comm_post.id_autor

INNER JOIN tb_comm_categorias
    ON tb_comm_post.id_categoria = tb_comm_categorias.id_categoria

WHERE tb_comm_post.exibir = 1

ORDER BY tb_comm_post.data_criacao DESC

LIMIT 5 OFFSET ?

END

...

É possível resolver esse problema também com tabela temporário e cruzar informando que 1 é igual a 1 (ON 1=1) para repetir todos os dados de uma tabela com a outra.

A: Complementando a respota do @alguém.
Quando falamos de otimização precisamos entender o tempo de consulta que cada tabela possui, pois cada tabela existe um certa quantidade de dados reais e podemos medir o quanto ela pode crescer no futuro. Por sua vez não somente uma query bem feita poderá surtir um efeito positivo. A solução da otimização pode ser diferente dependendo do ambiente que você se encontra hoje, pois talvez a criação de novas tabelas relacionais podem surtir um melhor efeito.
Uma boa solução, que já vi em alguns projetos é criar index nas tabelas e usar os indexex no select, acredito que o tempo de consulta será bem mais eficiente.
Exemplo:
SELECT CAMPO
FROM TABELA T WITH (INDEX(INDEX_NOMETABELAINDEXADA))
INNER JOIN OUTRA_TABELA OT
WITH (INDEX(OUTRO_INDICE))
ON OT.ID = T.ID


text:
Q: Vector names error Im trying to set names for a vector using the function names, but R gives me an error. I want to create a vector with function and then set name for each number in that vector. I want to do all this step by writing just one order (for example v(x)). This is example of my code script
v <- c(2,6,5)
d <- function(x) x*9

names(d(x))<-paste("q=", 1:3, sep="")

and R says

Error in names(d(x)) <- paste("q=", 1:3, sep = "") :
    could not find function "d<-"

A: I don't really know what you are doing, but assuming this approximates it I can reproduce the error:
qn <- 1:11

div_1 <- function(x) { x <- x + 1 }
div_2 <- function(x) { x <- x + 2 }

div<- function(x) c(div_1(x)[1],div_2(x),div_1(x)[2:10])
x <- 1
names(div(x))<- paste("q=", qn, sep="" )
# Error in names(div(x)) <- paste("q=", qn, sep = "") :
#  could not find function "div<-"

and I can fix it with this (breaking it into two steps):
qn <- 1:11

div_1 <- function(x) { x <- x + 1 }
div_2 <- function(x) { x <- x + 2 }

div<- function(x) c(div_1(x)[1],div_2(x),div_1(x)[2:10])

x <- 1

v <- div(x)
names(v)<- paste("q=", qn, sep="" )

# q=1  q=2  q=3  q=4  q=5  q=6  q=7  q=8  q=9 q=10 q=11
# 2    3   NA   NA   NA   NA   NA   NA   NA   NA   NA

It may be a bug, or a limitation in assigning names to a temporary variable (note that the result gets thrown out in your version). Out of curiousity, what are you doing with div?


text:
Q: pyspark rdd map is not calling function
I am trying to do few transformations on my RDD and for that, I am calling a function using map. However, this function is not getting invoked. Someone please let me know what I am doing wrong here?
I can see test function getting invoked but not store_past_info
def store_past_info(row):
    print "------------------- store_past_info  ------------------------------"

    if row["transactiontype"] == "Return":
        global prv_transaction_number
        prv_transaction_number = row["transnumber"]
        global return_occured
        return_occured = True
        global group_id
        group_id.append(row["transnumber"])

    if row["transactiontype"] == "Purchase":
            if return_occured:
                global group_id
                group_id.append(prv_transaction_number)
            else:
                global group_id
                group_id.append(row["transnumber"])

    print group_id

def test(rdd):
    print "------------------- test  ------------------------------"
    rdd.map(store_past_info).collect()
    print group_id

This is how it works in store:

*

*if some item is purchased an id is generated.

*if you want to return few items from your purchase, two entries are been made

*

*Return entry with new id for the return of all the products, with org_id as id of your purchase order you want to return

*New Purchase entry with the same id as your last purchase id for things you want to keep

Input
Date        Type        Id      org_id
25-03-2018  Purchase    111
25-03-2018  Purchase    112
26-03-2018  Return      113     111
26-03-2018  Purchase    111

Output
I want to add a new column group_id, which will show the same id for Return and Corresponding Purchase happened after return ( customer don't do this purchase, this is how system keeps entry for every return) step 2.1
Date        Type        Id      org_id  group_id
25-03-2018  Purchase    111             111
25-03-2018  Purchase    112             112
26-03-2018  Return      113     111     113
26-03-2018  Purchase    111             113

A: IIUC, I believe you can get your output using DataFrames, a pyspark.sql.Window function, and crossJoin()
First convert your rdd to a DataFrame using
df = rdd.toDF()  # you may have to specify the column names
df.show()
#+----------+--------+---+------+
#|      Date|    Type| Id|org_id|
#+----------+--------+---+------+
#|25-03-2018|Purchase|111|  null|
#|25-03-2018|Purchase|112|  null|
#|26-03-2018|  Return|113|   111|
#|26-03-2018|Purchase|111|  null|
#+----------+--------+---+------+

Then we will need to add an Index column to keep track of the order of the rows. We can use pyspark.sql.functions.monotonically_increasing_id(). This will guarantee that the values will be increasing (so they can be ordered), but does not mean that they will be sequential.
import pyspark.sql.functions as f
df = df.withColumn('Index', f.monotonically_increasing_id())
df.show()
#+----------+--------+---+------+-----------+
#|      Date|    Type| Id|org_id|      Index|
#+----------+--------+---+------+-----------+
#|25-03-2018|Purchase|111|  null| 8589934592|
#|25-03-2018|Purchase|112|  null|17179869184|
#|26-03-2018|  Return|113|   111|34359738368|
#|26-03-2018|Purchase|111|  null|42949672960|
#+----------+--------+---+------+-----------+

The ordering is important because you want to look for rows that come after a Return.
Next use crossJoin to join the DataFrame to itself.
Since this returns the Cartesian product, we will filter it to just the rows that meet either of the following conditions:

*

*l.Index = r.Index (essentially join a row to itself)

*(l.Id = r.org_id) AND (l.Index > r.Index) (an Id is equal to a org_id from an earlier row- this is where the Index column is helpful)

Then we add a column for group_id and set it equal to r.Id if the second condition is met. Otherwise we set this column to None.
df1 = df.alias('l').crossJoin(df.alias('r'))\
    .where('(l.Index = r.Index) OR ((l.Id = r.org_id) AND (l.Index > r.Index))')\
    .select(
        'l.Index',
        'l.Date',
        'l.Type',
        'l.Id',
        'l.org_id',
        f.when(
            (f.col('l.Id') == f.col('r.org_id')) & (f.col('l.Index') > f.col('r.Index')),
            f.col('r.Id')
        ).otherwise(f.lit(None)).alias('group_id')
    )
df1.show()
#+-----------+----------+--------+---+------+--------+
#|      Index|      Date|    Type| Id|org_id|group_id|
#+-----------+----------+--------+---+------+--------+
#| 8589934592|25-03-2018|Purchase|111|  null|    null|
#|17179869184|25-03-2018|Purchase|112|  null|    null|
#|34359738368|26-03-2018|  Return|113|   111|    null|
#|42949672960|26-03-2018|Purchase|111|  null|     113|
#|42949672960|26-03-2018|Purchase|111|  null|    null|
#+-----------+----------+--------+---+------+--------+

We are almost there but as you can see there are two things that still need to be done.

*

*We need to eliminate the duplicate row for Index = 42949672960

*We need to fill in the group_id for rows where it is null using the value from Id.

For the first step, we will use a Window function to create a temporary column called rowNum. This will be the pyspark.sql.functions.row_number() for each Index ordered by the boolean condition group_id IS NULL.
For the Index values where there are multiple rows, the one where the group_id has already been set will sort first. Thus we just need to select the rows where the rowNum is equal to 1 (row_number() starts at 1, not 0).
After this is done, the second step is trivial- just replace the remaining null values with the value from Id.
from pyspark.sql import Window
w = Window.partitionBy(f.col('Index')).orderBy(f.isnull('group_id'))
df2 = df1.withColumn('rowNum', f.row_number().over(w))\
    .where(f.col('rowNum')==1)\
    .sort('Index')\
    .select(
        'Date',
        'Type',
        'Id',
        'org_id',
        f.when(
            f.isnull('group_id'),
            f.col('Id')
        ).otherwise(f.col('group_id')).alias('group_id')
    )

df2.show()
#+----------+--------+---+------+--------+
#|      Date|    Type| Id|org_id|group_id|
#+----------+--------+---+------+--------+
#|25-03-2018|Purchase|111|  null|     111|
#|25-03-2018|Purchase|112|  null|     112|
#|26-03-2018|  Return|113|   111|     113|
#|26-03-2018|Purchase|111|  null|     113|
#+----------+--------+---+------+--------+


text:
Q: Using histogram info in scatter plot Is there a way to color scatter plot markers based on histogram bins into which given value has been placed?
Having following example data:
df = pd.DataFrame({
    'length': [1.5, 0.5, 1.2, 0.9, 3],
    'width': [0.7, 0.2, 0.15, 0.2, 1.1],
    'price': [12, 9, 2, 1, 10]})

I can print histogram with hist = df.hist(bins=3, column='price') as well as scatter plot with df.scatter.plot(x='length', y='width').
But I cannot figure out a way to combine both of those instructions. What I'd expect to see is have 3 colors on scatter plot and colors will be assigned based on bin where give value fits.
Any idea how this can be achieved?

A: The following approach first creates a colormap with 3 colors, and uses the price column to define the color. The scatter plot will add a colorbar indicating the relation between the colors and the prices.
import matplotlib.pyplot as plt
import pandas as pd`
import numpy as np

df = pd.DataFrame({
    'length': [1.5, 0.5, 1.2, 0.9, 3],
    'width': [0.7, 0.2, 0.15, 0.2, 1.1],
    'price': [12, 9, 2, 1, 10]})
num_colors = 3
cmap = plt.get_cmap('rainbow', num_colors)
df.plot.scatter(x='length', y='width', c='price', cmap=cmap)
plt.tight_layout()
plt.show()

PS: If you want to indicate the price borders, you can add these as colorbar ticks:
ax = df.plot.scatter(x='length', y='width', c='price', cmap=cmap)
ax.collections[0].colorbar.set_ticks(np.linspace(df['price'].min(), df['price'].max(), num_colors + 1))

A: The histogram is just taking the range of values, and splitting it into equal size bins.
You can do this by using pd.cut() to assign points into specific bins:
import pandas as pd
df = pd.DataFrame({
    'length': [1.5, 0.5, 1.2, 0.9, 3],
    'width': [0.7, 0.2, 0.15, 0.2, 1.1],
    'price': [12, 9, 2, 1, 10]
})
df['price'] = pd.cut(df['price'], bins=3)
df.plot.scatter(x='length', y='width', c='price', colormap='viridis')

Example output:


text:
Q: Round 12.01 to 13 Decimal Value = " 19500.98"
I need to display this value to TextBox with rounded off like "19501"
If decimal value = " 19500.43"
then
Value = "19501"
If decimal value comes +1 is add.

A: Just try below code:
decimal convertDecimal = decimal.Parse("19500.43", CultureInfo.InvariantCulture);
decimal ceiling = Math.Ceiling(convertDecimal );

For more information:

*

*DotnetPerls on Math.Ceiling

*MSDN

A: try this on:
decimal value = 1500.98M;
decimal newvalue = Math.Ceiling(value);


text:
Q: Trying to edit init.el to customize emacs So I'm relatively new in trying to customize emacs. But I really need to customize is asap. Tabs are a pain in emacs as they are two spaces, and the text is all messed up when it is opened with any other editor after that.
Currently, I only have few lines in my ~/emacs.d/init.el file:
(setq load-path (concat (getenv "HOME") "/.emacs.d/"))

(set-scroll-bar-mode 'right)

(require 'linum)
(global-linum-mode t)

I get an error while starting up emacs:
Loading encoded-kb...done

An error has occurred while loading `/Users/mycomp/.emacs.d/init.el':

Symbol's function definition is void: set-scroll-bar-mode

To ensure normal operation, you should investigate and remove the
cause of the error in your initialization file.  Start Emacs with
the `--debug-init' option to view a complete error backtrace.

I tried srtating it with the --debug-init option, but my lisp knowledge is not enough to help me figure out what's wrong. Any help on how to get this working or redirecting me to some GOOD tutorials on editing init.el files will be really helpful (yes i did google tutorials on editing the initialization file, but every one of them was terrible).
I'm assuming my code for getting line numbers on the left is also wrong. Could someone please help me with this? Thanks a lot.

A: I think this line may be the problem:
(setq load-path (concat (getenv "HOME") "/.emacs.d/"))

First of all, I don't think this is required to load ~/emacs.d/init.el. Secondly, if you do want to add a directory to your load-path, you should probably be doing it like this instead:
(add-to-list 'load-path "~/.emacs.d/")

This code adds the directory to the load-path, your code just clobbers it with the single directory.

A: Use 'M-x apropos' and 'M-x customize-apropos'. For now, those will make your life much easier when you want to customize things.
For instance, to customize things to do with scrolling, 'M-x customize-apropos RET scroll RET' will give you a list of all things that you can customize that have 'scroll' in them. You can look around and find the things that you want by searching the buffer. If you find a particular thing that you want, there's usually a group that it belongs to. You can click on that, and just customize those particular values. Make sure you save the settings.
It might take you a while to figure out what things are called. If you've got an idea, try the apropos search. If that doesn't turn up anything, google can probably sort it out for you.
For now, don't worry about hacking the elisp. This method will write values to your startup file (probably the .emacs?) and you can look and check the syntax later if you're really interested. I customize most of my stuff this way; I only bother actually modifying the file by hand when I'm trying to write my own hooks or functions.


text:
Q: The congruence $\,x^2+1\equiv 0\pmod{99}$ is unsolvable $x^2+1\equiv 0 \mod 99$
I rearranged the congruence to get $x^2\equiv -1 \mod 99$.
We have an isomorphism $\ \mathbb{Z}/99\mathbb{Z}\to\mathbb{Z}/ 3 \mathbb{Z}\times\mathbb{Z}/3\mathbb{Z}\times\mathbb{Z}/11\mathbb{Z}$.
Solving modulo $3$ first, $\ x^2\equiv -1 \mod 3$.
We find that there are no solutions. Likewise for $x^2\equiv -1\mod 11$.
Therefore $x^2+1\equiv 0 \mod 99$ has no solutions.
Is this correct?

A: It is correct, but redundant. You are already done when you show it is unsolvable mod $3.\,$ Indeed, if it is solvable mod $99$ then $\, 3\mid 99\mid x^2+1\,\Rightarrow\, x^2\equiv -1\equiv 2\pmod 3,\,$ which contradicts $\,x\equiv 0,1,\,$ or $\,2\Rightarrow x^2\equiv 0\,$ or $\,1$. There is no need to go further and show it's unsolvable mod $11.$
More generally a quadratic is unsolvable $\bmod n$ if its discriminant is nonsquare $\!\bmod n.\,$ Here $\,x^2+1\equiv 0\,$ has discriminant $\,b^2-4ac = 0^2\!-4(1)1\equiv -4\equiv 2\equiv$ nonsquare $\!\bmod 3\,$ as above.
Further, $\,\Bbb Z/9 \cong \Bbb Z/3 \times \Bbb Z/3\,$ is false, since the latter satisfies $\,3x = 0\,$ but the former does not.

A: Hints:
$$x^2=-1\pmod{99}\implies x^2=-1\pmod{11}$$
But $\;11\neq1\pmod 4\;$ ...


text:
Q: Have table view content go above or below main area I am currently developing an app which as a need for a box with some information above a table view. Unfortunately, I can not create the required behaviour with a standard UINavigationBar or a UIToolBar. I have instead created a UIEffectView with a blur background and placed this above my table view.
As you can see from this example in Apple's Stocks app, the table view content extends below the main visible area of the table view creating a nice blur effect.

My question is how can I recreate this whilst keeping the table view have a correct bottom and top area (if I just placed the blur view above the table view you would not be able to scroll to the bottom or top correctly, it would be obscured by the blur view).

A: Drop a UIView as header on the top of UITableview cell Using IB. and set the height of the UIView Equal to your CustomNavigationBar View.
header view will hide under your CustomNavigationBar view and Cell start from the bottom of navigationBar


text:
Q: change parent element from iframe not working? Can anyone advise why this code isn't working when I click the link?
The link is in an iframe and I want the link to toggle a menu in the Main page.
<script>
$(document).ready(function() {
 quickout = 0;
 $("#scrollsetting").click(function(){
    if (quickout==0){
    window.parent.document.getElementById('quickmenu').show(300);
    quickout = 1;
    } else {
    window.parent.document.getElementById('quickmenu').hide(300);
    menuout=0;
    }
 })
});
</script>

A: The jQuery selectors do not select elements in other windows naturally, you have to either access the jQuery in the other window to query its DOM or pass a reference to the other window's document so jQuery can find what you're looking for.
First approach, querying the element inside the iframe's window with the jQuery inside the iframe, and the one in parent window with the parent window's jQuery:
$(document).ready(function () {
    $("#scrollsetting").click(function () {
        window.parent.$('#quickmenu').toggle(300);
    });
});

Fiddle
Though, it is not always necessary to load jQuery twice, so let's say you just loaded it in the parent window, you can then use the parent's jQuery with a context selector setting it to the current document, while it still defaults to the parent window's document when omitted:
var $ = window.parent.$;
$(document).ready(function () {
    $("#scrollsetting", document).click(function () {
        $('#quickmenu').toggle(300);
    });
});

Fiddle
Likewise, if for some reason you'd have jQuery solely in the children window, use a context selector when referencing the parent window's document:
$("#scrollsetting").click(function () {
    $('#quickmenu', window.parent.document).toggle(300);
});

Fiddle
ps. Don't mind my inject wrapper. It is just a way to write code in a readable manner before injecting its text into the iframe in the form of an IIFE - my string concatenation implicitly calls Function.toString().
Of course, if you have other dependencies/plugin that absolutely require jQuery included in the framed page, you can go with the first solution which is the simplest, or whichever you find more suitable.
ps2. If any reader has a problem trying this code in your pages, remember that iframes are subject to the same origin police. That is, you can't access an iframe when its src's domain,  protocol or port doesn't match the parent document's, and the same for the other way around.


text:
Q: Can Google maps functions be loaded without loading the map? I have a site where I'm using Maps Javascript API to print several polygons to the screen and manage hover/click events, but I don't need to see the underlying map. At the moment I've just styled all of the map elements to white, and it works, but I'd rather eliminate the requests, since it's currently downloading ~40 seperate blank white squares.
Happy to try a different plugin / API if it works, but I had a look for alternate applications without much luck.


text:
Q: Google Drive SDK: Next step after obtaining a token from generateAssertion() Alright, I'm trying to set my application up with with the Google Drive SDK. I am using it as a service account, so the set up is a little different. This is how I am doing things:
including required files:
require_once 'google-api-php-client/src/Google_Client.php';
require_once 'google-api-php-client/src/auth/Google_AssertionCredentials.php';
require_once "google-api-php-client/src/contrib/Google_Oauth2Service.php";

define constants:
DEFINE("TRUE_PATH",$_SERVER["DOCUMENT_ROOT"].'path/to/file');
DEFINE("SERVICE_ACCOUNT_EMAIL","somecode@developer.gserviceaccount.com");
DEFINE("DRIVE_SCOPE","https://www.googleapis.com/auth/drive");

the function:
function generateAssertion() {

    $assertionCredentials = new Google_AssertionCredentials();

    $assertionCredentials->serviceAccountName='somecode@developer.gserviceaccount.com';

    $assertionCredentials->privateKey=
    TRUE_PATH.'9e01fd1414aa082fadeec316161eb7028558fbde-privatekey.p12';

    $assertionCredentials->privateKeyPassword = 'notasecret';
    $p12cert = array();
    $file = TRUE_PATH.'9e01fd1414aa082fadeec316161eb7028558fbde-privatekey.p12';
    if (file_exists($file)) {
        try {
            $assertion = $assertionCredentials->generateAssertion();
            return $assertion;
        } catch (Exception $e) {
            d($assertionCredentials);
            return 'Caught exception: ' . $e->getMessage() . "\n";
        }
    } else {
        return "no p12 privatekey file";
    }
}

the line $assertion = $assertionCredentials->generateAssertion(); gives me a code that loooks like this:
eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJhdWQiOiJodHRwczpcL1wvYWNjb3VudHMuZ29vZ2xlLmNvbVwvb1wvb2F1dGgyXC90b2tlbiIsInNjb3BlIjpudWxsLCJpYXQiOjEzNTMzNjk3NzUsImV4cCI6MTM1MzM3MzM3NSwiaXNzIjoiMjY5Mjg1NDU2NjY0QGRldmVsb3Blci5nc2VydmljZWFjY291bnQuY29tIn0.KMBTsGZkhLhddBFtc0PB1qZgtdQYyirhWtYixCYx1zo5Otv9pCUBfvrCXOg3JzR-mzE6zHuCZdmGOD7w_LRwYHJpoo0rdpxDXLjtNCgFZdu1d21cVAnqTkIhMGvdS_K7JP_KioXyi-nBdvZt9IXKaApIdDKhRp-T5HByIeO2ijU
my question is, what do I do with the code/token returned from generateAssertion() so that I can access my drive account?
I tried using it as an access token and a refresh token with no success.
I apologize if this is a stupid question, but I am new to the sdk
Any help will be greatly appreciated.
Thank you!!!

A: You don't need to call generateAssertion(). Rather, just give the credentials to the client instance and let it do the work of generating the assertion
$client = new Google_Client();
$client->setAssertionCredentials($assertionCredentials);

See http://code.google.com/p/google-api-php-client/wiki/OAuth2 for additional details.


text:
Q: Excel DATEDIF function issue I used the DATEDIF function in excel to calculate no. of days between 2 dates, but it is giving the result in another date format like 03-01-1900

I tried changing the formatting of the cell to general and number, but in both the cases, the date looks like a number in the excel, which i dont want


text:
Q: Limit the total number of emails per domain / per hour / per day I have Windows 2008 Server with Mail Enable Free edition with plesk 9.5. What I want is to limit each domain with total number of emails per hour / per day to avoid spam.
I know it's possible in Mail Enable Ent. Version, which is not free. (I don't want to pay right now). Is this possible or do I have to use any other script?
Is this possible in hMailserver?

A: There is no pre-made and free solution to this at the moment, sadly.
MailEnable should provide this feature without having to buy the enterprise edition but at the moment it seem to be the only option.
Unless MailEnable ever allow us to build a license "à la carte", custom scripts parsing logs are the only way to do this.


text:
Q: Как получить имя элемента и его родителя при обнаружении ошибок и несоответствия xsd-схеме в xml файле? Есть код для проверки XML файла по XSD-схеме:
public static void ValidateAgainstSchema(string XMLSourceDocument, XmlSchemaSet validatingSchemas)
    {
        if (validatingSchemas == null)
        {
            throw new ArgumentNullException("In ValidateAgainstSchema: No schema loaded.");
        }

        string errorHolder = string.Empty;
        ValidationHandler handler = new ValidationHandler();

        XmlReaderSettings settings = new XmlReaderSettings();
        settings.CloseInput = true;
        settings.ValidationType = ValidationType.Schema;
        settings.ValidationEventHandler += new ValidationEventHandler(handler.HandleValidationError);
        settings.Schemas.Add(validatingSchemas);
        settings.ValidationFlags =
            XmlSchemaValidationFlags.ReportValidationWarnings |
            XmlSchemaValidationFlags.ProcessIdentityConstraints |
            XmlSchemaValidationFlags.ProcessInlineSchema |
            XmlSchemaValidationFlags.ProcessSchemaLocation;

        StringReader srStringReader = new StringReader(XMLSourceDocument);

        XmlReader validatingReader = XmlReader.Create(srStringReader, settings);

        try
        {
            while (validatingReader.Read())
            {
            }
        }
        catch (XmlException ex)
        {
            Console.WriteLine("XMLException occurred: " + ex.Message);
        }

        if (handler.MyValidationErrors.Count > 0)
        {
            foreach (String messageItem in handler.MyValidationErrors)
            {
                errorHolder += messageItem;
            }
            //throw new XmlSchemaValidationException(errorHolder);
        }
        Console.WriteLine(errorHolder);}

public class ValidationHandler
{
    private IList<string> myValidationErrors = new List<String>();
    public IList<string> MyValidationErrors { get { return this.myValidationErrors; } }

    public void HandleValidationError(object sender, ValidationEventArgs ve)
    {
        if (ve.Severity == XmlSeverityType.Error || ve.Severity == XmlSeverityType.Warning)
        {
            this.myValidationErrors.Add(
                String.Format(
                    Environment.NewLine + "Line: {0}, Position {1}: \"{2}\"",
                    ve.Exception.LineNumber,
                    ve.Exception.LinePosition,
                    ve.Exception.Message)
            );
        }
    }
}

который выводит слудующую инфу об ошибках в xml-файле:

Line: 4, Position 20: "Элемент "foo" имеет недопустимый дочерний элемент "baz". Список ожидаемых элементов: "bar"."
Line: 13, Position 20: "Элемент "foo" имеет недопустимый дочерний элемент "baz". Список ожидаемых элементов: "bar"."

Как видно, благодаря свойствам LineNumber, LinePosition можно получить инфу о позиции каждой ошибки, но как получить имя элемента xml, в котором обнаружена ошибка, а также имя его родителя?

A: Чтобы было легче воспринимать, я упростил код до следующего:
using System;
using System.Collections.Generic;
using System.Xml;
using System.Xml.Schema;

namespace ConApp1
{
    class Program
    {
        static Stack<string> stack = new Stack<string>();
        static string previous;
        static int depth;

        static void Main(string[] args)
        {
            try
            {
                var schemaSet = new XmlSchemaSet();
                schemaSet.Add("", "test.xsd");

                var settings = new XmlReaderSettings();
                settings.ValidationType = ValidationType.Schema;
                settings.ValidationEventHandler += Settings_ValidationEventHandler;
                settings.Schemas.Add(schemaSet);

                using (var reader = XmlReader.Create("test.xml", settings))
                {
                    while (reader.Read())
                    {
                        if (reader.NodeType != XmlNodeType.Whitespace)
                        {
                            previous = reader.Name;
                        }
                        if (reader.NodeType == XmlNodeType.Element)
                        {
                            if (depth == reader.Depth)
                            {
                                stack.Push(reader.Name);
                                depth++;
                            }
                        }
                        else if (reader.NodeType == XmlNodeType.EndElement)
                        {
                            stack.Pop();
                            depth--;
                        }
                    }
                }
            }
            catch (Exception e) { Console.WriteLine(e.Message); }
        }

        private static void Settings_ValidationEventHandler(object sender, ValidationEventArgs e)
        {
            Console.WriteLine(string.Join(", ", stack));
            Console.WriteLine(previous);

            Console.WriteLine("Line: {0}, Position {1}: \"{2}\"",
                    e.Exception.LineNumber, e.Exception.LinePosition, e.Exception.Message);
        }

    }
}

Здесь в поле previous запоминается имя элемента, непосредственно предшествующего тому, в котором произошла ошибка валидации.
А в стеке хранятся все родительские элементы, от текущего до корня.
Аналогичным образом можно сохранять в коллекции любую необходимую информацию.

Для такого xml:
<?xml version="1.0"?>
<root>
  <foo>
    <bar/>
    <bar/>
  </foo>
  <foo>
    <bar/>
    <bar/>
  </foo>
</root>

была создана такая схема:
<?xml version="1.0" encoding="utf-8"?>
<xs:schema attributeFormDefault="unqualified" elementFormDefault="qualified" xmlns:xs="http://www.w3.org/2001/XMLSchema">
  <xs:element name="root">
    <xs:complexType>
      <xs:sequence>
        <xs:element maxOccurs="unbounded" name="foo">
          <xs:complexType>
            <xs:sequence>
              <xs:element maxOccurs="unbounded" name="bar" />
            </xs:sequence>
          </xs:complexType>
        </xs:element>
      </xs:sequence>
    </xs:complexType>
  </xs:element>
</xs:schema>

Если теперь внести ошибку: заменить последний элемент bar на baz, получим следующий вывод:

bar, foo, root
  bar

То есть мы имеем все родительские элементы и предыдущий элемент.


text:
Q: Branch wise Post-Commit hook in svn I have created CI using SVN(windows), Jenkins and Chef.
One of my project currently gets polled in Jenkins from post-commit hook and code from Trunk gets uploaded to local server using Chef. Now we have UAT server on Azure and we need to upload code only once or twice a week. So will create a branch UAT and when developer wants to upload code to UAT Server, he will merge the trunk to UAT branch.
I will create a different Job in Jenkins and would trigger it from post-commit hook. Creating another job would get me another CURL command.
Now how do I call that particular CURL command from my post commit hook if UAT Branch got check-in/merge by developer.
Below is my post-commit.bat
SET REPOS=%1
SET REV=%2
SET SVNLOOK="C:\Program Files\VisualSVN Server\bin\svnlook.exe"
SET PROJECT=PROJECT_NAME

curl "http://10.0.0.16:8080/job/PROJECT_NAME/build?token=123" // For Local-server

I'm not that good in coding so not sure if I should be using IF-ELSE or something else. And do I implement that.


text:
Q: php set my own timezone based on given GMT offset I've my GMT offset in seconds. I would like to set_default_time_zone() to that GMT offset. What I mean that if I have my GMT offset to 2 hours(7200 seconds) it will set the timezone to GMT+2 if I have 3 hours(10800 seconds) it will set the timezone to GMT+3, how can I do that? the set_default_time_zone() only accept pre-defined timezones strings.

A: You can use GMT offsets, but you must use the Etc prefix. The following works:
date_default_timezone_set('Etc/GMT+5');

But this is discouraged an deprecated, see here: http://php.net/manual/en/timezones.others.php
Also, I personally would recommend not to work with offsets, because there are many pitfalls in date/time handling where GMT offsets can cause bad results (e.g. DST, first day of the week).
It is generally recommended to work with UTC internally, and set local times to the geographical timezone instead of the GMT offset.


text:
Q: How to overcome a keyError in roman numeral converter? I feel confident that the logic of the code is correct, however, I come across keyError: 0.
def romanToInt(s: str) -> int:
    roman_table = {"I": 1, "V": 5, "X": 10, "L": 50, "C": 100, "D": 500, "M": 1000}
    result = 0

    for numeral in range(len(s)):
        if (
            numeral + 1 < len(s)
            and roman_table[s[numeral]] < roman_table[s[numeral + 1]]
        ):
            result -= roman_table[numeral]
        else:
            result += roman_table[numeral]

    return result

romanToInt("MCMXCIV")```

Below is the error in the terminal

```$ python to_roman_numeral_converter.py
Traceback (most recent call last):
  File "C:Users\XYZ\dev\repos\roman_numeral\to_roman_numeral_converter.py", line 14, in <module>
    romanToInt("MCMXCIV")
  File "C:\Users\XYZ\dev\repos\roman_numeral\to_roman_numeral_converter.py", line 6, in romanToInt
    if numeral + 1 < len(s) and roman_table[numeral] < roman_table[numeral + 1]:
KeyError: 0

Not sure why it is not recognising roman_table value [numeral]?
Any help here is appreciated.

A: I manged to find out the problem
def romanToInt(s: str) -> int:
    roman_table = {"I": 1, "V": 5, "X": 10, "L": 50, "C": 100, "D": 500, "M": 1000}
    result = 0

    for numeral in range(len(s)):
        if (
            numeral + 1 < len(s)
            and roman_table[s[numeral]] < roman_table[s[numeral + 1]]
        ):
            result -= roman_table[s[numeral]]
        else:
            result += roman_table[s[numeral]]

    return result

romanToInt("MCMXCIV")

I was not accessing the value S


text:
Q: jQuery append to variable I would like to append all values from a table to a variable (then the variable will be added to a field).
I don't manage to do that, so for now my solution has been to create an intermediary field :
var field = $('textarea');

$("#table .row").each(function () {
  value = $(this).find('input').val() + '
';
  field.val(field.val() + value);
});

var myfinalvariable = othervariable + 'content' + field.val();

This works, but it obliged me to create a textarea field just for this purpose. Ideally, i'd just like to get rid of it by creating a variable that would replace field.val(). I tried many things, for example :
var content = '';

$("#table .row").each(function () {
  value = $(this).find('input').val() + '
';
  var content = $(content) + value;
});

var myfinalvariable = othervariable + 'randomtext' + content;

Is there a problem with the syntax of with the logic ? I also tried .append() but with no success.
Thank you !


text:
Q: Where do I find googlemaps.MapContainer to import for the Ratatouilles Restaurant demo? I am trying to run the Ratatouilles Restaurant demo.  Where do I find the googlemaps.MapContainer to import.

A: This demo uses the GoogleMaps.cn1lib that is in the lib directory, to use this right click on your project and select "CodenameOne->Refresh cn1lib files" then rebuild the project


text:
Q: Running Junit Email Tests Without Emails Actually Going Out I want to run unit tests (Junit) on some model classes that typically will send emails confirming that things happened.  Is there a mock email server that you can use with unit tests that will let you confirmation that your run tried to send an email without actually sending the emails out?
This seems like it would be a nice to have, just not sure I want to write my own.  The app stack for the emailing aspect is Velocity+Spring, so it would be preferable if the test server can be pointed at by simply changing the applicationContext.xml file.

A: Dumbster is a fake SMTP server designed for testing against.  It's written in Java.

A: I assume you're using Javamail and the problem is that javax.mail.Session is final and therefore can't be mocked.
Seems like others have suggested you simply define your own 'mail session' interface and create an implementation that uses Javamail.  In your tests you then simply inject a mock while in 'real-world-mode' you inject the Javamail implementation.
Both JMock and EasyMock will support all the assertions you might want to make on the message you are sending and you testing is complete.
As an aside, I generally try to avoid any out-of-process calls from within unit tests - it kills you when you're running the test suite frequently, which normally translates into it being run less and that's code base issues start to occur.

A: I think the Mock JavaMail project is what you want.

A: I would take a look to GreenMail which is alive (apparently Dumbster is dead) with a lot of functionality and good examples.
http://www.icegreen.com/greenmail/

A: You can try JavaMail Mock2 https://github.com/salyh/javamail-mock2
Its primarily focused on IMAP/POP3 but SMTP Mock is also available. Its available in maven central.
Features

*

*Support imap, imaps, pop3, pop3s, smtp, smtps

*Supported for POP3: cast to POP3Folder, Folder.getUID(Message msg)

*Supported for IMAP: cast to IMAPFolder, cast to UIDFolder, Subfolders, -Folder.getMessagesByUID(...), delete/rename folders, append messages

*Support for SMTP: Mock Transport.send()

*Unsupported for the moment: IMAP extensions like IDLE, CONDSTORE, ... and casts to POP3Message/IMAPMessage, store listeners

A: Phil Haack has a blog post about unit testing email sending, with a solution he coded around a freeware mail server.

A: My solution was to wrap the mail server in a class which takes all the config options and has a send() method. In my tests, I'd mock this class and override send() with something that saves the current parameters for the assert.
To test that the mail service itself works, send yourself a mail locally. Try hMail if you're on Windows.