text:
Q: how to return several response instead of only once to spider in scrapy selenium middleware I am using the python scrapy framework to crawl car info on below page:
https://youjia.baidu.com/view/carDatabase?title=%E7%8E%B0%E4%BB%A3&key=code&val=174&sa=pc_growth_1

but this page is using something like infinite scroll technique to automatically loads json when you scroll down on the page. Every page 25 results, for different car brand page, the qty is different, so sometimes it needs to separate the results into 1~3 pages by scrolling down.
So I was wondering that maybe I can integrate some codes into the selenium middleware as below:
from scrapy import signals
from selenium import webdriver
from scrapy.http.response.html import HtmlResponse
import random
import time

class SeleniumDownloadMiddleware(object):
def __init__(self):
    # self.driver = webdriver.Chrome()
    self.driver = webdriver.Firefox()

def process_request(self,request,spider):
    self.driver.get(request.url)
    time.sleep(1)
    source = self.driver.page_source
    response = HtmlResponse(url=self.driver.current_url,body=source,request=request,encoding='utf-8')

    return response

    SCROLL_PAUSE_TIME = 2
    last_height = driver.execute_script("return document.body.scrollHeight")
    while True:
        driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
        time.sleep(SCROLL_PAUSE_TIME)
        source = self.driver.page_source
        response = HtmlResponse(url=self.driver.current_url, body=source, request=request, encoding='utf-8')
        return response

        # Calculate new scroll height and compare with last scroll height
        new_height = driver.execute_script("return document.body.scrollHeight")
        if new_height == last_height:
            break
        last_height = new_height

but the problem is this middleware only return response once, so the spider.py only parse once.
How can I modify this snippet to realize 1~3 times return?


text:
Q: What is the difference between declaration of module with and without variable in angularJs? correct me If I am wrong..
--Setting a module
    var app = angular.module("myapp", []);

// here brackets means module does't exist just go and create it, and the empty array is the list of module it depends on
--Getting a module
    var app = angular.module("myapp");

//and if brackets are not here mean module exist just find it.
but what is the difference between below lines:-
  var myapp = angular.module("myapp", []);
  myapp.controller("MyController", "$scope", [function($scope){
    //TODO
  }]);

  and

  angular.module("myapp", [])
  .controller("MyController", "$scope", [function($scope){
    //TODO
  }]);

I think we should use variable only if our module is divided in multiple files.
but I am not sure if it will really makes any difference.
As per Angular Style Guide we should not use variable while declaring a module.Could anyone please clarify?
Thanks

A:
--Setting a module
var app = angular.module("myapp", []);`

Here brackets means module does't exist just go and create it, and the empty array is the list of module it depends on
--Getting a module
var app = angular.module("myapp");`

// and if brackets are not here mean module exist just find it.

Correct

we should not use variable while declaring a module.Could anyone please clarify

When you write: var myapp = angular.module("myapp", []); you are creating the variable myapp in the global scope.

I think we should use variable only if our module is divided in multiple files

That's not necessary. You can always get your module with angular.module("moduleName");, avoiding thus the creation of a global variable.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Unity3D Rotation not behaving as expected I am trying to make a small demo for a simulation and I thought this part was going to be easy. Boy was I wrong and now I am totally stuck. Here is my problem.
I am trying to work with rotation and for this issue we will work with a 30 degree angle which is shown below:

The green ray is -15 degrees, red is 0 degrees and blue is +15 degrees for a total of 30 degrees.
Now I want to divide said 30 degrees into equalish parts so the first good number would be 10. meaning I can draw a ray every 3 degrees until I hit my maximum which in this case is +15 degrees. This can be seen below:

Looks good! There is a small amount of space that is off and if anyone knows why that is please let me know.
Now, I need a large amount of rays so we are going to go up by a factor of 10 and increase the number of divisions to 100 which can be seen below. Also I need to use imgur because there are only two pictures allowed here so please bear with me and thank you.
https://imgur.com/a/cWDdj
The first picture is with 100 chunks and as you can see the rays are all cast to the left. That is a problem.
The second picture is with the divisions increased to 1000. Even worse now is the fact that the got all the way around the object except for a 15 degree area.
Here is the snippet that is doing this.
 if(testRotation)
 {
      //Sets the objects rotation to the starting rotation which is -15 degeres
      this.transform.Rotate(this.transform.rotation.x, this.transform.rotation.y - 15.0f,
           this.transform.rotation.z);

      for (int i = 0; i <= 10; i++)
      {
           //Draws a ray at the current position and forwards relative to the objects transform
           Debug.DrawRay(this.transform.position,
           this.transform.forward * maxSightDistance, Color.cyan, 1000.0f);

           //This advances the rotation by a factor of one chunk
           //which in this case is 10 which seems to work
           this.transform.Rotate(new Vector3(this.transform.rotation.x,
           this.transform.rotation.y + (30/10), this.transform.rotation.z));
      }

      //This makes it so it doesn't run forever
      testRotation = false;

 }

The only places that change are in the for loop where the conditional is checked and also the second parameter of the Rotate function which adds to the current rotational value by "one chunk".
For 100 chunks I modify the pieces to: for(int i = 0; i < 100; i++) and this.transform.rotation.y + (30/100)
For 1000 chunks I modify the pieces to: for(int i = 0; i < 1000; i++) and this.transform.rotation.y + (30/1000)
I am totally stuck and don't know why it's is doing what it's doing. Also if you need something explained or clarified please let me know !

A: You dividing a number by an integer, which will return an integer. You instead need to divide by a float to return a decimal number.
i.e.
this.transform.rotation.y + (30/100f)
this.transform.rotation.y + (30/1000f)

Edit: Additionally, the components of rotate should be 0 instead of their previous value to avoid accumulation of rotation.
transform.Rotate(new Vector3(0, 30/10f, 0));


text:
Q: How to check the object type on runtime in TypeScript? I'm trying to find a way to pass an object to function in and check it type in a runtime. This is a pseudo code:
function func (obj:any) {
    if(typeof obj === "A") {
        // do something
    } else if(typeof obj === "B") {
        //do something else
    }
}

let a:A;
let b:B;
func(a);

But typeof always returns "object" and I could not find a way to get the real type of a or b. instanceof did not work either and returned the same.
Any idea how to do it in TypeScript?

A: "I'm trying to find a way to pass an object to function in and check it type in a runtime".
Since a class instance is just an object, the "native" answer is to use a class instance and instanceof when runtime type checking is needed, use an interface when not in order to keep a contract and decouple your application, make reduce signature size on methods/ctors, while not add any additional size. In my humble opinion this is one of a few main considerations for me in TypeScript when deciding to use a class vs type/interface. One other main driving factor is whether the object will ever need to be instantiated vs if it for instance defines a POJO.
In my codebase, I will typically have a class which implements an interface and the interface is used during compilation for pre-compile time type safety, while classes are used to organize my code and allow for ease in passing data between functions, classes and method as well as do runtime type checks in typescript.
Works because routerEvent is an instance of NavigationStart class
if (routerEvent instanceof NavigationStart) {
  this.loading = true;
}

if (routerEvent instanceof NavigationEnd ||
  routerEvent instanceof NavigationCancel ||
  routerEvent instanceof NavigationError) {
  this.loading = false;
}

Will not work
// Must use a class not an interface
export interface IRouterEvent { ... }
// Fails
expect(IRouterEvent instanceof NavigationCancel).toBe(true);

Will not work
// Must use a class not a type
export type RouterEvent { ... }
// Fails
expect(IRouterEvent instanceof NavigationCancel).toBe(true);

As you can see by the code above, classes are used to compare the instance to the types NavigationStart|Cancel|Error within the Angular library and if you have used the router before you a project I am willing to be that you have done similar if not identical checks within your own codebase in order to determine application state during runtime.
Using instanceof on a Type or Interface is not possible, since the ts compiler  strips away these attributes during its compilation process and prior to being interpreted by JIT or AOT. Classes are a great way to create a type which can be used pre-compilation as well as during the JS runtime.
Update 2022
In addition to my original response to this, you can leverage The TypeScript Reflect Metadata API or roll your own solution using the TypeScript compiler to do static analysis of your code and parse the AST, querying like so:
switch (node.kind) {
  case ts.SyntaxKind.InterfaceDeclaration:
    // ...
    break;
  case ts.SyntaxKind.TypeDeclaration:
    // ...
    break;
}

See this solution for additonal details

A: Expanding on Aaron's answer, I've made a transformer that generates the type guard functions at compile time. This way you don't have to manually write them.
For example:
import { is } from 'typescript-is';

interface A {
  foo: string;
}

interface B {
  bar: number;
}

if (is<A>(obj)) {
  // obj is narrowed to type A
}

if (is<B>(obj)) {
  // obj is narrowed to type B
}

You can find the project here, with instructions to use it:
https://github.com/woutervh-/typescript-is

A: I've been playing around with the answer from Aaron and think it would be better to test for typeof instead of just undefined, like this:
interface A {
  foo: string;
}

interface B {
  bar: number;
}

function isA(obj: any): obj is A {
  return typeof obj.foo === 'string'
}

function isB(obj: any): obj is B {
  return typeof obj.bar === 'number'
}

function func(obj: any) {
  if (isA(obj)) {
    console.log("A.foo:", obj.foo);
  }
  else if (isB(obj)) {
    console.log("B.bar:", obj.bar);
  }
  else {console.log("neither A nor B")}
}

const a: A = { foo: 567 }; // notice i am giving it a number, not a string
const b: B = { bar: 123 };

func(a);  // neither A nor B
func(b);  // B.bar: 123

A:
Edit: I want to point out to people coming here from searches that this question is specifically dealing with non-class types, ie object
  shapes as defined by interface or type alias. For class types you
  can use JavaScript's instanceof to determine the class an instance comes from, and TypeScript will narrow the type in the type-checker automatically.

Types are stripped away at compile-time and do not exist at runtime, so you can't check the type at runtime.
What you can do is check that the shape of an object is what you expect, and TypeScript can assert the type at compile time using a user-defined type guard that returns true (annotated return type is a "type predicate" of the form arg is T) if the shape matches your expectation:
interface A {
  foo: string;
}

interface B {
  bar: number;
}

function isA(obj: any): obj is A {
  return obj.foo !== undefined
}

function isB(obj: any): obj is B {
  return obj.bar !== undefined
}

function func(obj: any) {
  if (isA(obj)) {
    // In this block 'obj' is narrowed to type 'A'
    obj.foo;
  }
  else if (isB(obj)) {
    // In this block 'obj' is narrowed to type 'B'
    obj.bar;
  }
}

Example in Playground
How deep you take the type-guard implementation is really up to you, it only needs to return true or false. For example, as Carl points out in his answer, the above example only checks that expected properties are defined (following the example in the docs), not that they are assigned the expected type. This can get tricky with nullable types and nested objects, it's up to you to determine how detailed to make the shape check.

A: No, You cannot reference a type in runtime, but yes you can convert an object to a type with typeof, and do validation/sanitisation/checks against this object in runtime.
const plainObject = {
  someKey: "string",
  someKey2: 1,
};
type TypeWithAllOptionalFields = Partial<typeof plainObject>; //do further utility typings as you please, Partial being one of examples.

function customChecks(userInput: any) {
  // do whatever you want with the 'plainObject'
}

Above is equal as
type TypeWithAllOptionalFields = {
  someKey?: string;
  someKey2?: number;
};
const plainObject = {
  someKey: "string",
  someKey2: 1,
};
function customChecks(userInput: any) {
  // ...
}

but without duplication of keynames in your code

A: You can call the constructor and get its name
let className = this.constructor.name

A:
I know this is an old question and the "true" question here is not the
same as the question in the title, but Google throws this question for
"typescript runtime types" and some people may know what they are
looking for and it can be runtime types.
Right answer here is what Aaron Beall answered, the type guards.
But answer, matching question in the title and matching Google
searches, is only usage of TypeScript transformers/plugins. TypeScript
itself strip out information about types when transpiling TS to JS.
And well,.. it is one of the possible ways how to implement the type guards,
eg. the typescript-is transformer as user7132587 pointed out.

Another options is transformer tst-reflect. It provides all the information about types at runtime. It allows you to write own type guards based on type information, eg. checking that object has all the properties you expect. Or you can use directly Type.is(Type) method from the transformer, which is based directly on the TypeScript's type checking information.
I've created this REPL. Have a fun!
More info in Github repository.
import { getType, Type } from "tst-reflect";

class A {
  alphaProperty: string;
}

interface B {
  betaProperty: string;
}

class Bb extends A implements B {
  betaProperty = "tst-reflect!!";
  bBetaProperty: "yes" | "no" = "yes";
}

/** @reflectGeneric */
function func<TType>(obj?: TType)
{
    const type: Type = getType<TType>();

    console.log(
      type.name,
      "\n\textends", type.baseType.name,
      "\n\timplements", type.getInterface()?.name ?? "nothing",
      "\n\tproperties:", type.getProperties().map(p => p.name + ": " + p.type.name),
      "\n"
    );

    console.log("\tis A:", type.is(getType<A>()) ? "yes" : "no");
    console.log("\tis assignable to A:", type.isAssignableTo(getType<A>()) ? "yes" : "no");
    console.log("\tis assignable to B:", type.isAssignableTo(getType<B>()) ? "yes" : "no");
}

let a: A = new A();
let b: B = new Bb();
let c = new Bb();

func(a);
func<typeof b>();
func<Bb>();

Output:
A
    extends Object
    implements nothing
    properties: [ 'alphaProperty: string' ]

    is A: yes
    is assignable to A: yes
    is assignable to B: no
B
    extends Object
    implements nothing
    properties: [ 'betaProperty: string' ]

    is A: no
    is assignable to A: no
    is assignable to B: yes
Bb
    extends A
    implements B
    properties: [ 'betaProperty: string', 'bBetaProperty: ' ]

    is A: no
    is assignable to A: yes
    is assignable to B: yes

A: You should use a separate dynamic typing library that allows you to define custom types with dynamic type information and track it's compliance to the expected type.
The best solution that allows you this is this amazing library: https://github.com/pelotom/runtypes
Using it, you can define a meta-type for your A and B types:
const AType = Record({foo: Number})
const BType = Record({baz: String})

This is pure TS, and you can note that we are creating constant objects, not static types. Also, we are using Number and String objects provided by the library, and not the TS static types of number and string.
Then, you create the static type declarations for A and B:
type A = Static<typeof AType>
type B = Static<typeof BType>

Now, these types are proper Typescript static types. They contain all the proper members that you passed during the creation of the meta-type, up to the infinite depth of objects. Arrays, objects, optionals, faulsy values, scalar types are all supported.
Then you can use this like this:
function asdf(object: any): A | undefined {
    try {
        const aObject = AType.check(object) // returns A if complies with Record definition, throws otherwise
        return aObject
    } catch {
        return undefined
    }
}

asdf({ foo: 3 }) // returns A, literally the same object since it passed the check
asdf({ bar: "3" }) // returns undefined, because no `foo` of type `number`
asdf({ foo: "3" }) // returns undefined, because `foo` has wrong type

This is the most modern, serious solution that works and scales beautifully.

A: You should use the "in" operator to narrow down. Reference
type Fish = { swim: () => void };
type Bird = { fly: () => void };

function move(animal: Fish | Bird) {
  if ("swim" in animal) {
    return animal.swim();
  }

  return animal.fly();
}

A: Alternative approach without the need of checking the type
What if you want to introduce more types? Would you then extend your if-statement? How many such if-statements do you have in your codebase?
Using types in conditions makes your code difficult to maintain. There's lots of theory behind that, but I'll save you the hazzle. Here's what you could do instead:
Use polymorphism
Like this:
abstract class BaseClass {
    abstract theLogic();
}

class A extends BaseClass {
    theLogic() {
       // do something if class is A
    }
}

class B extends BaseClass {
    theLogic() {
       // do something if class is B
    }
}

Then you just have to invoke theLogic() from whichever class you want:
let a: A = new A();
a.theLogic();

let b: B = new B();
b.theLogic();


text:
Q: Running nativescript with angular application on iPhone SE I am developing mobile app by using nativescript with angular. The issue I am facing is that when I run my app on physical iPhone SE, it becomes over heat and sometimes I didn't see anything on my screen. When I tested with another version iPhone7 and iPhone6, it's ok. If you have some experiences with that please share me.
Thanks & Best Regards,
Zaw Zaw Naing


text:
Q: regular expression for number and spaces in the end I am trying to validate some forms and what I want to have is a regular expression that will allow numbers and spaces. The expression will not allow
1000 space space 00

but it will allow something like
space space space 10000

or
1000 space space space

I have tried this, but it's not what I want:
var filter = /^[0-9 ]+$/;
if(price.val() == "")
    alert('vide');
else if(filter.test(price.val()))
    alert('number');
else
    alert('no number');

Hope you can help me.

A: You could try
var filter = /^\s*[0-9]+\s*$/;

\s is the whitespace character. You can replace it with  if you only want to specifically check for spaces.

A: You can use a regex like this:
^\s*\d+\s*$

Working demo

Regex explanation from Hwnd tool:
^                        the beginning of the string
\s*                      whitespace (\n, \r, \t, \f, and " ") (0 or
                         more times)
\d+                      digits (0-9) (1 or more times)
\s*                      whitespace (\n, \r, \t, \f, and " ") (0 or
                         more times)
$                        before an optional \n, and the end of the
                         string

A: Hope this pattern helps ^ *[0-9]+ *$


text:
Q: convert a matrix from non-square to square with different column names I have a matrix
> dput(m1)
structure(c(1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 2L, 3L, 4L, 5L,
6L, 7L, 8L, 9L, 4L, 5L, 6L), .Dim = 5:4, .Dimnames = list(c("A",
"B", "C", "D", "E"), c("col1", "col2", "col3", "col4")))

I want to convert my matrix to a square one by adding dummy columns or rows (whichever is missing) that are filled with 1
What I expect to get:
structure(c(1, 2, 3, 4, 5, 6, 7, 8, 9, 2, 3, 4, 5, 6, 7, 8, 9,
4, 5, 6, 1, 1, 1, 1, 1), .Dim = c(5L, 5L), .Dimnames = list(c("A",
"B", "C", "D", "E"), c("col1", "col2", "col3", "col4", "anyname")))

A: sqmat <- function(m) {
  while (ncol(m) < nrow(m)) {
    m <- cbind(m, anyname = 1)
  }
  while (nrow(m) < ncol(m)) {
    m <- rbind(m, anyname = 1)
  }
  return(m)
}

This could lead to duplicate row/column names, which you might not want. You could keep track of an index and rename later ...

A: Here is a function that can help -
make_symmetric_matrix <- function(m) {
  nr <- nrow(m)
  nc <- ncol(m)
  if(nc > nr) {
    m <- rbind(m, matrix(1, nrow = nc - nr, nc = nc))
  } else if(nr > nc) {
    m <- cbind(m, matrix(1, nrow = nr, nc = nr - nc))
  }
  m
}

Some test cases to check -
#on the original matrix
make_symmetric_matrix(m1)

#  col1 col2 col3 col4
#A    1    6    3    8 1
#B    2    7    4    9 1
#C    3    8    5    4 1
#D    4    9    6    5 1
#E    5    2    7    6 1

test_mat <- matrix(c(1, 2, 3, 3, 4 ,5), ncol = 3)

#     [,1] [,2] [,3]
#[1,]    1    3    4
#[2,]    2    3    5

make_symmetric_matrix(test_mat)
#     [,1] [,2] [,3]
#[1,]    1    3    4
#[2,]    2    3    5
#[3,]    1    1    1

test_mat <- matrix(c(1, 2, 3, 3, 4 ,5), ncol = 6)

#     [,1] [,2] [,3] [,4] [,5] [,6]
#[1,]    1    2    3    3    4    5

make_symmetric_matrix(test_mat)

#     [,1] [,2] [,3] [,4] [,5] [,6]
#[1,]    1    2    3    3    4    5
#[2,]    1    1    1    1    1    1
#[3,]    1    1    1    1    1    1
#[4,]    1    1    1    1    1    1
#[5,]    1    1    1    1    1    1
#[6,]    1    1    1    1    1    1

A: We could first rename the column names and
then we could  create a NA matrix (learned here How to convert a non-square matrix to a square matrix with R?
To work: this code must fulfill the assumptions stated by akrun in his answer!
then test with is.square.matrix() function from matrixcalc package.
# Rename column names
colnames(m1) <- LETTERS[1:4]

# Use this code
un1 <- unique(sort(c(colnames(m1), rownames(m1))))
m2 <- matrix(NA, length(un1), length(un1), dimnames = list(un1, un1))
m2[row.names(m1), colnames(m1)] <- m1
m2

# Output:
  A B C D  E
A 1 6 3 8 NA
B 2 7 4 9 NA
C 3 8 5 4 NA
D 4 9 6 5 NA
E 5 2 7 6 NA

# Test if is a square matrix:
#install.packages("matrixcalc")
library(matrixcalc)
is.square.matrix(m2)

#Output:
[1] TRUE


text:
Q: Angular token based authentication, get and store the user profile, best practice I started some months ago to build my first token-based authentication for an Angular project and now I need to upgrade it. Until now my /login endpoint returned just a token which is stored in the local storage. The user is logged in when the token is present and valid.
But now I need also to display the username in the navigation bar and the user role because I need to create a role guard.
I read a lot of articles and questions/answer about this topic but I'm really confused which is the best way to get the user profile.
Get

*

*Get the user details directly at the login together with the token

*Exactly after login, if login request is successful, execute another request for example: /me

*Add the username and the role in the token payload

Store
Also the details should be persistent(if the user close and open the browser), How can I store them? Should I use the a storage(local storage/cookie)? Or execute a request each time when the user open the application?
Use
Here I don't have any clue. If I use the storage, should I read them every time? Or should I use a subject?
From your experience which is the best way to do it? Or do you have other ideas?
Thanks in advance!

A: I am dealing with this, I hope to help you.

*

*The api/login repsonse like this:

{
  token: 'your token...',
  expireAt: 'token expire time',
  user: {
    name: 'admin',
    role: 'master'
    // ... else user info
  }
}

*Use localStorage save the token and user info. You can get the token info from local storage when you open the same website in next time, and determine if you need to re-login based on the expiration time.

*cookie should not save complex or large data structure, becase it:

*

*Inconvenient operation

*Size is limited

*Every time http request has to take


text:
Q: Java / Groovy : Find XML node by Line number Below is my groovy code to validate XML schema aginst an XSD
import java.io.File;
import java.io.IOException;

import javax.xml.XMLConstants;
import javax.xml.transform.stream.StreamSource;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
import javax.xml.validation.Validator;
import javax.xml.transform.sax.SAXSource
import javax.xml.parsers.SAXParserFactory
import org.xml.sax.SAXException
import org.xml.sax.InputSource
import org.xml.sax.SAXParseException
import org.xml.sax.ErrorHandler

def validateXMLSchema(String xsdPath, String xmlPath) {
    final List < SAXParseException > exceptions = new LinkedList < SAXParseException > ();
     try {
      SchemaFactory factory =
       SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
      Schema schema = factory.newSchema(new File(xsdPath));
      Validator validator = schema.newValidator();
      validator.setErrorHandler(new ErrorHandler() {
       @Override
       public void warning(SAXParseException exception) throws SAXException {
        exceptions.add(exception);
       }

       @Override
       public void fatalError(SAXParseException exception) throws SAXException {
        exceptions.add(exception);
       }

       @Override
       public void error(SAXParseException exception) throws SAXException {
        exceptions.add(exception);
       }
      });
      def xmlFile = new File(xmlPath);
      validator.validate(new StreamSource(xmlFile));
      exceptions.each {
       println 'lineNumber : ' + it.lineNumber + '; message : ' + it.message
      }
     } catch (IOException | SAXException e) {
      println("Exception: line ${e.lineNumber} " + e.getMessage());
      return false;
     }
     return exceptions.size() == 0;
}

Below are some of the validation errors, I can access the line number for each message and am trying to find the corresponding node name
lineNumber : 106; message : cvc-datatype-valid.1.2.1: '' is not a valid value for 'date'.
lineNumber : 248; message : cvc-enumeration-valid: Value 'Associate' is not facet-valid with respect to enumeration '[ADJSTR, ADJSMT]

Is there a simple way to find the Node name for corresponsding error message usinng the line number? Or do I have to read that specific line and parse it using XmlSlurper like below(trying to avoid this approach since it will be slower for larger XML files in production with heavy user load)?
def getNodeName(xmlFile, lineNumber){
  def xmlLine =  xmlFile.readLines().get(lineNumber)
  def node = new XmlSlurper().parseText(xmlLine.toString())
  node.name()
}

A: This is not elegant but the following getNodeName() should be faster (full example here):
def getNodeName(xmlFile, lineNumber) {
    def result = "unknown"
    def count = 1
    def NODE_REGEX = /.*?<(.*?)>.*/
    def br

    try {
        br = new BufferedReader(new FileReader(xmlFile))
        String line
        def isDone = false
        while ((! isDone) && (line = br.readLine()) != null) {
            if (count == lineNumber) {
                def matcher = (line =~ NODE_REGEX)
                if (matcher.matches()) {
                    result = matcher[0][1]
                }
                isDone = true
            }
            count++
        }
    } finally {
        // TODO: better exception handling
        br.close()
    }

    return result
}

It simply reads lines until the line in question and then uses a rudimentary regular expression to get the name. You could potentially use XmlSlurper as in your example if preferred. The key thing is that the file IO/memory should be considerably less.


text:
Q: Presenting an image cropping interface I'm trying to engineer a UI for cropping images in iphone OS and suspect I'm going about things the hard way. My goal is pretty much what the Tapbots duo have done with Pastebot. In that app, they dim the source image but provide a movable and resizable cropping view and the image you're cropping is in a zoomable scrollview; when you resize or move the underlying image, the cropping view adjusts appropriately.
I mocked up a composite image which will give a sense of the design I'm after, along with how I presently have my view hierarchy setup.
alt text http://grab.by/3TN4
The approach I've started with is the following: UIImageView with the image to crop is in a scrollview, a plain UIView with black fill and suitable transparency/alpha setting is added in front of the imageview. I then use a custom UIView which is a sibling to the scrollview at a higher level, which implements the drawRect: method and for the most part calls CGImageCreateWithImageInRect to get the portion of the image's bitmap that matches the position of the cropping view and draws that to the CGContext.
in the viewcontroller I'm using the UIScrollViewDelegate methods to track scrolling and passing those changes to the custom cropping UIView so it stays in sync with the scroll contentOffset. That much is finally working. But trying to keep in sync as the scrollview zoomScale changes is when I figured I should ask for help.
Looking for suggestions or guidance. My initial approach just seems like more work than is required.
Could this be done with a masking layer in the ImageView? And if so, how would I setup the tracking for moving and resizing the cropping rect? My experience working with layers is non-nil, but very limited thus far.

A: I have found that often a better UI for cropping results if you think of manipulating the position and size (and even rotation) of an image underneath a simple, immovable mask or cropping rect rather than trying to move a mask or cropping rect on top of an unmoving image. This is especially true of you always want the cropped image to have a preset proportion and orientation.

A: For record's sake - A ready made component on Cocoa Controls
http://cocoacontrols.com/platforms/ios/controls/imagecropper


text:
Q: How to correctly write my relationship/associations in Rails? I have 4 Models and i am not sure what is the correct way to write my relationships/associations.
class User < ActiveRecord::Base
  has_many :boards
  has_many :lists
  has_many :cards
end

class Board < ActiveRecord::Base
 belongs_to :user
 has_many :lists
end

class List < ActiveRecord::Base
  belongs_to :user
  belongs_to :board
  has_many :cards
end

class Card < ActiveRecord::Base
  belongs_to :user
  belongs_to :list
end

A: If you want to be more explicit about your relationships, feel free to do the following (preferred in most every case):
class User < ActiveRecord::Base
  has_many :boards, inverse_of: :user, dependent: :destroy
  has_many :lists, inverse_of: :user, dependent: :destroy
  has_many :cards, inverse_of: user, dependent: :destroy
end

class Board < ActiveRecord::Base
 belongs_to :user, inverse_of: :boards
 has_many :lists, inverse_of: :board
end

class List < ActiveRecord::Base
  belongs_to :user, inverse_of: :lists
  belongs_to :board, inverse_of :lists
  has_many :cards, inverse_of :list
end

class Card < ActiveRecord::Base
  belongs_to :user, inverse_of: :cards
  belongs_to :list, inverse_of :cards
end

Finally, make sure any of your models that are dependent on another (e.g. Board belongs_to User) have the appropriate foreign key in their table. So, for example, Board will need to have a user_id foreign key to correctly create the association.
You can create a migration for any of those entities if you haven't already like so:
rails generate migration AddUserRefToBoards user:references


text:
Q: Maximo- Update work order using RESTApi by passing wonum and siteid instead of workorderid We are currently on Maximo 7.6.1 and have started to use Restful APIs and was wondering if there is a way to update a work order using RESTApi by passing wonum and siteid instead of workorderid.
We would like to avoid one additional GET call for our middleware to retrieve the workorderid and then use it in the PUT request.
Using this URL (OS as well)  tries to insert a record even though the HTTP method is PUT.
/maxrest/rest/mbo/WORKORDER?_action=AddChange&siteid=XXX&wonum=7065644&description=Testing
Any pointers will be helpful.
Thanks

A: The IBM documentation appears to suggest you can only update existing records with the unique ID:

Use the PUT method to update or insert a resource. An update request
  must provide the unique ID of the resource. To update an object
  structure resource, the ID of the main object is required.

https://www.ibm.com/support/knowledgecenter/en/SSLKT6_7.6.0/com.ibm.mif.doc/gp_intfrmwk/rest_api/r_rest_put_method.html
The response received using the url you provided appears to bear this out in as far as it indicates the work order cannot be created as it already exists:

Error 400: BMXAA4129E - The record for Site=BEDFORD, Work Order=1234
  already exists. Ensure that the key value for the given record is
  unique.

Reviewing the information at the following url I wasn't able to determine a method to perform the update without the unique ID:
https://www.ibm.com/developerworks/community/wikis/form/anonymous/api/wiki/02db2a84-fc66-4667-b760-54e495526ec1/page/87348f89-b8b4-4c4a-94bd-ecbe1e4e8857/attachment/0a884bde-d17e-471b-b046-7f8feddfd267/media/MaximoNextGenRESTAPI%20%281%29.pdf
In addition the Maximo RESTful API Swagger documentation indicates a POST to /os/mxwo is used to "Create a new resource":
/maximo/oas3/api.html?includeactions=1#/Work_Order_Definition_(MXWO)/post_os_mxwo
Whilst a POST to /os/mxwo/{id} is used to "Update WORKORDER Object":
/maximo/oas3/api.html?includeactions=1#/Work_Order_Definition_(MXWO)/post_os_mxwo__id_
I was however able to update an existing work order using the unique ID.  This being the case I can only suggest one of the following:

*

*If you're creating the work order first using the REST/OSLC API,
retrieve and store the unique ID from the response received when the
record is created.

*If (1) above is not possible, perform a GET and use parameters in
the query to filter on wonum and siteid and only receive back the minimum of
fields (e.g. workorderid only).

*If neither (1) or (2) are feasible investigate whether it's possible
to customise Maximo and create your own endpoint for the work order
object structure that takes wonum and siteid as parameters,
retrieves the mbo and performs the update.


text:
Q: How do I filter multiple values in array const arr1 = [{id:2},{id:3},{id:4},{id:5}]
const arr2 = [{Id:2},{id:4}]
I want to filter arr1 that contains arr2.id

A: function will return elements arr1 not contained arr2

const arr1 = [{id:2},{id:3},{id:4},{id:5}]
const arr2 = [{id:2},{id:4}]

const arrayFilter = (arr1, arr2) => {

  return arr1.filter( (item) => {
    return ((JSON.stringify(arr2)).indexOf(JSON.stringify(item)) <= 0) ? item : false
   })
}

console.log(arrayFilter(arr1,arr2))


text:
Q: Uncaught ReferenceError: CCapture is not defined? I have a simple app to create a canvas and render it. I am using capture js and FFmpeg module for converting videos in my app, but when I run the app I get the following reference error:
Uncaught ReferenceError: CCapture is not defined
    at test.js:67`

Here is test.js:
(function() {
  "use strict";

  var framesPerSecond = 60;
  var numFrames = 20; //framesPerSecond * 60 * 2;
  var thickness = 100;
  var speed = 4;
  var frameNum = 0;

  var canvas = document.getElementById("c");
  var ctx = canvas.getContext("2d");
  canvas.width = 1280;
  canvas.height = 720;

  var progressElem = document.getElementById("progress");
  var progressNode = document.createTextNode("");
  progressElem.appendChild(progressNode);

  function onProgress(progress) {
    progressNode.nodeValue = (progress * 100).toFixed(1) + "%";
  }

  function showVideoLink(url, size) {
    size = size ? (" [size: " + (size / 1024 / 1024).toFixed(1) + "meg]") : " [unknown size]";
    var a = document.createElement("a");
    a.href = url;
    var filename = url;
    var slashNdx = filename.lastIndexOf("/");
    if (slashNdx >= 0) {
      filename = filename.substr(slashNdx + 1);
    }
    a.download = filename;
    a.appendChild(document.createTextNode(url + size));
    document.body.appendChild(a);
  }

  var capturer = new CCapture( {
    format: 'ffmpegserver',
    //workersPath: "3rdparty/",
    //format: 'gif',
    verbose: false,
    framerate: framesPerSecond,
    onProgress: onProgress,
    //extension: ".mp4",
    //codec: "libx264",
  } );
  capturer.start();

  function drawLines(ctx) {
    for (var xx = -canvas.width; xx < canvas.width; xx += 2) {
      var l = (xx - (-canvas.width)) / (canvas.width * 2);
      ctx.beginPath();
      ctx.moveTo(xx, -canvas.height);
      ctx.lineTo(xx,  canvas.height);
      ctx.strokeStyle = "hsla(" + ((l * 360 * 24) % 360) + ",100%,50%,0.5)";
      ctx.stroke();
    }
  }

  function render(time) {
    ctx.fillStyle = "#000";
    ctx.fillRect(0, 0, canvas.width, canvas.height);

    ctx.fillStyle = "#FFF";
    for (var xx = 0; xx < canvas.width + thickness * 2; xx += thickness * 2) {
      var x = xx - (frameNum * speed % (thickness * 2));
      ctx.fillRect(x, 0, thickness, canvas.height);
    }

    ctx.save();
    ctx.globalCompositeOperation = "difference";

    ctx.font = "400px sans-serif";
    ctx.textAlign = "center";
    ctx.textBaseline = "middle";
    ctx.fillText(frameNum, canvas.width / 2, canvas.height / 2);

    ctx.save();
    ctx.translate(canvas.width * 0.5, canvas.height * 0.5);
    ctx.rotate(frameNum * 0.01);
    ctx.translate(canvas.width * 0.25, 0);
    drawLines(ctx);
    ctx.restore();

    ctx.save();
    ctx.translate(canvas.width * 0.5, canvas.height * 0.5);
    ctx.rotate(frameNum * -0.013);
    ctx.translate(canvas.width * 0.37, 0);
    drawLines(ctx);
    ctx.restore();

    ctx.restore();

    capturer.capture(canvas);

    ++frameNum;
    if (frameNum === numFrames) {
      capturer.stop();
      capturer.save(showVideoLink);
    } else {
      requestAnimationFrame(render);
    }
  }
  requestAnimationFrame(render);
}());


text:
Q: Factory design patter Spring Boot double bean @Component
public abstract class CommandBase {

    @Autowired
    WebServiceProxy nbiService;

    @Autowired
    OperationCacheRepository cacheRepository;

    public CommandBase(
            WebServiceProxy nbiService,
            OperationCacheRepository cacheRepository) {

        this.nbiService = nbiService;
        this.cacheRepository = cacheRepository;
    }

    public abstract void executeSPV(SpeedTestDTO stDTO) throws NBIException;

    public abstract long executeGPV(long guid, OperationCache operationCache) throws NBIException;

@Slf4j
public class DownloadDiagnosticsCommand extends CommandBase {

    public DownloadDiagnosticsCommand(WebServiceProxy nbiService, OperationCacheRepository cacheRepository) {
        super(nbiService, cacheRepository);
    }

    @Override
    public void executeSPV(SpeedTestDTO stDTO) throws NBIException {
        // some executable code
    }

    @Override
    public long executeGPV(long guid, OperationCache operationCache) throws NBIException {
        // some executable code
    }
}

@Slf4j
public class UploadDiagnosticsCommand extends CommandBase {

    public UploadDiagnosticsCommand(WebServiceProxy nbiService, OperationCacheRepository cacheRepository) {
        super(nbiService, cacheRepository);
    }

    @Override
    public void executeSPV(SpeedTestDTO stDTO) throws NBIException {
        // some executable code
    }

    @Override
    public long executeGPV(long guid, OperationCache operationCache) throws NBIException {
        //some executable code
    }
}

@Component
public class RFACommandFactory {

    @Autowired
    WebServiceProxy nbiServiceProxy;

    @Autowired
    OperationCacheRepository cacheRepository;

    public final CommandBase createCommand(final String measureType) {
        if ("download".equalsIgnoreCase(measureType)) {
            return new DownloadDiagnosticsCommand(nbiServiceProxy, cacheRepository);
        } else if ("upload".equalsIgnoreCase(measureType)) {
            return new UploadDiagnosticsCommand(nbiServiceProxy, cacheRepository);
        }
        return null;
    }
}

Calling method executeSPV from abstract class
@RestController
@RequestMapping("/rfa/speedtest/v1")
@Slf4j
public class Controller {

    @Autowired
    CommandBase command;

    @Autowired
    RFACommandFactory rfaCommandFactory;

    @PostMapping(value = "{id}", consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    private ResponseEntity<String> post(
            @PathVariable String assetId,
            @RequestBody Payload payload) {

        log.info("Received new payload:{}", payload);

        command = rfaCommandFactory.createCommand(speedTestDTO.getType());

        try {
            command.executeSPV(speedTestDTO);
        } catch (NBIException e) {
            log.info("NBIException", e);
            return new ResponseEntity(payload, HttpStatus.BAD_REQUEST);
        }
        return new ResponseEntity(payload, HttpStatus.CREATED);
    }
}

If I remove @Componet from Upload and Download classes I receive error I need to add Bean for abstrcat class CommndBase
If I use @Compoment on Upload and Download classes I receive dual Bean is useed...
Field command in .Controller required a single bean, but 2 were found:

A: You should not use @Component for abstract class, because Spring context will not be able to initialize that bean. You should remove it then.
Another thing is the way you want to implement a factory pattern here - I recommend you the way described here: https://stackoverflow.com/a/39361500/14056755, refactored version https://stackoverflow.com/a/55060326/14056755.


text:
Q: Which is faster? Pass by reference vs pass by value C++ I thought that pass by reference should be faster then pass by value because the computer isn't copying data, it just points to the address of data.
But, consider the following C++ code:
#include <iostream>
#include <cassert>
#include <cmath>

using namespace std;

// do not use pass by reference& with this function, it will become so slow
unsigned long long computePascal(const unsigned int row, const unsigned int position) {
    if (position == 1 || position == row)
    return 1L;
    unsigned long long left = computePascal(row-1, position-1);
    unsigned long long right = computePascal(row-1, position);
    unsigned long long sum = left + right;
    return sum;
}

int main() {
    int row, position;
    cout << "Input row and position: ";
    cin >> row >> position;
    assert(position > 0 && position <= row);
    unsigned long long pascalNumber = computePascal(row, position);
    cout << pascalNumber << endl;
    return 0;
}

Now this code is just a normal program that compute pascal number recursively by entering the desired row and position of the triangle.
I tried putting row 50 and position 7 and it computes around 1 second (pass by value). The output is about 13 million which is correct. So I thought that it could be faster if I pass by reference instead because it doesn't need to copy a lot of data. But this is very wrong and I don't know why it took longer time about 3 times the amount it took for passing by value.
The question is ...
Why this program computes so slow after I try changing it to pass by const reference?
Does it matter that because recursive function is an exception that you should pass by value rather than const reference?

A: The answer to "Which is faster" is usually "It depends".
If instead of passing four bytes of data you are passing an eight byte pointer to data, then you can't really expect that to make things faster. If instead of passing 100 bytes of data you are passing an eight byte pointer to data, that's different.
But now the function doesn't have the data, it only has a reference. So whenever it needs to read the data, it has to do that indirectly through the reference. That takes longer. If you pass a 100 byte object and only read eight byte of it, you still are likely to win. But if you actually read all the data, and maybe multiple times, then it could easily be faster to pass the value even for large objects.
The real difference comes when you pass an object, and passing by value means a more or less complex constructor will be called. Passing by reference means no constructor. But int has no constructor anyway.
And then there is optimisation. Passing by value means the compiler knows your function is the only one with access to the data. Pass by reference means the data could be anywhere. If you have two int& parameters, I could pass the some int twice. So increasing row might increase pos. Or it might not. That kills optimisations.
And then there is the rule of optimisation: "Measure it". You measured it and found what's faster. Sometimes things are faster or slower for no good reason whatsoever.


text:
Q: Zrub Foundation dropdown buttons break inside Angular partial When I use Zrub Foundation drop down buttons inside an Angular partial, they look OK at first glance, but but when you click to display the choices, they are not displayed.  The color of the botton on hover and click change as they should, it's just the list items do not display.
There are no errors in the console.  Also, if I put the button code directly in index.html, the drop down behavior works fine.
Any ideas on how to get the dropdown button working inside a partial?
app.js
'use strict';
angular.module('myapp', ['myappFilters', 'myappServices']).
  config(['$routeProvider', function($routeProvider) {
  $routeProvider.
      when('/test', {templateUrl: 'partials/test.html',   controller: EnvListCtrl}).
}]);

test.html

  Dropdown Button

Choice 1

Choice 2

Choice 3

A: My work-around was to trigger change on the select element, and then click on the anchor and list elements.
This essentially initializes the dropdown element to display properly with consideration to whatever is set as the selected element.
I have the dropdown inside a reveal modal, which is inside a partial. In my case, I initialize the element before activating the modal.
markup
<select style="display:none;" id="customDropdown"
  ng-options="o.label for o in apptStatusOpts" ng-model="apptStatus"></select>

  Appointment Status

{{o.label}}

javascript
$("#customDropdown").trigger('change');
$("#customDropdown a.current").trigger('click');
$("#customDropdown li.selected").trigger('click');

Also note, Foundation 3 is what I was working with. not sure if anything changed in the recently release Foundation 4 yet.


text:
Q: Virtualbox Start VM Headless on Windows Oracle VirtualBox on Windows
Hi All,
Is there a way to start a vm headless (vboxheadless -s ) but one can close that command window or if I add that as a startup item will that make it run silent ?
I have successfully exported a appliance (linux vm), when I will do the batch import will it retain the settings I had configured originally or will one would have to assign bridged adapter, amount of ram, etc ?
will be grateful for your suggestions !
Kind Regards
EDIT :
Iain, if one wants to script the GuestAdditions install on first boot in a CentOS VM, shall I just put the commands ./VBOXLinux-x86-additions.run to the bash script and it will run at startup, any thoughts on this would be really helpful.
Kind Regards

A: If you use
vboxmanage import ovffile.ovf --dry-run

you will get a report telling you what configuration is going to be applied when the import is actually done. You'll also get advice on how to make changes if required.
As to running vboxheadless detached from a command line and a window it's not as straightforward as you may think. A simple
start /b vboxheadless -s vmname

appears to work in that it detaches from the command line but if you close the window the child process dies too and the 'power cord' is pulled from your vm.
To solve this use a small vbs script test.vbs
Set WshShell = WScript.CreateObject("WScript.Shell")
obj = WshShell.Run("c:\temp\test.bat", 0)
set WshShell = Nothing

My test.bat
@echo off
vboxheadless -s vmname

A: This is pretty old post but I spent a lot of time looking for this
Here's what I use
VBoxManage.exe startvm "myvm" --type "headless"

And to stop it
VBoxManage.exe controlvm "myvm" savestate

or poweroff
I have put these in the Widows 7 task scheduler so it starts and stops with Windows.
Start:
Trigger at start up
Shut down:
Trigger on an Event
System event:
Source User32
Event ID 1074
The one issue I have found with this is if the IP changes it becomes difficult to figure out the right IP address.

A: AFAIK when you import the applicance it will hold the settings you had on the machine you exported it from.
See if this post on the VirtualBox forum can help you.

A: I am using a small opensource application named VBoxVmService, which is very helpful in this type of scenario. It enables you to run your VirtualBox VMs in headless mode as windows services (one service for each VM). It is hosted on Sourceforge at:
http://vboxvmservice.sourceforge.net/
You can configure the VMs to start as service in a simple ini file. Documentation is provided with the download.
Be aware of the fact that the started VMs do not show up in the VirtualBox GUI application as started (differing from Linux, where those can be seen). If you should need to reconfigure your VMs, you will need to shutdown the service first (the supplied tray miniapp of VBoxVmService is very helpful there), then make the change in the VirtualBox GUI and then lauch the VM service again.
I added this proposal, because it may be more convenient to some users...

A: This works well for me
VBoxManage startvm --type headless "Name of guest to start"


text:
Q: inject html code to all port 80 request I am looking for the best solution to inject some html ad code into every webpage request.
I have public wireless access.  I would like to keep it free but append/inject ad code to every port 80 or webpage request.  Would a proxy software handle this?  I would like to keep this open source not some paid server or high end software if all possible.
Thanks!

A: This answer probably goes against the aim of the software, but you should take a look at privoxy and its filter capabilities. For this to work on a public hotspot, you would need to make it intercept traffic - using something like PF. Alternatively, you could check out commercial software/hardware on google.


text:
Q: "Enthused" vs. "enthusiastic" Is it grammatically correct to say "I was enthused" rather than "I was enthusiastic"?
If so, what is the difference between the two?

A: The answer is one of preference, not grammar.
Enthused is a back-formation. Because it's newer, some people may be more used to hearing enthusiastic. Also, as the quote below indicates, the two words can have different implications.
Quoth the grammarist:

... problems arise when enthused is used as a past-participle adjective in place of enthusiastic, which is a perfectly good, and far older, word. Plus, the adjective enthused can carry an ironic tone and is difficult to use in earnest.


text:
Q: Global sections of a line bundle with negative self intersection Let $X$ be a smooth projective surface over complex numbers. Consider a line bundle $L$ on $X$ such that it's self intersection $L\cdot L$ is negative. I read that it means that $L$ is rigid and cannot be moved. Does the negative intersection number mean $H^0(L)=0$?

A: If $X$ is the blowup of another surface $Y$ along a point and $E$ is the exceptional divisor of the blowup then $L = O_X(E)$ has negative self-intersection, and at the same time has a global section. So, the answer is no.


text:
Q: Efficient k-order voronoi diagram and 3d voronoi diagram in CGAL I'm having trouble in calculating k-order Voronoi diagram and 3d voronoi diagram in CGAL.

*

*First, I want to calculate a k-order Voronoi diagram(k is the number of nearest neighbor) from given set of points(2d/3d).

*

*As far as I know, there is a header file "k_delaunay.h" (code here) in CGAL demo ipelet folder. And it can calculate a k-order regular triangulation.  And I believe I can convert regular triangulation to Delaunay triangulation.

*However, from the code we can see the complexity is very high. I have tested 300k 2d points, and the actual run time for calculating k-order Voronoi diagram is not acceptable. So I wonder is there any other implementation of k-order Voronoi diagram in CGAL(the rest of my code is written in CGAL, so I really want to use the existing data structures)?

*Also, since CGAL's voronoi diagram adapter only support 2D, is there any efficient way to convert 3D delaunay triangulation to 3D voronoi diagram?
Thanks!

A: Instead of k-order you can use a hierarchical cluster, i.e. a dendogram.


text:
Q: WebView is not showing content on Android 2.3 I created a project for testing why a web page is not showing (blank page) on a WebView in Android 2.3 and below. The url that must be load is:
https://www.geotrackline.com/android/middleware/TabletGeoFrame.php?user_id=503&method=load
That should return a web showing a map. The point is that the application works nice in Android 3.0 (tested in a GalaxyTab) and above (tested in a Galaxy Nexus).
This is my code in Java:
WebViewTestActivity.java:
WebView wb;
private static String MAP_URL = "https://www.geotrackline.com/android/middleware/TabletGeoFrame.php?user_id=503&method=load";

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

    setContentView(R.layout.main);

    wb = (WebView)findViewById(R.id.webView);

    WebSettings settings = wb.getSettings();

    settings.setJavaScriptEnabled(true);
    settings.setDomStorageEnabled(true);
    settings.setJavaScriptCanOpenWindowsAutomatically(true);
    settings.setBuiltInZoomControls(true);
    settings.setSupportZoom(true);
    settings.setGeolocationEnabled(true);

    wb.loadUrl(MAP_URL);
    wb.setWebChromeClient(new WebChromeClient(){

            public boolean onConsoleMessage(ConsoleMessage cm) {
                Log.e("onConsoleMessage", cm.message() + " -- From line "
                                     + cm.lineNumber() + " of "
                                     + cm.sourceId());
                return true;
            }
     });

The console message is showing the next:
06-07 11:15:36.480: E/onConsoleMessage(21930): Uncaught SyntaxError: Unexpected token for -- From line 573 of https://www.geotrackline.com/android/middleware/js/GeoTracking.js
06-07 11:15:36.500: E/onConsoleMessage(21930): Uncaught ReferenceError: GeoTracking is not defined -- From line 15 of https://www.geotrackline.com/android/middleware/TabletGeoFrame.php?user_id=503&method=load
06-07 11:15:36.530: E/onConsoleMessage(21930): Uncaught TypeError: Cannot call method 'sendAJAX' of undefined -- From line 27 of https://www.geotrackline.com/android/middleware/TabletGeoFrame.php?user_id=503&method=load

And this is the response I get from the url in Android 2.3 and below:

        <meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <title> :: geotracking :: </title>

Any idea what's happening?
thanks in advance, and sorry for my english


text:
Q: HTTPS domain proxying to HTTP app - how to properly make them work together? I have a domain on AWS EC2 instance with SSL that is served at https://example.com.
The only job for this domain is to proxy traffic from the domain to my home PC which serves a Laravel app. They are connected via WireGuard tunnel.
nginx is used both on the EC2 instance and locally.
This is my config in the EC2 instance:
server {
    server_name example.com www.example.com;
    location / {
        proxy_set_header X-Real-IP  $remote_addr;
        proxy_set_header Host-Real-IP  $http_host;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header Host $host;
        proxy_pass http://10.10.10.1:80; # WireGuard IP
    }

    listen 443 ssl; # managed by Certbot
    ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem; # managed by Certbot
    ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem; # managed by Certbot
    include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
    ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot
}

server {
    if ($host = www.example.com) {
        return 301 https://$host$request_uri;
    } # managed by Certbot

    if ($host = example.com) {
        return 301 https://$host$request_uri;
    } # managed by Certbot

    server_name example.com www.example.com;
    listen 80;
    return 404; # managed by Certbot
}

Now when I develop locally the app is not using SSL so the URLs there aren't secured. For example the login page action is http://192.168.100.100/login and not https.
But then when I try to login from the domain and not locally at https://example.com/login, it doesn't work. Nothing happens it just refreshes the page.
So when I set the form action to https, then it works from the domain, but then locally it doesn't work (locally I get 419 page expired, maybe because my app expects the CSRF token but there is issue with the conflicting HTTP/HTTPS?)
How should I make it work in this case? Do you want me to also post my local nginx config as well?
Can I make my app also work locally with SSL? So serving it like https://192.168.100.100? (but then how do I do it)


text:
Q: Error Running python (forecasting) in Tableau I am pretty new to this system and fairly new in python. Thus there might be few redundant lines in the code.
I am trying to forecast y (CARA_Flows) using x (Hybrid_MF). Although the same code is working perfectly fine in Python, I am getting error in tableau. The error window itself shows me the correct forecasting (as well as prediction for the next 12 months).
Also, there's no issue with the integration.
Can someone help me understand the issue here.
SCRIPT_REAL(
"
import pandas as pd
import numpy as np

dateparse = lambda dates: pd.datetime.strptime(dates, '%Y%m')
data = pd.read_excel('S:\AIM India\Anup\Requests_2018\CTI_Forecasting_Tableau\Forecast_CTI_2.xlsx',parse_dates=['YYYYMM'], index_col='YYYYMM',date_parser=dateparse)

ts_exogenMF = data['Hybrid_MF']

from statsmodels.tsa.arima_model import ARIMA
model = ARIMA(ts_exogenMF,order=(2, 0, 2))
results_ARIMA1 = model.fit(disp=-1)
forecast1,std,conf=results_ARIMA1.forecast(steps=12,alpha=0.5)
forecastMF=forecast1
MF_Arr=[]
MF_Arr=forecastMF

ts = data['CARA_Flows']
from statsmodels.tsa.stattools import adfuller
ts_log = np.log(ts)
ts_log_diff = ts_log - ts_log.shift()

model = ARIMA(ts_log,exog=ts_exogenMF,order=(2, 0, 2))
results_ARIMA2 = model.fit(disp=1)
Final_Untransformed_Forecast=results_ARIMA2.predict(start=1, end=46, exog=MF_Arr,  dynamic=False)
predictions_ARIMA_log = pd.Series(ts_log.ix[0], index=ts_log.index)
predictions_ARIMA_cumsum = predictions_ARIMA_log.add(Final_Untransformed_Forecast,fill_value=0)
predictions_12M = np.exp(Final_Untransformed_Forecast)

return predictions_12M

",SUM([Hybrid MF]), SUM([CARA Flows]))

A: The error is because of the mismatch in the date formats with the code and output. So you should replace pd.datetime.strptime(x, '%Y-%m-%d') with pd.datetime.strptime(dates, '%Y%m')

A: This got fixed when I converted the output to a list. Below is the entire code:
SCRIPT_REAL(
"
import pandas as pd
import numpy as np

dateparse = lambda dates: pd.datetime.strptime(dates, '%Y%m')
data = pd.read_excel('S:\AIM.....\...\ =dateparse)

ts_exogenMF = data['Hybrid_MF']

from statsmodels.tsa.arima_model import ARIMA
model = ARIMA(ts_exogenMF,order=(2, 0, 2))
results_ARIMA1 = model.fit(disp=-1)
forecast1,std,conf=results_ARIMA1.forecast(steps=12,alpha=0.5)
forecastMF=forecast1
MF_Arr=[]
MF_Arr=forecastMF

ts = data['CARA_Flows']
from statsmodels.tsa.stattools import adfuller
ts_log = np.log(ts)
ts_log_diff = ts_log - ts_log.shift()

model = ARIMA(ts_log,exog=ts_exogenMF,order=(2, 0, 2))
results_ARIMA2 = model.fit(disp=1)
Final_Untransformed_Forecast=results_ARIMA2.predict(start=0, end=46, exog=MF_Arr,  dynamic=False)
predictions_ARIMA_log = pd.Series(ts_log.ix[0], index=ts_log.index)
predictions_ARIMA_cumsum = predictions_ARIMA_log.add(Final_Untransformed_Forecast,fill_value=0)
predictions_12M = np.exp(Final_Untransformed_Forecast)

predList=pd.Series.tolist(predictions_12M)

return predList

",SUM([Hybrid MF]), SUM([CARA Flows]))


text:
Q: Setting width and height of modal window from JavaScript/JQuery to ASP.NET MVC inline code This is my HTML ActionLink helper in the view:
<%=Html.ActionLink(Resources.Localize.Routes_WidgetsEdit, "Edit", Model.ContentType.ToString(),
new {slug = Model.Slug, modal = true},
new {
      rel = "shadowbox;height=_HEIGHT_;width=_WIDTH_",
      title = Resources.Localize.Routes_WidgetsEdit,
      @class = "editWidget"
})%>

It renders out this HTML
Edit tab

What I would like to do is insert dynamic values for HEIGHT and WIDTH, in JavaScript I get them like this:

Now I need a jQuery selector or command to select the "rel" attribute of all the links on page that are wired up to Shadowbox (see shadowbox value in rel) and if they contain shadowbox and HEIGHT and WIDTH replace those two placeholders with actual values at runtime. The solution should be quite bulletproof.
Hopefully this will be a piece of cake for all you jqueryists out there. ;)

A: Not sure how bullet proof it is, but how about something like the following:

Edit tab

Edit tab

Edit tab


text:
Q: How to create a OpenVPN server that redirects all incoming traffic to Tor? I have a working OpenVPN server that forwards all traffic to/fro the internets. How can I configure another VPN user/client that will forward all traffic through Tor?  I have Tor running.
Must I change something in server.conf?
Edit:
This is useful:
https://airvpn.org/topic/1738-tor-over-vpn-or-vpn-over-tor/
Basically, what I'm asking is apparently just a proxy over OpenVPN, which will configure itself automatically if I use Tor on client and VPN to route ALL connections.
Follow-up question:
Does this setup mean that Tor will encrypt everything client side before sending through VPN - thus the VPN will never see anything but encrypted traffic? (It's my own VPN on my own VPS, but you know.. ;)

A: Answer to your initial question:
If your client has internet access through the VPN, this should be sufficient to initiate a Tor handshake. Your VPN server should be smart enough to forward your client its own traffic.
Answer to your follow-up question:
Yes, any traffic viewable on your VPN would be encrypted.
Tor uses a process of encryption called "Onion Routing" where your computer encrypts the message multiple times based on how many relay stations it will hit on the way to its destination. Packets sent FROM your client will be encrypted multiple times and then be decrypted one layer at a time on the way to each relay station. At the final relay node, it decrypts the message entirely and sends it to the intended recipient.
On the return journey, the last Tor node in the chain re-encrypts the message and sends it back all the way through in a similar process. Each node encrypts it further until finally the host receives the message encrypted x number of times. It decrypts the message with all of the shared keys and can finally view the message.


text:
Q: Java pass by value clarified I have a list of Cell object that represent a board game inside the board class.
Cell boardGame[][] = new Cell[8][8];

I needed a temporary cell to try the player move on him and compare it to the other cells, so I though that I could use a java pass-by-value to do it.
test(board.boardGame);
board.printBoard();

private static void test(Cell[][] boardGame) {
Cell c = new Cell((new Soldier(ChessPiece.QUEEN, Color.WHITE)), 7, 4);
    boardGame[7][7] = c;

}

I read some post about java here, but apparently I still didn't catch it 100%.
I expected to see only one white queen on the board, but I saw two.
I know that if you pass a reference you can change its values, but I though that if I would pass the array itself its members won't be modified unless I would execute a return.
Please help me to understand this subject better.
Thanks
Edit:
I think I don't understand when it called attributes and where it doesn't.
I though the different it if you are call "new" or not.
When its part of another object it called attribute right? but every object can be created as part of another object. I can create a new string in dog class and then create the dog class in the animal class and then create it in another class. So only the top class is in the stack?
For exemple:
public class Board  { //fake class

    int num= 0;
    public void test(int i){
        i = 1;
    }
}

and on another class:
    public class Main {
        static void outsideTest(Board board){
            board.num = 1;
        }
    public static void main(String[] args) {
        Board board = new Board();
        System.out.println(board.num);
        board.test(board.num);
        System.out.println(board.num);
        outsideTest(board);
        System.out.println(board.num);
}
}

Now I didn't understand why on test() method the num didn't change and on outsideTest() the num change, num as been created in the heap because its part of the board object, so its need to be changed on both cases no?

A: The best and least confusing way to remember it is as follows: Java passes everything by value, that includes the references. :)
When you have a variable:
Object a = new Object();

you don't actually have an object stored in a. What you have is a reference to an object somewhere in memory.
Likewise when you call a method on an object:
String b = a.toString();

you don't do that. What you call is a method that uses the data of the referenced object as its context.
So when you pass an object as an argument
System.out.println(b);

You don't pass the whole object. You pass the reference and that reference is passed by value.
edit:
If the reference were not passed by value, but by reference, you could do something like this, which fortunately you can't.
public void swap(Object a, Object b){
   Object swap = a; a = b ; b = swap;
}

String a = "a";
String b = "b";
swap(a,b);

// would print "b a" if references were
// passed by reference but instead prints
// "a b" as they're passed by value.
System.out.println(a + " " b);

A: The reference to the object is passed by value, which means that
boardGame = new Cell[8][8];

does not do any harm, but changing anything you get from boardGame does.

A: Java is essentially always "pass-by-value".

Caveat: It passes the value stored in the memory for the variable.
For primitive data types, the memory is allocated in stack space, whereas for objects reference memory is allocated in stack space but the object itself is created in heap. Similar can be stated for arrays too though they are not exactly objects in a strong sense.

Diagrams below would make it clearer.

Your Cell object 2D array should seem something like anObjectArrayVar (not exactly as the ref in the diagram pointing to the objects should now be pointing to the rows and we would need another level of allocation in heap in between ref and objects for each row (a set of cells refering to the objects).
So, when you pass boardGame, the value stored in the stack is passed that stores the reference to the array of objects (just like the value stored in the anObjectArrayVar). If say the list of refs is stored in location numbered 50 then anObjectArrayVar would have stored that and it passes that value to the test method when we call it. In such a scenario the test method wont be able to goto memory location anObjectArrayVar and change its value (to say 100) as it has only a copy of the value but it could easily change what it refers to(directly or indirectly) like the values in ref or the next level (and add new objects as in your case adding a new cell with queen) or the objects pointed to by them and those changes would reflect through out the program!
I would also like to draw your attention to the fact that the code
boardGame[7][7] = c;

would replace the current cell (as well as the soldier currently in it) which would create major issues if there was originally a soldier in that place at that point in the game. The game state would actually change.
As a suggestion (given the limited knowledge about your design) I would say at least save the cell in some other value in test method before replacing it.
Cell old = boardGame[7][7];
//now do all your operations
boardGame[7][7] = old;//just before returning from the function


text:
Q: A form is displaying as filled in, instead of blank, using PHP I am using an add on with Wordpress and it appears the PHP code is somehow calling my admin e-mail to autofill a form that is supposed to show up as blank.
Unfortunately for me, PHP is WAY over my head and I don't want to break everything.

              <?php _e( 'E-mail Address: ', 'stc_textdomain' ); ?>
              <input type="text" id="stc-email" class="form-control" name="stc_email" value="<?php echo !empty( $email ) ? $email : NULL; ?>"/>

I just want the form to be blank, but it's autofilling with the admin e-mail on the Wordpress account. I've targeted the line of code, I think it has something to do with this bit:
value="<?php echo !empty( $email ) ? $email : NULL; ?>"/>

But I don't think
!empty

is working, nor is NULL, could anyone help out please?


text:
Q: Toggle mobile navigation depending on scroll direction I have this navigation for mobile that i want to hide/show depending on which direction the viewport gets scrolled in. So if scrolling down i want it to hide, and scrolling up i want it to show.
My current code looks like this. It just toggles on scroll top. Anyone?
$(function() {
    $(window).on("scroll touchmove", function () {
        $('.mobile-nav').toggleClass('tiny', $(document).scrollTop() > 0);
    });
});

A: Maybe something like this:
var menu_height = 80;
var menu_visible = true;
var old_scroll = $(window).scrollTop();

function checkMenu() {
    new_scroll = $(window).scrollTop();
    if (old_scroll < new_scroll && new_scroll > 0) {
        // Scroll down
        if (menu_visible == true) {
            toggleMenu();
        }
    } else if (old_scroll > new_scroll) {
        // Scroll up
        if (menu_visible != true) {
            toggleMenu();
        }
    }
    old_scroll = new_scroll;
}

function toggleMenu() {
    if (menu_visible == true) {
        // Hide
        $('#menu').animate({top: '-='+menu_height+'px'}, 200, function(){ $(this).css('display', 'none') });
        menu_visible = false;
    } else {
        // Show
        menu_visible = true;
        $('#menu').css('display', 'block').animate({top: '+='+menu_height+'px'}, 200);
    }
}

$(document).ready(function() {
    // Show / hide menu on scroll
    setInterval(checkMenu, 100);
});

Codepen: http://codepen.io/anon/pen/dPGggg


text:
Q: How do I type text on top of a PDF? I've been given a form to fill out as a PDF.  It is not a fillable PDF, it's just a file that I'm expected to print out, fill in by hand, and scan back in.  Is there something available in the software center that will let me type text on top of a PDF?

A: (I really hate when people answer as a comment, so I'm going to list Inkscape here as an alternative and flag the comment.)
Typically I prefer inkscape to gimp (Gimp is very clunky to use), but both are limited to a single page at a time.  Thus if you have more than one page to edit, you'll need a tool like pdf-Shuffler to recombine the individual pdf files.
This limitation is why I decided to look for another editor, and am happy to report that John Baber's answer of using xournal worked well for me.

A: Lots of resources on the web recommend pdfedit but that's not available in the latest ubuntu.  xournal works perfectly for this.

A: http://www.wikihow.com/Edit-PDF-Files-in-Linux-Using-GIMP
requires both GIMP and Krita but it does work

A: Some time ago I spent lots of time trying them all and see which one was best for my need and easy fast to learn.
I strongly advise you to try PDF-XChange Viewer over wine, it runs smoothly and will probably do all you need. Here are some tips.
A review of other PDF editors, XChange included


text:
Q: Inference the time a process would take depending on the number of threads I have several datasets consisting on:

*

*Number of threads n

*Start process time t1

*Stop process time t2

*Operations processed x
So each line of the dataset mean n threads processed x operations in t2-t1 time
When more threads are added, the processing time is reduced, because they run on parallel. However, they have locks between them, so the total time is not (t2 -t1)/n, but a bit more.
I would like to infer the time a process will take to do x operations depending on the thread number, some sort of "parallel factor" so t = x * n * factor gives me the estimated time. How could I achieve this?


text:
Q: Clustering based on correlation I have a pearson correlation matrix with how different foods are correlated with each other.
I would like to create groups of foods that can be analyzed together, therefore I would like to categorize them into clusters.
I want to cluster these foods into categories using the following criteria:
1) I would like to maximize the correlation within each of the clusters
2) I would like to setup a minimum correlation for each group (i.e. each cluster needs to have a correlation of >0.7).
Is there a machine learning algorithm that would be applicable for this case.

A: Use hierarchical clustering with

*

*Complete linkage

*Cut at height 0.7

*Transform similaritires into distances


text:
Q: TF30063: You are not authorized to access Microsoft-IIS/8.5 I got an issue with the tfs.
Firstly after my tfs server database got full.
So in order to solve it i cleared the table of logs from tfs server.
Now at time of clearing data one of my workspace had checkout of one file. As soon i finished my clearing data, it is giving me this error TF30063: You are not authorized to access Microsoft-IIS/8.5. at every time i try to get latest version.
Thats how i am unable to take latest.
Any help would be appritiable.

A: *

*Clean the Cache folder on client computer. The folder path is: C:\Users\username\AppData\Local\Microsoft\Team Foundation\5.0\Cache.

*Clean the Cache folder on Server machine. The folder path is: C:\Program Files\Microsoft Team Foundation Server 12.0\Application Tier\Web Services_tfs_data

*After cleaned, on Server machine, click Start and select Run… to open the dialog box, then input iisreset.exe and click OK, wait it run completely.

A: *

*Right-click solution

*Get Latest Version

*Try commit again

Issue started for me when I upgraded to VS2017

A: For me it helps if i just click the Refresh button at the top of the Team Explorer.
After that, the message disappears and i can normally check in.

A: For me, it helped just to restart Visual Studio.

A: I just reconnected to the team project in the Team Explorer and my commit went through, didn't have to restart anything.

A: I had the same issue. When I closed an open Source Control Explorer window and all the files in Visual Studio, I was able to check in.

A: I think i got solution, exactly got that how to do.
Do checkout that file and check in an old version of that file
and
than do take latest.
It will not generate this error again.

A: If you can get a copy of the file that is on TFS you can add it as a new file to TFS, and then do get latest version of the file, and then select keep local when you get the conflict error, and then you can check in the file. After that you can then get latest with no errors.

A: For me, Run as Administrator from Visual, It will never make this error again.

A: *

*1 : Open TFS window.

*2 : Click on Refresh(F5).

*3: Try again to Check-in.
CLick here see Solution (Image):
I have faced same issue while check-in on TFS : You are not authorized to access Microsoft-IIS/10.0.

A: Using Visual Studio 2017 Enterprise with the latest update installed v15.2 (26430.4) on Windows 10 64-bit. The issue has been happening for awhile, it is not new with the latest VS update. We're using a TFS repository hosted on Visual Studio Online, i.e. our TFS repository is at COMPANY.visualstudio.com.
Frequently, when checking in, or attempting to shelve changes from the Team Explorer window in VS, I'll get an error message indicating I'm not authorized to access Microsoft-IIS/10.0. I've had reports of other developers experiencing this as well.
We've discovered the following workarounds.
Clicking the refresh button on the top of the Team Explorer window and then trying the operation again
If you have multiple workspaces, changing to a different one, then back to the original, then trying the operation again
It appears something is "stale" perhaps with the TFS connection and that refreshing it prevents the error message.
Hitting the refresh button over the Team explorer, resolved the issue.

A: I had a locked item. When I excluded/undo the locked item it went through.

A: Refresh TFS not worked for me
In my case the error disappear restarting Visual Studio
or me, it helped just to restart Visual Studio.


text:
Q: For every new row cells copy the format of previous row I have a code(button) where you can add a new row. Unfortunately the new row doesn't inherit the format(date) of previous cells. Now I need to write a code where I can paste the new row with formats of previous row.
The code should be integrated to this following code:
Private Sub CommandButton1_Click()

Sheets("Vorschlag V+V").Unprotect Password:="verpack21"

Range("C" & Rows.Count).End(xlUp).Select
ActiveCell.EntireRow.Insert

Sheets("Vorschlag V+V").Protect Password:="verpack21", AllowSorting:=True

A: Maybe something like this:
Sub Test()

    With ThisWorkbook.Worksheets("Vorschlag V+V")
        Dim LastRow As Long
        LastRow = .Cells(.Rows.Count, 3).End(xlUp).Row

        .Cells(LastRow, 1).EntireRow.Copy
        .Cells(LastRow + 1, 1).EntireRow.PasteSpecial Paste:=xlPasteFormats
        Application.CutCopyMode = False
    End With

End Sub


text:
Q: How to read the openoffice .sxc spreadsheet? I need to to read the data in the openoffice .sxc spreadsheet. I have seen the openoffice java SDK to operation the openoffice. Indeed, it is difficult for me to understand. I need to loop the sxc spradsheet and read the cells. Please help me! Thank you!

A: you need to use the OpenOffice UNO API for Java.  You  can get it from http://api.openoffice.org/
Looks like the best places to start reading are the Developer's Guide , and the samples in  Java
But there is another solution ;
How to get values from Open office spreadsheet?


text:
Q: Column username doesn't exist error when querying devise model with find_by_sql I'm trying to query my Devise-created table with find_by_sql and am running into a strange error.
User.find_by_sql("select username from user")

results in:
PG::UndefinedColumn: ERROR:  column "username" does not exist
LINE 1: select username from user
: select username from user

ActiveRecord::StatementInvalid: PG::UndefinedColumn: ERROR:
column "username" does not exist

LINE 1: select username from user
           ^
: select username from user

Here's my devise migration (I added the username field):
class DeviseCreateUsers < ActiveRecord::Migration
  def change
    create_table(:users) do |t|
      ## Database authenticatable
      t.string :username,           null: false
      t.string :email,              null: false, default: ""
      t.string :encrypted_password, null: false, default: ""

      ## Recoverable
      t.string   :reset_password_token
      t.datetime :reset_password_sent_at

      ## Rememberable
      t.datetime :remember_created_at

      ## Trackable
      t.integer  :sign_in_count, default: 0, null: false
      t.datetime :current_sign_in_at
      t.datetime :last_sign_in_at
      t.string   :current_sign_in_ip
      t.string   :last_sign_in_ip

      t.timestamps null: false
    end

    add_index :users, :email,                unique: true
    add_index :users, :reset_password_token, unique: true
  end
end

As you can see I have declared the field username. Querying other tables in this manner works perfectly. I have also tried User.find_by_sql("select 'username' from user"), and that just returns [#<User id: nil>].
Thanks!
Edit: want to add that User.last returns
#<User id: 1, username: "xxxxxx", email: "xxxxxxxx",
encrypted_password: "xxxxxx", reset_password_token: nil,
reset_password_sent_at: nil, remember_created_at: nil,
sign_in_count: 2, current_sign_in_at: "2016-06-26 20:16:59",
last_sign_in_at: "2016-06-25 22:00:31", current_sign_in_ip: "xxxxx",
last_sign_in_ip: "xxxx", created_at: "2016-06-25 22:00:31",
updated_at: "2016-06-26 20:16:59">

with the correct values in place of 'xxxxx'

A: It should be because the name of the table is users rather than user. You can check schema.rb to check that the name of table is users or user. However, according to the migration, it has to be users.
This should work: User.find_by_sql("select username from users"). And you can use User.find_by_sql("select id, username from users") if you need user_id of record along with the username.
Or rather I would suggest you to do it in the ruby way: User.select(:username)
Hope it Helps : )


text:
Q: Fill database table with data from config files on app startup I want the initial database state in my yesod web app to be defined by config files that are parsed on app startup. My current approach to achieve this compiles, but doesn't seem to do anything, I suspect this is because the database may not be ready for use at that point or needs to be accessed differently.
import System.Directory
import Data.Ini

-- | The @main@ function for an executable running this site.
appMain :: IO ()
appMain = do
  settings <- loadYamlSettingsArgs
      [configSettingsYmlValue]
      useEnv

  foundation <- makeFoundation settings

  loadConfigs -- | load configs and fill db

  app <- makeApplication foundation
  runSettings (warpSettings foundation) app

loadConfigs :: IO ()
loadConfigs = do allFiles <- getDirectoryContents "/config"
                 let filtered = filter (isSuffixOf ".cfg") allFiles
                 forM_ filtered parseConfig

parseConfig :: String -> IO ()
parseConfig fileName = do
                        res <- readIniFile fileName
                        case res of
                            Left msg -> do
                                return ()
                            Right ini -> do
                                let name = fromRight (pack "-") $ lookupValue (pack "name")  (pack "-") ini
                                db $ insert (User name "" "")
                                return ()

-- | Run DB queries
db :: ReaderT SqlBackend (HandlerT App IO) a -> IO a
db = handler . runDB

Could you please enlighten an unexperienced haskeller? Thanks!


text:
Q: Not able to display string from a resource in android I am trying to display a string from a resource
I have displayed the resource of the string in the values folder
activity_main.xml
<RelativeLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:paddingLeft="4dp"
        android:paddingRight="4dp"
        android:paddingTop="10dp" >

        <RelativeLayout
            android:layout_width="fill_parent"
            android:layout_height="140dp"
            android:background="@drawable/frame_background_for_rounded_corners_white_bkg" >

            <ImageView
                android:id="@+id/image1"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:background="@drawable/image_view_background_white_background" />

            <Button
                android:id="@+id/button1"
                android:layout_width="116dp"
                android:layout_height="wrap_content"
                android:background="@drawable/button_round_cornered_white_background"
                android:text="Button" />

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="141dp"
                android:layout_alignParentBottom="true"
                android:layout_below="@+id/button1"
                android:gravity="center"
                android:text="@string/BuffetOfferings-Breakfast-statement"
                android:textColor="#000000"
                android:textSize="24sp" />

        </RelativeLayout>
    </RelativeLayout>

In the values folder

styles.xml
<?xml version="1.0" encoding="utf-8"?>

<resources>

    <style name="AppTheme" parent="android:Theme.Light" />

    <color name="TextColorForTextAboveImage">#FFFFFF</color>

    <string name="BuffetOfferings-Breakfast-statement">Tap the "Breakfast" to offer, then the days and time of its offerings to your customers</string>

</resources>

My OUTPUT ::

Clearly you can see instead of text to display .... reference itself is displaying
How to resolve this !

A: Your string names need to use _ instead of -.
<string name="BuffetOfferings_Breakfast_statement"></string>

A: You need to remove your Dash(-) from name attribute.
 <string name="BuffetOfferingsBreakfaststatement">Tap the "Breakfast" to offer, then the days and time of its offerings to your customers</string>

For more information read Document.

A: Replace the resource attribute as
 <string name="BuffetOfferings_Breakfast_statement">Tap the "Breakfast" to offer, then the days and time of its offerings to your customers</string>

replace hyphen '-' with underscore'_'

A: You can't define string in styles.xml directly instead of you can reference to a String from strings.xml.
You should define your string in strings.xml and remove '-' use '_'
strings.xml

Use like this
<string name="BuffetOfferings_Breakfast_statement">Tap the "Breakfast" to offer, then the days and time of its offerings to your customers</string>

Hope this help you.


text:
Q: Which eigenvectors should I ignore? Solving an Euler-Bernoulli equation for a beam using Finite Element Method leads to the following equation
$$M \ddot{\vec d}(t)+K \vec d(t)=\vec F$$
where $M$ is system mass matrix, $K$ system stiffness matrix and $\vec d(t)$ a vector of primary node variables.
In my case where we discreticise the beam to $n=5$ identical parts (see attached figure) the vector of primary variables can be written as follows $$\vec d (t)=(w_1,\Phi_1,w_2,\Phi_2,w_3,\Phi_3,w_4,\Phi_4,w_5,\Phi_5,w_6,\Phi_6)^\intercal$$ assuming $w_i$ is the vertical displacement of $i$-th node and $\Phi_i$ the angle at $i$-th node.
Note that the $dim(\vec d(t))=12$, therefore both mass and stiffness matrices are 12$\times$12 matrices.
It is also obvious from the attached figure that $\vec F =\vec 0$, since we do not have any external forces or momentums acting on the beam. In that case the dynamic equation can be rewritten to
$$-\omega_0^2 M\vec d(t)+K\vec d(t)=\vec 0,$$
where I already assumed that the system will respond harmonically ($\ddot{\vec d}(t)=-\omega_0^2\vec d(t)$). Now what we have here is eigensystem
$$(M^{-1}K-\omega_0^2)\vec d(t)=\vec 0$$
THE PROBLEM:
Let's assume that we were able to calculate all the eigenvalues and eigenvectors of the system (meaning we were able to get some numerical values). Now what I would like to do is I would like to visualize the displacements of each node - $w_1$, $w_2$, $w_3$, $w_4$, $w_5$ and $w_6$.
But I have 12 eigenvectors each with dimension of 12. Meaning I would have to somehow ignore half of the eigenvectors. But... How do I know which ones?
EXAMPLE:
Let's say that one of the eigenvectors is $(1,2,3,4,5,6,7,8,9,10,11,12)$. According to how we defined $\vec d(t)$ I would like to get components $(1,3,5,7,9,11)$. But which eigenvectors do I choose?

A: Generally, the expectation is that you should keep the lowest eigenvalues, as they represent the collective motion of the beam which is well modelled by your discretization. (The higher eigenvalues, on the other hand, model waves with a higher spatial frequency, which you're not sampling tightly enough to get an accurate description.)
However, the real test with any discretization procedure is to check that your observables are numerically converged. Select the first $k$ eigenvalues (going up in frequency), and then repeat your calculation for 14×14, 16×16, 18×18 matrices (i.e. discretizing using smaller length steps), and as high as your code can go. If your observables don't change much, then you can be reasonably confident that you're doing things right.

That's as far as one can go without knowing exactly what you're putting in. However, in your case, there is a separation of your state space into two distinct sectors, and if you're only interested in one sector then you can select for the eigenvalues whose eigenvectors have significant amplitude in that sector.
As an extreme case, suppose that you introduce absolutely no couplings in either $K$ or $M$ between the vertical and torsional displacements. This will mean that $M^{-1}K$ will be the direct sum of two matrices, each with a distinct set of eigenpairs, with the eigenvectors either completely torsional or completely vertical. You then take the eigenvalues that correspond to the vertical displacements.
However, this simple separation is not always possible. In the other extreme case, you can introduce matrices where the coupling between the vertical and torsional displacements is as high as the vertical-vertical and torsional-torsional couplings, and in this case you'll just have completely mixed eigenvectors, so you need to take everything that's converged.
In an intermediate coupling, it may or may not be a good idea to post-select only on "mainly vertical" eigenmodes - that's for you to evaluate given the relative amplitudes of the "mainly vertical" vs the "mainly torsional" modes over the degrees of freedom that you care about.

A: The reason you think you need to ignore half the eigenvectors is most likely because your plotting algorithm is ignoring half the displacement data! It is only using the translations, and ignoring the rotations.
If you used the element shape functions to plot the internal displaced shape along the length of each element, every mode shape would look different.
Most Finite Element post processing software doesn't bother to do that, because for accurate results, as a rule of thumb you need about 5 node (grid) points for each "wavelength" of the displaced shape anyway.
So for your model with 5 elements, probably only one eigenvector (the lowest frequency) would be useful for real-life engineering work, and at best it would only be worth plotting the mode shapes for the two or three lowest frequencies.


text:
Q: Python - Passing params to base class inheriting from TestCase I have some code which I'm using to run some selenium tests using Python.
I have created a base class which inherits from TestCase, which all works fine.
However, I want to be able to access a config object passed into the base class so I can reference the chromedriver executable path & whether I run the tests headless.
class TestBase(unittest.TestCase):

    def setUp(self):
        chrome_options = webdriver.ChromeOptions()
        is_headless = bool(distutils.util.strtobool(self.config.get("CHROMEDRIVER", "headless_enabled")))
        if is_headless:
            chrome_options.headless = True
        else:
            chrome_options.headless = False

        executable = self.config.get("CHROMEDRIVER", "executable_path")
        self.driver = webdriver.Chrome(executable, options=chrome_options)

class TestWebSite(TestBase):

    def setUp(self):
        root_dir = os.path.abspath('../../')
        self.config = ConfigLoader(root_dir + '/resources/config.ini').config
        super().setUp()

    def test_tc001_test_page_loads(self):
        pass

class ConfigLoader:
    def __init__(self, config_file):
        self.config = configparser.ConfigParser()
        if os.path.exists(config_file):
            self.config.read(config_file)
        else:
            raise SystemExit('Could not find config file to load.')

I'm defining self.config within the TestWebSite class, which works, although when I review in PyCharm is flags with the following warning: unresolved attribute reference 'config' for class 'TestBase', unassumingly because I'm not passing in via a constructor.
What's the best way of resolving this?
I could move the config loading into the base class, but prefer to have this at the test case level.


text:
Q: How to show the newsletter with user name option in footer Can anyone suggest me how to show the newsletter with username option in the footer? Please check the reference site: http://www.oculosshop.com.br/.

A: You can create a simple module for it or you can try any module available here.
I could have provided instructions to create the module but since there are free modules available, I thought that reinventing the wheel is not a good advice.
Please check any of the above and hit like if it helped you.


text:
Q: Faced problem with interval not being cleared in React I was doing a project in React and what I wanted to do is to start the calculation of factorial of 1000 on start button and cancel the calculation on cancel button click. Thus, I used setInterval here is the whole code:
import React, { useState } from "react";

const Button = ({ title, countButton }) => {
  const [result, setResult] = useState(0);

  let interval;

  const handleFactorial = (num) => {
    let iteration = 1;
    let value = 1;

    interval = setInterval(function () {
      value = value * iteration;
      console.log(iteration++);
      if (iteration === num) {
        setResult(value);
        console.log(result);
        clearInterval(interval);
      }
    }, 0);
  };

  let cancelFactorial = () => {
    clearInterval(interval);
  };

  return countButton ? (
    <button onClick={() => handleFactorial(1000)}>{title}</button>
  ) : (
    <button onClick={cancelFactorial}>{title}</button>
  );
};

export default Button;

The problem is when I click on cancel button which is this one <button onClick={cancelFactorial}>{title}</button> but calculation keeps going. Thus I need your help

A: You should use a reference for that as if you log your interval value, you will notice that you re-assign its value on every render.
const Button = ({ title, countButton }) => {
  const intervalRef = useRef();

  const handleFactorial = (num) => {
    intervalRef.current = setInterval(function () {...}, 0);
  };

  let cancelFactorial = () => {
    clearInterval(intervalRef.current);
  };
...
}

A: You need to use [useRef][1] to keep a reference to your interval.

// don't do that
// let interval;

// do this instead
const intervalRef = useRef();

interval.current = setInterval(function () { ... })

const cancelFactorial = () => {
    clearInterval(interval.current);
 };


text:
Q: It seems that I can *reference a field before it is defined*

public enum MyEnum1 {

    FOO(BAR), BAR(FOO);

    private MyEnum1 other;

    private MyEnum1(MyEnum1 other) {
        this.other = other;
    }

    public MyEnum1 getOther() {
        return other;
    }

}

MyEnum1 generates the error Cannot reference a field before it is defined, which is quite understandable, since declaration order matters here. But why does the following compile?
public enum MyEnum2 {

    FOO { public MyEnum2 getOther() { return BAR; } },
    BAR { public MyEnum2 getOther() { return FOO; } };

    public abstract MyEnum2 getOther();

}

FOO refers to BAR before BAR is defined, am I wrong?

A: The important JLS parts are this and this

A class or interface type T will be initialized immediately before the
  first occurrence of any one of the following:
T is a class and an instance of T is created.
T is a class and a static method declared by T is invoked.
A static field declared by T is assigned.
A static field declared by T is used and the field is not a constant
  variable (§4.12.4).
T is a top level class (§7.6), and an assert statement (§14.10)
  lexically nested within T (§8.1.3) is executed.

And

The optional class body of an enum constant implicitly defines an
  anonymous class declaration (§15.9.5) that extends the immediately
  enclosing enum type.

So with
FOO { public MyEnum2 getOther() { return BAR; } },
BAR { public MyEnum2 getOther() { return FOO; } };

you are creating two anonymous classes extending MyEnum2.
When BAR is eventually reference either when you call Foo.getOther() or some other piece of code does MyEnum2.Bar, the type will be initialized.

A: you are creating enum constant with reference to yet undeclared constant in first case. In second case it does not matter because of compilation order, enumeration constants are compiled before enumeration body. I would say this is the reason. If it was not true, compilation would fail earlier because abstract method declaration is defined after the non-abstract method declaration in body of each enum constant.
Good reference - http://docs.oracle.com/javase/specs/jls/se7/html/jls-8.html#jls-8.9

A: When writing FOO(BAR), you are actually invoking the constructor of MyEnum1 and therefore BAR has to be evaluated, which is impossible at that moment since BAR hasn't yet been defined.
When writing FOO {...}, you are creating a new enum constant called FOO, but defining a new anonymous class. Since the class definition is only loaded ('loaded' as in 'ClassLoader') at this point and nothing is yet being evaluated, no error occurs. Then, BAR {...} is being created, the rest of your program continues, etc., and return BAR; (or return FOO;) is only evaluated when you make a method call to getOther(), which is perfectly possible at that point since both enum constants are happily alive at that point.