text:
Q: Perl scalar reference I am trying to do some scalar reference work.  Here is a simplified version of what I am trying to accomplish. I am currently using perl 5.10.1.
Notes:
*color is dynamically obtained
*trying to get a say 100, or the red value
*I realize this is much easier done with a hash but how can I do it with scalars?
$red = 100;
$blue = 150;
$green = 200;

$color = "red";

say ${$color};

Current error = SCALAR ref while "strict refs"

A: Use a hash, that's what they're for:
my %color_value = (
    red => 100,
    blue => 150,
    green => 200,
);

$color = "red";

say $color_value{$color};

Otherwise, your error was reported because you just forgot to do no strict "refs";.  But please please don't do that.

A: In addition to the answers already given...
use strict;
use warnings;
use feature qw( say );

my $red = 100;
my $blue = 150;
my $green = 200;

my $color = \$red;

say ${$color};

A: The error you are receiving is because of use strict. You need to turn off strict refs.
no strict 'refs';
say ${"$color"}; # "" are optional, I want to show it's about the string

Edit: Note that this only works on global variables. So you need to declare them with our or use vars instead of my. This is documented in perlfaq7 and shows why it is not a good idea to use variables to name other variables.

It's OK to turn off a strict feature in certain cases. But remember that it is good practice to contain it inside a very limited scope so it does not affect parts of your program that better not have this turned off.
use strict;
use warnings;
use feature 'say';

our $red = 100;
our $blue = 150;
our $green = 200;

my $color = "red";
{
  no strict 'refs'; # we need this to say the right color
  say ${$color};
}
# more stuff here

See also:

*

*http://perldoc.perl.org/perlref.html#Not-so-symbolic-references

*http://perldoc.perl.org/strict.html

*http://perldoc.perl.org/functions/no.html

*http://perldoc.perl.org/perlfaq7.html#How-can-I-use-a-variable-as-a-variable-name%3F


text:
Q: Object # has no method 'use' [Express+ShareJS] Environment

*

*Express 3.2.4

*ShareJS 0.6.2

*OS X 10.8.3

Goal
I am trying to get ShareJS running inside of an Express app.

Problem
I get the following error on running node app.js:
/Users/eric/Documents/Projects/collabit/node_modules/share/src/server/index.coffee:52
      server.use(options.staticpath, connect["static"]("" + __dirname + "/../.
             ^
TypeError: Object #<Server> has no method 'use'
    at Function.create.attach.attach (/Users/eric/Documents/Projects/collabit/node_modules/share/src/server/index.coffee:52:14)
    at Object.<anonymous> (/Users/eric/Documents/Projects/collabit/app.js:43:16)
    at Module._compile (module.js:449:26)
    at Object.Module._extensions..js (module.js:467:10)
    at Module.load (module.js:356:32)
    at Function.Module._load (module.js:312:12)
    at Module.runMain (module.js:492:10)
    at process.startup.processNextTick.process._tickCallback (node.js:244:9)

I used the express cli interface to generate an app and was working with SocketIO just fine before deciding to swap in ShareJS.  I'm pretty sure my issue is how I'm crafting the server but I don't know enough to figure out how I should be creating the server object to keep the express functionality but allow ShareJS to attach.b

Code
/**
 * Module dependencies.
 */

var express = require('express')
  , sharejs = require('share')
  , routes = require('./routes')
  , user = require('./routes/user')
  , http = require('http')
  , path = require('path');

var app = express();

app.configure(function(){
  app.set('port', process.env.PORT || 3000);
  app.set('views', __dirname + '/views');
  app.set('view engine', 'jade');
  app.use(express.favicon());
  app.use(express.logger('dev'));
  app.use(express.bodyParser());
  app.use(express.methodOverride());
  app.use(app.router);
  app.use(express.static(path.join(__dirname, 'public')));
});

app.configure('development', function(){
  app.use(express.errorHandler());
});

app.get('/', routes.index);
app.get('/users', user.list);

var server = http.createServer(app).listen(app.get('port'), function(){
  console.log("Express server listening on port " + app.get('port'));
});

/**
 * ShareJS Code
 */

var options = {db: {type: 'none'}};
sharejs.server.attach(server, options);

Question
What is the proper way to create my server object in order to allow ShareJS to attach to it while retaining the Express functionality.

Thanks!
Thanks in advance for help and let me know if any additional information is needed.

A: I had a similar issue. After a lot of trial and error this worked for me:
var express = require('express'),
http = require('http'),
sharejs = require('share').server;

var app  = express();
var server = http.createServer(app);

var options = {db:{type:'none'}}; // See docs for options. {type: 'redis'} to enable     persistance.

// Attach the sharejs REST and Socket.io interfaces to the server
sharejs.attach(app, options);

app.use(app.router);

app.set('views', __dirname + '/views');
app.engine('html', require('ejs').renderFile);

server.listen(8000, function () {
    console.log('Server running at http://127.0.0.1:8000/');
});

app.get('/', function(req, res) {
    res.render('share.html');
});

Then in views/share.html I had the standard example html:
<!DOCTYPE html>

    <title>Test</title>

redpajama_set_name: RedPajamaStackExchange


text:
Q: What are the basic rules for manipulating diverging infinite series? This is something that I played around with in Calc II, and it really confuses me:
$s = 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + \ldots = \infty$
$s - s = 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + \ldots $
$ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ -  (1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + \ldots) $
$s - s = 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + \ldots$
$0s \ \ \ \ \ = 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + \ldots = \infty$
$\therefore 0 (\infty) = \infty$
I'm aware the $0\cdot\infty$ is indeterminate, so what am I doing wrong? What are the basic rules for manipulating these diverging infinite series?

A: Basically, you don't.
The only way to manipulate them is if you know precisely what you're doing and using renormalization techniques or analytic continuation or something, but those techniques won't be taught for awhile and have specific rules about them.
Long story short, you don't manipulate them.


text:
Q: C# Garbage Collector's "KeepAlive" and Threads I have an application which is some sort of test for someone and lasts about 30 minutes. During the start of the program (3rd party), my code is called and I register the time and return some info to the application, and I save the test as "ONGOING".
After about 30 minutes, I expect the program to return to me and send me the results of the test so I can save and finish the process. Sometimes this doesn't happen for various reasons.
So I'm thinking in implementing a code to start a thread, sleep it for about 35 minutes (the maximum duration it can), and when it runs it does one thing only: if the test is still as "ONGOING", it updates it to "FAILED" or some other status.
However, I've read from here that C#'s garbage collector can collect threads that it assumes as inactive, and I'm worried about this, so I'd like to ask how does this KeepAlive method works with threads, or if there's any reliable way to test it (because even if I did wait all 35 min for it to happen, there might be a situation where the GC actually collects the thread and everything fails).
So, what's the correct way for this to work, or if it isn't like this, how should I do it?
static void Main(string[] args)
{
    //After all the startup functions are done...
    Thread thread = new Thread( () => UpdateTest(1) );
    thread.Start();

    //My thread is supposedly safe...?
    GC.KeepAlive(thread);
}

static void UpdateTest(int testID)
{
    Thread.Sleep(210000); //Sleep for 35min

    //Search the database for the testID, update it if it's still ONGOING.
}

A: Threads are not aborted due to GC. In fact, it is not possible to reliably abort a thread. (Try to abort try {} finally { while(true); }.)
The answer you reference is wrong. But there are 3 correct answers in that question. You just happened to believe the wrong, minority answer.
There is no problem for you to solve.


text:
Q: Workaround for lack of cross domain AJAX support in Opera Mini According to  caniuse.com and opera.com,  Opera Mini doesn't support CORS. Is there a workaround? Can I make AJAX requests from/to a different domain or at least to a subdomain in AngularJS?

A: Use one of the following workarounds:

*

*window.name can be used to share data across domains. For example:
window.name=window.StackExchange; window.location="http://www.example.com"; console.log(window.name);

*DOM Level 3 Load and Save

Any solution has its flaws but no one besides Opera allows a data:URI  which is not located on the same domain. Once parseURI can be executed combined with a data:URI the possibilities are endless - and it's very hard to determine the origin and content of the payload.
Use the data:URI with a HTML document that loads the original page via XHR
parseURI
Parse an XML document from a location identified by a URI reference [IETF RFC 2396]. If the URI contains a fragment identifier (see section 4.1 in [IETF RFC 2396]), the behavior is not defined by this specification, future versions of this specification may define the behavior.

  function loadDataForVersion(core_version)
    {
    var features_doc = document.implementation.createLSParser(DOMImplementationLS.MODE_SYNCHRONOUS, "").parseURI("features."+core_version+".xml");
    var feature_nodes = features_doc.evaluate("//feature", features_doc, null, XPathResult.ORDERED_NODE_ITERATOR_TYPE, null);
    var feature_node;
    while (feature_node = feature_nodes.iterateNext())
      {
      addFeatureNode(features_doc, feature_node, core_version);
      }
    }

Asynchronous LSParser objects are expected to also implement the events::EventTarget interface so that event listeners can be registered on asynchronous LSParser objects.
Events supported by asynchronous LSParser objects are:
load
The LSParser finishes loading the document. See also the definition of the LSLoadEvent interface.
progress
The LSParser signals progress as data is parsed.
This specification does not attempt to define exactly when progress events should be dispatched. That is intentionally left as implementation-dependent. Here is one example of how an application might dispatch progress events: Once the parser starts receiving data, a progress event is dispatched to indicate that the parsing starts. From there on, a progress event is dispatched for every 4096 bytes of data that is received and processed. This is only one example, though, and implementations can choose to dispatch progress events at any time while parsing, or not dispatch them at all.

*

*CSSHTTPRequest

A request is invoked using the CSSHttpRequest.get(url, callback) function:

CSSHttpRequest.get(
        "http://www.nb.io/hacks/csshttprequest/hello-world/",
        function(response) { alert(response); }
    );

Data is encoded on the server into URI-encoded 2KB chunks and serialized into CSS @import rules with a modified about:URI scheme. The response is decoded and returned to the callback function as a string

References

*

*Web Browser DOM Support

*CSSHTTPRequest github repo

*CSSHttpRequest: cross-domain Ajax using CSS for transport

*Improve cross-domain communication with client-side solutions

*: Fun with XXE, Data Islands and parseURI: Index

*The sad state of DOM security (or how we all ruled Mario's challenge)

*Dev.Opera — Opera Mini and JavaScript

*TVML Programming Guide: Implementing Search

*Opera Mini: Web Content Authoring Guidelines

*Opera Mini Request Headers


text:
Q: Using NLog to output to one of two log files I have a single-threaded .NET Winforms application. I am using a static NLog logger to log errors using this syntax:
MyLogger.Log.Error("Error occurred...");

In accordance with my one NLog.config-defined target and one NLog.config-defined rule, that log-error output always is written to a file called "errors.txt". Sometimes I want an error to be written to "errors2.txt" instead. How would I do that without creating another static logger instance?

A: You could use filters in the config or pass the filename to the logger call.
Note: These examples are using .WithProperty (on the NLog Logger), introduced in NLog 4.6.3
Filters
Use filters in the logger rules, we use the LogFinal so we need only the rules once (not needed for the 2nd logger rule)
See Filtering log messages on the NLog wiki
<rules>
  <logger name="*" writeTo="file-error1">
    <filters defaultAction='LogFinal'>
      <when condition="${event-properties:target} == 'error2'" action="Ignore" />
    </filters>
  </logger>
  <logger name="*" writeTo="file-error2">
  </logger>
</rules>

Logger call:
MyLogger.Log.Error("Error occurred..."); // writes to file-error1 target
MyLogger.Log.WithProperty("target", "error2").Error("Error occurred..."); // writes to file-error2 target

Pass file name
Pass the file name in as property. Maybe you could set a default property in the static Log method.
See also Event properties documentation
<targets>
    <target name="file" xsi:type="File"
        ....
        fileName="${basedir}/logs/{event-properties:filename}"
        ...  />
</targets>

Logger call:
MyLogger.Log.WithProperty("filename", "error1.txt").Error("Error occurred...");
MyLogger.Log.WithProperty("filename", "error2.txt").Error("Error occurred...");


text:
Q: How to convert Expression> to Expression> Is there way to convert Expression<Func<T, object>> to Expression<Func<object, object>> ?

A: I've had to do this before...
public static class ExpressionHelper {
    public static Expression<Func<object,object>> ConvertParameterToObject<T>(this Expression<Func<T,object>> source){
             return source.ReplaceParametersWithBase<T,object,object>();
    }

    public static Expression<Func<TBase,TResult>> ReplaceParameterWithBase<T,TResult,TBase>(this Expression<Func<T,TResult>> lambda)
        where T :TBase
    {
        var param = lambda.Parameters.Single();
        return (Expression<Func<TBase,TResult>>)
            ParameterRebinder.ReplaceParameters(new Dictionary<ParameterExpression, ParameterExpression>
                                                {
                                                    { param, Expression.Parameter(typeof (TBase), param.Name) }
                                                }, lambda.Body);
    }
}

public class ParameterRebinder : ExpressionVisitor
{

    private readonly Dictionary<ParameterExpression, ParameterExpression> map;

    public ParameterRebinder(Dictionary<ParameterExpression, ParameterExpression> map)
    {

        this.map = map ?? new Dictionary<ParameterExpression, ParameterExpression>();

    }

    public static Expression ReplaceParameters(Dictionary<ParameterExpression, ParameterExpression> map, Expression exp)
    {

        return new ParameterRebinder(map).Visit(exp);

    }

    protected override Expression VisitParameter(ParameterExpression p)
    {

        ParameterExpression replacement;

        if (map.TryGetValue(p, out replacement))
        {

            p = replacement;

        }

        return base.VisitParameter(p);

    }

}

A: How about something like this:
static Expression<Func<object,object>> ConvertFunction<T>(Expression<Func<T,object>> function)
{
    ParameterExpression p=Expression.Parameter(typeof(object));

    return Expression.Lambda<Func<object,object>>
    (
        Expression.Invoke(function,Expression.Convert(p,typeof(T))), p
    );
}

Then you can say something like this:
Expression<Func<string,object>> foo=s=>s.Length;
Expression<Func<object,object>> bar=ConvertFunction(foo);

var call=bar.Compile();
Console.Write(call("hello")) ; // Prints 5


text:
Q: Building a tree of vectors I'm trying to make a simple LISP parser, but I'm stuck on the step where I convert the vector of tokens into a tree of AST nodes.
I create the root of the tree, and then maintain a stack of references into the tree where I currently want to add the next node. The problem is that no matter what I try, it seems that the borrow checker thinks I'm referencing something that doesn't live long enough.
This is the code:
pub fn parse(tokens: &Vec<Token>) -> Node {
    let mut root: Vec<Node> = vec![];

    {
        tokens.into_iter().fold(vec![&mut root], handle_token);
    }

    Node::List(root)
}

fn handle_token<'a>(mut stack: Vec<&'a mut Vec<Node>>, token: &Token) -> Vec<&'a mut Vec<Node>> {
    if *token == Token::LParen {
        let new_node = Node::List(vec![]); // Create the new node
        stack[0].push(new_node); // Add it to the tree
        match stack[0][0] {
            Node::List(ref mut the_vec) => stack.push(the_vec), // Finally, add a mutable reference to the new vector so that subsequent nodes will become children of this Node
            _ => panic!(),
        };
    } else if *token == Token::RParen {
        stack.pop();
    } else {
        match *token {
            Token::Identifier(ref identifier) => {
                stack[0].push(Node::Identifier(identifier.to_owned()))
            }
            Token::Number(number) => stack[0].push(Node::Number(number)),
            Token::Str(ref s) => stack[0].push(Node::Str(s.to_owned())),
            Token::EOF => {}
            _ => panic!(),
        }
    }

    stack
}

This is the compiler output:
error: `stack` does not live long enough
  --> src/parser.rs:30:15
   |
30 |         match stack[0][0] {
   |               ^^^^^ does not live long enough
...
47 | }
   | - borrowed value only lives until here
   |
note: borrowed value must be valid for the lifetime 'a as defined on the block at 26:96...
  --> src/parser.rs:26:97
   |
26 | fn handle_token<'a>(mut stack: Vec<&'a mut Vec<Node>>, token: &Token) -> Vec<&'a mut Vec<Node>> {
   |                                                                                ^

After researching this a bit, it seems like I'm trying to do something completely non-idiomatic to Rust, but I'm not sure. Is there a simple way to make this work, or do I need to rethink this?
I tried to reduce the problem to a minimal example:
enum Token {
    Start,
    End,
    Value(i32),
}

enum Node {
    List(Vec<Node>),
    Value(i32),
}

fn main() {
    let v = vec![Token::Start, Token::Value(1), Token::End];
    parse(&v);
}

fn parse(tokens: &Vec<Token>) -> Node {
    let mut root: Vec<Node> = vec![];

    {
        tokens.into_iter().fold(vec![&mut root], handle_token);
    }

    Node::List(root)
}

fn handle_token<'a>(mut stack: Vec<&'a mut Vec<Node>>, token: &Token) -> Vec<&'a mut Vec<Node>> {
    match *token {
        Token::Start => {
            stack[0].push(Node::List(vec![])); // Add the new node to the tree
            match stack[0][0] {
                Node::List(ref mut the_vec) => stack.push(the_vec), // Add a mutable reference to the new vector so that subsequent nodes will become children of this Node
                _ => panic!(),
            };
        },
        Token::End => { stack.pop(); },
        Token::Value(v) => stack[0].push(Node::Value(v)),
    }

    stack
}

A: As @wimh mentioned, you're violating ownership.  Let me try to break it down a bit, and see if it makes sense.
stack[0][0] gives you a Node contained in a mutable borrow of a Vec.  You then try to mutably borrow the Vec contained in the Node::List variant of that Node, and add it as a mutable borrow to the outer Vec (the stack).  If this were allowed, you'd now have the outer Vec and the inner Vec able to mutate that Node's Vec at the same time.
I would try to rethink your design a bit, and see if you can make ownership a bit more clearcut.

A: After reading a blog post about modeling graphs using vector indices I decided to try a similar approach. The resulting code works and is a lot simpler:
type NodeIndex = usize;

pub fn parse(tokens: &Vec<Token>) -> Node {
    let mut root: Node = Node::List(vec![]);

    {
        tokens.into_iter().fold((&mut root, vec![]), handle_token);
    }

    root
}

fn add_node(tree: &mut Node, indices: &Vec<NodeIndex>, node: Node) -> NodeIndex {
    let node_to_add_to = get_node(tree, indices);

    match node_to_add_to {
        &mut Node::List(ref mut vec) => {
            vec.push(node);
            vec.len() - 1
        },
        _ => panic!(),
    }
}

fn get_node<'a>(tree: &'a mut Node, indices: &Vec<NodeIndex>) -> &'a mut Node {
    indices.iter().fold(tree, |node, index| match node {
        &mut Node::List(ref mut vec) => &mut vec[*index],
        _ => panic!(),
    })
}

fn handle_token<'a>(state: (&'a mut Node, Vec<NodeIndex>), token: &Token) -> (&'a mut Node, Vec<NodeIndex>) {
    let (tree, mut index_stack) = state;

    match *token {
        Token::LParen => {
            let new_index = add_node(tree, &index_stack, Node::List(vec![]));
            index_stack.push(new_index);
        },
        Token::RParen => { index_stack.pop(); },
        Token::Identifier(ref identifier) => { add_node(tree, &index_stack, Node::Identifier(identifier.to_owned())); },
        Token::Number(number) => { add_node(tree, &index_stack, Node::Number(number)); },
        Token::Str(ref s) => { add_node(tree, &index_stack, Node::Str(s.to_owned())); },
        Token::EOF => { assert!(index_stack.is_empty()); },
    }

    (tree, index_stack)
}


text:
Q: Convert 12hr Time String to DateTime object So I'm processing some raw XML and it has a time element with a value as such
10:30PM
or conversely
10:30AM
etc etc
The Date is presumed to be today...
If I was to use DateTime.TryParse; would anyone be willing to help out crafting a FormatProvider would to do the job?
It doesn't have to be DateTime.TryParse if anyone else has a smarter solution..

A: You don't need to use a custom format provider - you just need to specify a custom format string with the AM/PM designator specifier ("tt"):
DateTime result;
if (DateTime.TryParseExact(text, "hh:mmtt", CultureInfo.InvariantCulture,
                           DateTimeStyles.None, out result))
{
    Console.WriteLine("Parsed to: {0}", result);
}

A: You can try this with DateTime.TryParseExact and make sure about format like hhfor 12 hrs and HH for 24Hrs, same for minute MM for month and mm for minute. Check here for more custom options :
string strTime = "10:30AM";
DateTime dtTime;
if(DateTime.TryParseExact(strTime, "hh:mmtt",
   System.Globalization.CultureInfo.InvariantCulture,
   System.Globalization.DateTimeStyles.None, out dtTime))
 {
    Console.WriteLine(dtTime);
 }


text:
Q: error field not showing in django crispy forms? Here is my form class:
class VinForm(forms.Form):
    VIN = forms.CharField(min_length=13,max_length=13, label='VIN')

    def __init__(self, *args, **kwargs):
        super(VinForm, self).__init__(*args, **kwargs)
        self.helper = FormHelper()
        self.helper.form_method = 'post'
        self.helper.form_class = 'form-horizontal col-xs-12 col-md-6 col-lg-5'
        self.helper.label_class = 'col-xs-3 col-md-3 col-lg-3'
        self.helper.field_class = 'col-xs-12 col-md-12 col-lg-12'

        self. helper.layout = Layout(
            Fieldset(
                'Get vehicle info',
                Field('VIN', autofocus=True, placeholder='JN1HJ01F8RT231164'),
            ),
            FormActions(
                Submit('submit', 'get vehicle info'),
            ),
        )

Please note that I'm not using a ModelForm since there is no need for it. When I enter 3 digits for the VIN it should show an error. Currently it is not showing any error. How can I fix this?
Here is my rendering in template:
{% load crispy_forms_tags %}
   {% crispy form %}

my view:
class HomePageView(FormView):
    success_url = '/dashboard/'
    template_name = 'home.html'
    form_class = VinForm

    def get_context_data(self, **kwargs):
        context = super(HomePageView, self).get_context_data(**kwargs)
        context['vehicle_count'] = 1234  #Glucose.objects.count()
        form =  VinForm()
        context['form'] = form
        return context


text:
Q: Reading a file with fscanf() I have used fgets as well as fscanf to read a file line by line but all the time I have got some wrong output.
1st line of the file contain 149 characters and 2nd line contains 122 characters, but in my output file it shows 1st line contain 149 but 2nd line contain 128.

A: By output file do you mean to say that you are reading from one file and writing it into another? Are you manipulating the string before writing it? If that is the case then maybe your manipulaion is repositioning the newline characther. Just a guess. We will need to see the code.


text:
Q: Output of RC circuit is just a straight line The two images below are the simple circuit I developed. It consists of a pre-amplifier, a filter, an RC circuit that acts like an exponential average circuit, a peak detector and perhaps I still need to do another amplifier in order to use the entire range of the ADC I intended to connect.

Here are the signals at some of the nodes:

Everything works ok till it reaches that RC circuit.  I have a time constant of 30ms and the signal just comes horizontally with no significant variation.  What's happening? If I zoom in it's the equal to the input wave but just much smaller.
The peak detector just does what it does, the input of the peak is a straight line so the output will also be one.
The RC circuit I used was inspired by this:

I initially wanted to do a true RMS circuit but I just couldn't find a way to do the square circuit with a 5 volts supply so I just did an "averaging" circuit, good enough for my application I hope.
If I were to connect this circuit to an ADC, how exactly would I build an amplifier that goes to the input range (0V to 3.3V) of the ADC? I could use an op-amp in non-inverting configuration but then what?

A: The long-term average value of any audio signal is 0 V.
The low-pass filter sections are DC-coupled, but the highpass sections are not.  Thus, the zero-signal DC value of the signal going into the lowpass sections is all that is left after the lowpass filter strips off all of the audio.
The solution is to move he peak detector to be before an output lowpass filter.
Separate from that, your peak detector is half-wave.  If you use another opamp as a full-wave precision rectifier, you will get a more accurate envelope shape out of the filter.

A: As mentioned in the comments, your RC low pass filter (R14 and C11) has a cutoff frequency of about 4.5 Hz.  Since your signal is composed of mostly higher frequencies, it is pretty much all filtered away.
The average of an audio signal is zero.  RMS takes the square root of the mean square.  That is, you square all the values before summing and taking the square root.   Squaring makes all the values for the mean positive.
You need to move your averaging circuit (the low pass filter) to after the point where you take the peak (which is more or less the absolute value and always positive.)

simulate this circuit – Schematic created using CircuitLab
The result will be sort of somewhat like RMS, but not really.  If you just want a value proportional to the volume of the music, then this will get you something that'll work.  If you want something that will match RMS values or other values measured with proper instruments, then this will not be sufficient - it will never really match anything as measured by proper instruments.


text:
Q: Integrating Box-Sdk with iOS application I am working with an iOS application in which i have to authenticate with help of BOX-SDK for iOS and then upload images on Box. Firstly i used the sample app of BOX-API by Mr. lopopolo and upload images with that. Currently i want to integrate the api with my iOS application . i can work with the sample application but it uses storyboard . I am using XIB in my application so i get lots of issues. Can anybody tell me how to integrate Box-api with my iOS application.
I have to integrate box-api with my iOS app.Please help me out only with the authentication process. Please explain the steps for integrating the api so that i can authenticate with view controllers and xib not with the Storyboard.
Thanks in advance.

A: You should be able to use BOXContracts sample app to achieve your goal. it is not using Storyboard. https://github.com/box/box-ios-sdk-sample-app/tree/master/BOXContracts


text:
Q: Authenticate with Twitter using Mechanize I'm using Mehanize and want to authenticate to a site Twitter OAuth for authentication.
require 'mechanize'
agent       = Mechanize.new
homepage    = agent.get(HOME_URL)
auth        = homepage.link_with(href: AUTH_URL)
form        = auth.form_with(action: AUTH_ACTION)
uname       = form.fields[2]
pword       = form.fields[3]
uname.value = 'uname'
pword.value = 'pword'
loggedin    = agent.submit(form, form.buttons.first)

The result is a 403 exception: echanize::ResponseCodeError: 403 => Net::HTTPForbidden for https://api.twitter.com/oauth/authorize -- unhandled response
I found and tried this article which shows how to handle the exception but no luck in logging in.
Any insight in how I might get this to work?


text:
Q: Why does this program automatically convert the result to INT_MIN instead of integer overflow? I'm confused as to why the result is converted into INT_MIN instead of integer overflow?
Any ideas?
#include <stdio.h>

int ft_atoi(const char *str)
{
    int sign;
    int result;

    sign = 1;
    result = 0;
    while (*str == 32 || (*str >= 9 && *str <= 13))
        str++;
    if (*str == '+')
        str++;
    else if (*str == '-')
    {
        sign = -1;
        str++;
    }
    while (*str >= '0' && *str <= '9')
    {
        printf("before: %d\n", result);
        result = (result * 10) + *str - '0';
        printf("after: %d\n", result);
        str++;
    }
    return (sign * result);
}

int main(void)
{
    printf("%d\n", ft_atoi("-2147483648"));
    return (0);
}

Result:
e1z2r7p5% ./a.out
before: 0
after: 2
before: 2
after: 21
before: 21
after: 214
before: 214
after: 2147
before: 2147
after: 21474
before: 21474
after: 214748
before: 214748
after: 2147483
before: 2147483
after: 21474836
before: 21474836
after: 214748364
before: 214748364
after: -2147483648
-2147483648

A: It can help to remember that a signed integer quantity uses the most-significant (leftmost ...) bit as a sign-bit:  0 is positive, 1 is negative.  If you "add one" to a 32-bit integer 0x7FFFFFFF (all bits on except the leftmost), you'll probably get 0x80000000 (leftmost bit on, all others zero) which, because the leftmost bit is now on, is seen as "negative."  And you might not get an "integer overflow" exception.


text:
Q: How to use the query parameters in Java Jersey Application? I am following a tutorial and also used the Stackoverflow question here.
Here is my Java class:
package com.crunchify.tutorial;

import javax.ws.rs.DefaultValue;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Consumes;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.core.UriInfo;
import org.json.simple.JSONObject;

@Path("api")
public class CrunchifyAPI {

    @SuppressWarnings("unchecked")
    @GET
    @Path("/get")
    @Consumes(MediaType.TEXT_PLAIN)
    public String get(
            @DefaultValue("111") @QueryParam("user") int user,
            @Context UriInfo uriInfo
            ) {
        MultivaluedMap<String, String> queryParams = uriInfo.getQueryParameters();
        String nameParam = queryParams.getFirst("user");
        System.out.println("Data Received: " + uriInfo.getRequestUri().getQuery()
                + " | " + nameParam);
        JSONObject obj = new JSONObject();
        obj.put("auth", true);
        String ret = JSONObject.toJSONString(obj);
        return ret;
    }
}

Following is what I am GET'ing from postman:
GET>> localhost/api/get?user=123

Response is:
{"auth":true}

Server console:
Starting Crunchify's Embedded Jersey HTTPServer...

Started Crunchify's Embedded Jersey HTTPServer Successfully !!!
Data Received: ?user=123 | null
User Authenticated: true

I have tried with passing String, Integer etc but nothing works. The uri Info is getting printed correctly and the response back is also fine. The issue is that I am not getting the parameter to be read in Java Code. I will need to pass many other parameters once I am able to get this going. Please suggest. Thanks!!

A: I think you're trying too hard. As far as I can tell, doing the following should get you what you want if you call localhost/api/get?user=123:
package com.crunchify.tutorial;

import javax.ws.rs.DefaultValue;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Consumes;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.core.UriInfo;
import org.json.simple.JSONObject;

@Path("api")
public class CrunchifyAPI {

    @SuppressWarnings("unchecked")
    @GET
    @Path("/get")
    @Consumes(MediaType.TEXT_PLAIN)
    public String get(
            @DefaultValue("111") @QueryParam("user") Integer user,
            @Context UriInfo uriInfo
            ) {
        System.out.println("Data Received: " + uriInfo.getRequestUri().getQuery()
                + " | " + name);
        JSONObject obj = new JSONObject();
        obj.put("auth", true);
        String ret = JSONObject.toJSONString(obj);
        return ret;
    }
}

All that extra stuff with the query string isn't needed if all you need is the information passed in the user parameter.

A: @QueryParam("user") int user
the value of that user int should be 123
See https://www.mkyong.com/webservices/jax-rs/jax-rs-queryparam-example/

A: Well, I think you're having a problem with Java Types.
If your user is an Integer you should pass it to String first if you want to work with a String (Integer.toString() or String.valueof()).
But the way you're passing the parameter is bothering me, I'm not sure if you can pass integers by text plain medi types.


text:
Q: Modify live camera view How can I modify live camera view on Android?
I was searching and found this app https://play.google.com/store/apps/details?id=com.fingersoft.cartooncamera as good example what I want to do. I wanted to apply some effect to my camera view as well. I need to find a way to add some effects or draw something on my camera view.
As far as I understood I have to get some video stream, apply some changes and show back in camera view.
Any ideas?
Much thanks!

A: You can find more information about this topic Android - Camera Preview and in this post.
A completely other approach would be to use OpenCV.
The smallest piece of code I could think of to get an image and preview it on the screen looks like this:
public class MainActivity extends Activity implements Callback {

    Camera camera;
    SurfaceView surfaceView;
    SurfaceHolder holder;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        surfaceView = (SurfaceView) findViewById(R.id.surfaceView1);
    }

    @Override
    protected void onResume() {
        super.onResume();
        camera = Camera.open();
        Camera.Parameters parameters = camera.getParameters();
        parameters.setPictureFormat(ImageFormat.JPEG);
        camera.setParameters(parameters);

        holder = surfaceView.getHolder();
        holder.addCallback(this);

        camera.setPreviewCallback(new PreviewCallback() {
            public void onPreviewFrame(byte[] data, Camera camera) {
                // You could apply some pixel operations directly here.
                Log.d("Camera", "Camera image aquired");
            }
        });
    }

    @Override
    protected void onPause() {
        super.onPause();
        camera.stopPreview();
        camera.release();
    }

    @Override
    public void surfaceCreated(SurfaceHolder holder) {
        try {
            camera.setPreviewDisplay(holder);
        } catch (IOException e) {
            e.printStackTrace();
        }
        camera.startPreview();
    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
    }
}

A full example that does this, can be found on GitHub.


text:
Q: FTP Monitoring issues I have windows 2003 and 2008 installed on my hosting server.
In my office there is a 2 internet line with static IPs.
When some one upload files on server I have checked the FTP log it shows my static ips.
Is it any ways to find out the local IP of my office system the file is uploaded.
If any one has a answer it will be great for me to trace out who is changing files on server. From last one month suddenly anytime one broken link is added in my sites home page and due to this my site is down.
Please help me to trace out the issue.
Thanks in advance.
Jagat Sheth

A: It sounds like your office is using NAT to share your static IPs with the computers in your local network. If that's the case, it's very unlikely you'll be able to trace back from the FTP log on your server to the private IP address within your local network.
To make it possible to identify the source of changes in future, you could configure multiple user accounts on your FTP server and give each staff member a different username and password. The FTP server should be able to keep track of which user logs in at which time. Permissions can be managed by using groups.


text:
Q: Complexity of equitable partitions We are talking about undirected simple graphs and partitions of their vertex sets into disjoint non-empty cells.  Such a partition is equitable if for any two vertices $v,w$ in the same cell, and any cell $C$, it holds that $v,w$ have the same number of neighbours in $C$. The trivial partition (with only one vertex per cell) is always equitable.
Given any partition $\pi$, there is a unique coarsest equitable partition $\bar\pi$ finer than $\pi$.  (The concepts finer and coarser include equality). This is a very old result, as also are polynomial-time algorithms for computing $\bar\pi$ from $\pi$.
Another fact is that it is NP-complete to determine if a graph has an equitable partition with every cell of size 2. (This follows from Lubiw, SIAM J Comput 10, 1981, 11–21 on noting that such a partition corresponds to a fixed-point-free automorphism of order 2.)
My question is: what else?  Are any other complexity results known? In particular:

*

*What is the complexity of: Given a regular graph, does it have any non-trivial equitable partition other than the partition with just one cell?

*What is the complexity of: Given a regular graph, does it have an equitable partition with exactly two cells?

*What is the complexity of: Given a graph and two vertices $v,w$, is there a non-trivial equitable partition which has $v,w$ in different cells?

*Is there any problem on equitable partitions with complexity equal to graph isomorphism?

A: Here is a partial answer to your fourth question.
The Fractional Graph Isomorphism problem (see the relevant paper and book) is related to the problem of computing equitable partitions of a graph. The Fractional Graph is no harder than the Graph Isomorphism problem so it seems likely that many problems on equitable partitions will be no harder than the Graph Isomorphism problem.
Consider the Graph Isomorphism problem as the problem of determining whether there is a permutation matrix $P$ such that $AP = PB$, where $A$ and $B$ are the adjacency matrices of the two graphs. This is really the problem of determining the feasibility of an integer linear program (where the entries of $P$ are the unknown variables).
The Fractional Graph Isomorphism problem is the relaxation that allows $P$ to be a doubly stochastic matrix instead of a permutation matrix. Now this problem can be posed as a linear program instead of an integer linear program, so it can be solved in polynomial time. (It is unknown whether Graph Isomorphism can be solved in polynomial time, and more generally, integer linear programming cannot be solved in polynomial time unless $\mathsf{P} = \mathsf{NP}$.)
According to the references linked above, the Fractional Graph Isomorphism is equivalent to the problem of determining whether two graphs have a common coarsest equitable partition, or simply any common equitable partition.

A: More a comment than an answer. I have (as suggested) asked a related question which is essentially about the complexity of determining if a certain eigenspace has a member with two distinct entries.
Related to this question, here is an astonishingly vague sketch of a possible type of approach for an attempted construction of a potentially difficult example for question 2: Start with a connected bipartite graph $H$ which has $2m$ vertices $v_1 \cdots v_{2m}$ all of degree $d$ (so the two halves each have $m$ vertices) but is otherwise fairly irregular. Also generate $2m$ graphs $G_1 \cdots G_{2m}$ each with  $n$ vertices, regular of degree $d^*$ and all having $0$ as an eigenvalue of reasonably high multiplicity but without any very simple eigenvectors. Now make them into a big graph $\mathcal{G}$ with $2mn$ vertices by putting in all $n^2$ edges connecting $G_i$ and $G_j$ whenever $v_iv_j$ is an edge of $H.$ There will be an enormous number of fairly complicated eigenvectors of $\mathcal{G}$ obtained by picking an arbitrary eigenvector of $0$ for each of the $G_i.$ There will also be an eigenvector which is $1$ on half the vertices and $-1$ on the other half (respecting the bipartition of $H$.) Now if the graph is just presented as a huge adjacency matrix with vertices in a very scrambled order then it will be clear that $0$ is an eignevalue of high multiplicity and our favorite program will present us a basis for the corresponding eigenspace, but it may not be obvious how to find that special eigenvector.
Left unspecified is how to pick good values for $m,n,d,d^*$ Perhaps there is a simple flaw in this description, maybe too many easy to find $0,1,-1$ eigenvectors. In that case I say that that was only a sketch. In some other way build in an equitable (two cell) partition overlaid with lots of noise.

A: For question 4, It is NP-complete to decide whether a bipartite graph $G(V_1 \cup V_2, E)$ has an automorphism of order 2 which interchange the two color classes. If we drop the order 2 requirement then the problem becomes equivalent to Graph Isomorphism problem. The correspondence between order 2 fixed-point free automorphisms and equitable partitions should help you to transfer the last result to equitable partitions (note that the requirement of interchanging the two color classes forces the automorphism to be fixed-point free).

A:
Concerning Question 1,
it seems that partitioning a hypercube into two diagonally crossing sets
is an equipartition: in the two examples shown,
each blue vertex has two neighbors in the purple set, and vice versa.
This continues to hold for $d$-dimensional hypercubes, providing
an example of a $d$-regular graph with a 2-equipartition.


text:
Q: Concatenating a list of numbers into one integer in haskell I am doing yet another Project Euler problem - Problem 38.
I have this function which returns a list of numbers but what I need is that list of numbers to be one number. It calculates the concatenated product of an integer.
f (a,b) = a*b
conProInt x n  = map f (zip (replicate n x) ([1..n]))

prob38 = maximum [ (conProInt (x) (n)) | x <- [100..500], n <- [1..9], (sort $ nub $ (decToList $ (conProInt x n) )) == (sort $ (decToList $ (conProInt x n) )), (sort $ nub $ (decToList $ (conProInt x n))) == [1..9] ]

eg:
conProInt 192 3

returns:
    [192,384,576]
what I need returned is:
    192384576
I have searched around and can't find a function or think of a function I could construct that would deliver what I need. How would I go about this?
EDIT:
I have updated the script to incorporate faster concatenation, but it doesn't return the correct result:
f (a,b) = a*b
conProInt x n  =( combine (map f (zip (replicate n x) ([1..n]))))
prob38 = maximum [ (conProInt (x) (n)) | x <- [1..50000], n <- [2..40], (sort $ nub $ (decToList $ (conProInt x n) )) == (sort $ (decToList $ (conProInt x n) )), (sort $ nub $ (decToList $ (conProInt x n))) == [1..9] ]

I'm pretty sure the pandigital test
(sort $ nub $ (decToList $ (conProInt x n) )) == (sort $ (decToList $ (conProInt x n) )), (sort $ nub $ (decToList $ (conProInt x n))) == [1..9]

won't fail. I tried to make the search as large as possible, but the maximum 9-pandigital I got was 986315724. Any suggestions? Is the range of values for n a very large one?

A: Going via Strings is probably easiest:
read $ concat $ map (show) [192,384,576]

Though you'll probably need to add a type signature:
Prelude> (read $ concat $ map (show) [192,384,576]) :: Int
192384576

A: You can use this function to concatenate a list of numbers:
concatNumbers :: [Int] -> String
concatNumbers = concat . map show

If you want the function to return the concatenation as a number, you can use read.

A: Here's an example of how to concatenate digits without converting to and from character strings.
-- foldl1' is a strict fold.  "foldl1" would also work...
import Data.List (foldl1')

-- Combine two numbers such that their digits are concatenated.
-- op 1 23 = 123, op 0 12 = 12, op 12345 67 = 1234567
op :: Int -> Int -> Int
op a b = a * power 10 (numDigits b) + b

-- How many digits does a positive number have?
numDigits :: Int -> Int
numDigits x = length . takeWhile (>= 1) . iterate (`div` 10) $ x

-- Take a positive number and raise it to a positive power.
-- power 5 2 = 25, power 10 3 = 1000
power :: Int -> Int -> Int
power x y = foldl1' (*) . take y $ repeat x

-- Take a list of numbers, and concatenate all their digits.
combine :: [Int] -> Int
combine xs = foldl1' op xs

example run:
Prelude> :m +Data.List
Prelude Data.List> let power x y = foldl1' (*) . take y $ repeat x
Prelude Data.List> let numDigits = length . takeWhile (>=1) . iterate (`div` 10)
Prelude Data.List> let op a b = a * power 10 (numDigits b) + b
Prelude Data.List> let combine xs = foldl1' op xs
Prelude Data.List> combine [192, 384, 576]
192384576
Prelude Data.List>


text:
Q: Spring singleton-scoped bean has different propeties values for different objects My app is built upon Spring + SockJs. Main page represents a table of available connections so that user can monitor them in real-time. Every single url monitor can be suspended/resumed separatelly from each other. The problem is once you suspend some monitor then you can never resume it back because ApplicationEvents property of MonitoringFacade bean suddenly becomes null for the SINGLE entity. For other entites listener keeps working pretty well. When attempt to invoke methods of such null listener NullPointerException is never thrown though.
class IndexController implements ApplicationEvents
...
public IndexController(SimpMessagingTemplate simpMessagingTemplate, MonitoringFacade monitoringFacade) {
        this.simpMessagingTemplate = simpMessagingTemplate;
        this.monitoringFacade = monitoringFacade;
    }

    @PostConstruct
    public void initialize() {
        if (logger.isDebugEnabled()) {
            logger.debug(">>Index controller initialization.");
        }

        monitoringFacade.addDispatcher(this);
    }

...

@Override
    public void monitorUpdated(String monitorId) {
        if (logger.isDebugEnabled()) {
            logger.debug(">>Sending monitoring data to client with monitor id " + monitorId);
        }

        try {
            ConfigurationDTO config = monitoringFacade.findConfig(monitorId);
            Report report = monitoringFacade.findReport(monitorId);
            ReportReadModel readModel = ReportReadModel.mapFrom(config, report);
            simpMessagingTemplate.convertAndSend("/client/update", readModel);
        } catch (Exception e) {
            logger.log(Level.ERROR, "Exception: ", e);
        }
    }

public class MonitoringFacadeImpl implements MonitoringFacade
...
private ApplicationEvents dispatcher;

  public void addDispatcher(ApplicationEvents dispatcher) {
        logger.info("Setting up dispatcher");
        this.dispatcher = dispatcher;
    }

...
 @Override
    public void refreshed(RefreshEvent event) {
        final String monitorId = event.getId().getIdentity();
        if (logger.isDebugEnabled()) {
            logger.debug(String.format(">>Refreshing monitoring data with monitor id '%s'", monitorId));
        }

        Configuration refreshedConfig = configurationService.find(monitorId);
        reportingService.compileReport(refreshedConfig, event.getData());

        if (logger.isDebugEnabled()) {
            logger.debug(String.format(">>Notifying monitoring data updated with monitor id '%s'", monitorId) + dispatcher);
        }
        dispatcher.monitorUpdated(monitorId); // here dispatcher has null value... or it's actually not

    }

void refreshed(RefreshEvent event) method succesfully receives updates from Quartz scheduler through the interface and sends it back to controller.
The question is how a singleton-scoped bean can have different property values for different objects it is applied for and why such a property becomes null even though i have never set it to null?
UPD:
@MessageMapping("/monitor/{monitorId}/suspend")
    public void handleSuspend(@DestinationVariable String monitorId) {
        if (logger.isDebugEnabled()) {
            logger.debug(">>>Handling suspend request for monitor with id " + monitorId);
        }

        try {
            monitoringFacade.disableUrlMonitoring(monitorId);
            monitorUpdated(monitorId);// force client update
        } catch (Exception e) {
            logger.log(Level.ERROR, "Exception: ", e);
        }
    }

    @MessageMapping("/monitor/{monitorId}/resume")
    public void handleResume(@DestinationVariable String monitorId) {
        if (logger.isDebugEnabled()) {
            logger.debug(">>>Handling resume request for monitor with id " + monitorId);
        }

        try {
            monitoringFacade.enableUrlMonitoring(monitorId);
            monitorUpdated(monitorId);// force client update
        } catch (Exception e) {
            logger.log(Level.ERROR, "Exception: ", e);
        }
    }


text:
Q: An Alternative to VS 2008 Designer Screen I thought the web page designer screen in 2005 was mediocre until I used the one in 2008 which I think is bad.  There is an interesting  white paper here:
http://www.west-wind.com/weblog/posts/484172.aspx
I've gotten very used to these WYSIWYG designers over the years, but I am looking now for a new way.
I make business web apps which call for data entry forms.  I don't need anything particularly artistic, but I do need to be able to line up text boxes etc on input forms so that they lkook orderly and are convenient for the user.  I use Telerik controls, and my skills with CSS are approaching passable.
People often mention that they don't use the designer, but they rarely state what approach they DO use.
What are some of the alternatives to using the VS designer?

A: I don't use any WYSIWYG editor for WebForms. I've found that there are no good WYSIWYG editors for HTML, let alone ASP.net.
My suggestion is to learn enough HTML/CSS/ASP.net that you care code entirely without the WYSIWYG editor. If you can't or don't want to do this, then you'll just have to put up with a marginal editor.

A: I think a lot of the time when people say they don't use the designer they just use the source view the majority of the time. The reason for this is the designer often generates extra HTML code you don't need or it can even be a hindrance such as adding extra css styles directly to your page, I have also had it create technically invalid html by putting bold tags in the wrong places inside a table (Although it displayed ok in most browsers).
If you are not comfortable with just the source yet, I suggest split view then at least when you are using the designer you can see what it is creating and edit to get it perfect.
Don't trust the designer over seeing your website in a few different browsers.


text:
Q: Cancel = True is not working in Workbook_BeforeClose
This clearly shows that value of cancel is true, and still my workbook closes after this! Why?
I want to cancel closing of the excel file if user input is incorrect.
I debug the code and found out that the value of Cancel was initially False, and it becomes True. But once the Sub ends, file is still closed.
(variable error is defined at workbook declaration space, so accessible within module.)
    Private Sub Workbook_BeforeClose(Cancel As Boolean)
        error = 0

        check_for_error
        If error = 1 Then
            Cancel = True
            Exit Sub
        End If

        Application.EnableEvents = False
        Sheet1.Cells.ClearContents
        Sheet2.Cells.Clear
        Application.EnableEvents = True
    End Sub

I want to cancel closing of file if error = 1.
Update:: Thanks everyone for the responses, but nothing seems to work for me! Following is how my current code looks.
Option Explicit
Dim errYes As Byte

Private Sub Workbook_BeforeClose(Cancel As Boolean)
    check_freeze_panel
    If errYes = 1 Then
        Cancel = True
        Exit Sub
    End If

    Application.DisplayAlerts = False
    ThisWorkbook.Save
    Application.DisplayAlerts = True
End Sub

errYes is returning 1, Cancel = True is being executed, and still my workbook closes.
I even tried commenting all the code, and just putting Cancel = True as suggested and guess what, it still closes!

A: Change the name of error this is a reserved word for an already existing function (see Error function) and must not be used as a variable name. And activate Option Explicit and declare all your variables.
Here is an example how you would do it correctly:
Option Explicit

Private Sub Workbook_BeforeClose(Cancel As Boolean)
    Dim ErrorsFound As Boolean
    ErrorsFound = check_for_error

    If ErrorsFound Then
        Cancel = True
        Exit Sub
    End If

    Application.EnableEvents = False
    Sheet1.Cells.ClearContents
    Sheet2.Cells.Clear
    Application.EnableEvents = True
End Sub

Function check_for_error() As Boolean
    'check and return
    check_for_error = True 'errors found
End Function

Or even shorter:
Option Explicit

Private Sub Workbook_BeforeClose(Cancel As Boolean)
    Cancel = check_for_error

    If Not Cancel Then
        Application.EnableEvents = False
        Sheet1.Cells.ClearContents
        Sheet2.Cells.Clear
        Application.EnableEvents = True
    End If
End Sub

Function check_for_error() As Boolean
    'check and return
    check_for_error = True 'errors found
End Function

A: Try this. Set Error equal to your function call and make sure it returns the right data type.
Private Sub Workbook_BeforeClose(Cancel As Boolean)
    error = check_for_error

    If error = 1 Then
        Cancel = True
        Exit Sub
    End If

    Application.EnableEvents = False
    Sheet1.Cells.ClearContents
    Sheet2.Cells.Clear
    Application.EnableEvents = True
End Sub

A: Initially Cancel is equal False, means File Close will succeed.
For me the below code works fine. When I set error = 1 then closing is cancelled whether you use "Exit Sub" or not. When I set error <> 1 then cls
When I test your Code:
Option Explicit

Private Sub Workbook_BeforeClose(Cancel As Boolean)
Dim error As Integer
error = 1

If error = 1 Then
    Cancel = True

    'Exit Sub
End If

End Sub

Just test this:
Write False and workbook should Close, and True should "stop" the closing.
Private Sub Workbook_BeforeClose(Cancel As Boolean)

Cancel = False

End Sub


text:
Q: How to set up a new program in eclipse I'm trying to write a small console program to get total events for different event actions from Google Analytics using the Google Analytics API and write them to a csv.
This is my first Java program ever, first time using Eclipse, and first time using the Google Analytics API.
I'm having some trouble getting started. The biggest problem is, I can't figure out which packages from the GA API I need to include in my import declarations.
For example, I'm trying to build a new DataQuery, but Eclipse can't resolve the type and I'm not sure how to search through the packages to see if I can find it.
Any help would be appreciated.

A: Eclipse has a keyboard shortcut crtl+shift+o for importing the correct classes automatically. You can also do it manually by hovering over the error and clicking import.

A: If you've included the jar(s) in the build path, when typing a class name just type part of it and then press ctrl+space and autocomplete will suggest classes it can find (even if you haven't imported the package).
So try typing 'DataQuer' in the code and pressing ctrl+space. Your desired class should be among the first suggested. If it's not in the list, it means it can't find your class (most likely you haven't imported the necessary jars).
Edit: As it seems the problem is missing jars, you can import a jar file by right clicking the project, then Build Path -> Configure Build Path..., then go to the 'Libraries' tab, Add external jars... and browse to the desired jar file.


text:
Q: Python 3 openpyxl UserWarning: Data Validation extension not supported So this is my first time that I'm attempting to read from an Excel file and I'm trying to do so with the openpyxl module. My aim is to collate a dictionary with a nested list as its value. However, when I get this warning when I try to run it:
UserWarning: Data Validation extension is not supported and will be removed
warn(msg)
I don't know where I'm going wrong. Any help would be much appreciated. Thanks
import openpyxl
try:
    wb = openpyxl.load_workbook("Grantfundme Master London.xlsx")
    except FileNotFoundError:
        print("File could not be found.")

sheet = wb["FUNDS"]

database = {}
for i in range(250):#this is the number of keys I want in my dictionary so loop through rows
    charity = sheet.cell(row=i + 1, column=1).value

    area_of_work = []
    org = []
    funding = sheet.cell(row=i + 1, column=14).value

    for x in range(8, 13): # this loops through columns with info I need
        if sheet.cell(row=i +1, column=x).value !="":
            area_of_work.append(sheet.cell(row=i +1, column=x).value)

    for y in range(3, 6): # another column loop
        if sheet.cell(row=i +1, column=y).value !="":
            org.append(sheet.cell(row=i +1, column=y).value)

    database[charity] = [area_of_work,org, funding]

try:
    f = open("database.txt", "w")
    f.close()
except IOError:
    print("Ooops. It hasn't written to the file")

For those asking here is a screenshot of the exception:
(

A: Excel has a feature called Data Validation (in the Data Tools section of the Data tab in my version) where you can pick from a list of rules to limit the type of data that can be entered in a cell. This is sometimes used to create dropdown lists in Excel. This warning is telling you that this feature is not supported by openpyxl, and those rules will not be enforced. If you want the warning to go away, you can click on the Data Validation icon in Excel, then click the Clear All button to remove all data validation rules and save your workbook.

A: Sometimes simply clearing the Data Validation rules in the Workbook is not a viable solution - perhaps other users rely on the rules, or maybe they are locked for editing, etc.
The error can be ignored using a simple filter, and the Workbook can remain untouched, as:
import warnings

warnings.simplefilter(action='ignore', category=UserWarning)

In practice, this might look like:
import pandas as pd
import warnings

def load_data(path: str):
    """Load data from an Excel file."""
    warnings.simplefilter(action='ignore', category=UserWarning)
    return pd.read_excel(path)

Note:
Just remember to reset warnings, else all other UserWarnings will be ignored as well.

A: Thanks, for the screenshot! Without seeing the actual excel workbook it's hard to say exactly what it is complaining about.
If you notice the screenshot references line 322 of the reader worksheet module. It looks like it is telling you the data valadation extension to the OOXML standard is not supported by the openpyxl library. It's appears to be saying it found parts of the data valadation extension in your workbook and that will be lost when parsing the workbook with the openpyxl extention.


text:
Q: jquery datepicker opening issue after validation i have a problem with my jquery datepicker that gets opened automatically when there's a
validation error on the daptepicker field.
here's the code
a("#da-ex-validate1").validate(
{

rules:{"jourferie.nombrejours":{required:true,digits:true,max:40},
       "jourferie.date":{required:true,date:true},
       "jourferie.occasion":{required:true}
       },
invalidHandler:function(e,c){var f=c.numberOfInvalids();if(f){var d=f==1?"Vous avez manqué 1 champ.  Il a été mis en évidence":"Vous avez manqué "+f+" champs. Ils ont été mis en évidence";a("#da-ex-val1-error").html(d).show();}else{a("#da-ex-val1-error").hide();}}

});

a("#da-ex-datepicker").datepicker({showOtherMonths:true,onSelect: function() { a(this).valid(); }});

so what i want is to disable this behavior.
thanks.

A: You can hide the datepicker in "invalidHandler" handler callback.
Example :
a("#da-ex-validate1").validate(
{
   //exisiting rules
   invalidHandler:function(e,c){
        // exisiting stuff
        a("#da-ex-datepicker").datepicker("hide");
   }
});

Alternately you can set the "focusInvalid" option to false to prevent focusing of invalid elements.
a("#da-ex-validate1").validate(
{
   focusInvalid : false,
   //exisiting stuff
});

Hope this will help !!


text:
Q: Flash Side-scroller game objects shakes while hero is moving I'm trying to create a side-scroller game using Citrus Engine in Flash CS5
Everything is done but just when the Hero is moving everything starts shaking!
Before I was making all objects as Movie Clips and i changed it to some images and its still the same...
Any idea what is the problem exactly?

A: It's because as your character moves across non-whole pixels (e.g. 10.5 pixels across), the other elements in the scene will round themselves to the nearest whole pixels. This means they 'dance' across a pixel as they are positioned by rounding down and rounding up.


text:
Q: Facebook is not showing Shared links image properly. "og:image" Thumbnails for posts of my site https://business-students.net/ is not appearing in Facebook.
When I share a link on Facebook, It shows the correct preview of the link thumbnail, but when posted, Thumbnail disappears. (see below)
Post Link for example: https://business-students.net/f3-fa-mcqs-quiz-1-acca/
Screenshot before posting/sharing a link. (preview)
Screenshot after posting/sharing a link.
Even Facebook debugger shows a correct image of the post. See this.
But it disappears when it is shared on facebook. [see 2]
Even, the homepage of the site doesn't show any thumbnail image there.
(See here.)
I tried to scrape so many times but no use.
I thought My website might be missing Meta Tag for Social Media, So I added these
<meta property="og:type" content="website" />
<meta property="og:url" content="<?php echo current_url(); ?>" />
<meta property="og:description" content="<?php echo $seo_description; ?>" />
<meta property="og:keywords" content="<?php echo $seo_keywords; ?>" />

<meta property="og:image" content="<?php echo $thumb; ?>" />
<meta property="og:image:secure_url" content="<?php echo $thumb; ?>" />
<link rel="image_src" href="<?php echo $thumb; ?>" />

<meta name="description" content="YOUR_DESCRIPTION_HERE" />

<meta name="keywords" content="YOUR_KEYWORDS_HERE, SEPERATED_BY_COMA" />

<meta content='English' name='language'/>
<meta http-equiv="content-language" content="en-us"/>
<html lang="en-us"/>
<title lang="en-us"/>

<b:if cond='data:blog.pageType == "index"'>
<title><data:blog.pageTitle/></title>
<b:else/>
<title><data:blog.pageName/> - <data:blog.title/></title>
</b:if>
<b:if cond='data:blog.metaDescription != ""'>
<meta expr:content='data:blog.metaDescription' name='description'/>
</b:if>
<b:if cond='data:blog.pageType == "archive"'>
<meta content='noindex, nofollow' name='robots'/>
<b:else/>
<b:if cond='data:blog.pageType == "index"'>
<b:if cond='data:blog.url == data:blog.homepageUrl'>
<meta expr:content='data:blog.title' name='keywords'/>
<meta content='index, follow' name='robots'/>
</b:if>
<b:else/>
<b:if cond='data:blog.pageTitle != data:blog.title'>
<meta expr:content='data:blog.pageName' name='keywords'/>
</b:if>
</b:if>
<b:if cond='data:blog.pageType == "item"'>
<meta content='article' property='og:type'/>
<meta expr:content='data:blog.title' property='og:site_name'/>
<meta expr:content='data:blog.pageName' property='og:title'/></b:if>
<b:if cond='data:blog.postImageThumbnailUrl'>
<meta expr:content='data:blog.postImageThumbnailUrl' property='og:image'/>
</b:if>
<meta content='global' name='distribution'/>
<meta content='1 days' name='revisit'/>
<meta content='1 days' name='revisit-after'/>
<meta content='document' name='resource-type'/>
<meta content='all' name='audience'/>
<meta content='general' name='rating'/>
<meta content='all' name='robots'/>
<meta content='en-us' name='language'/>
<meta content='USA' name='country'/>
<meta content='@twitter.com/example.Com' name='twitter:site'/>
<meta content='@example.Com' name='twitter:creator'/>
<meta content='example.Com' name='author'/>
<meta content='contact@example.Com' name='email'/>
</b:if>

But still the issue is not resolved.
Please help to resolve this strange issue.

A: I think because the image has been changed since, You would need to run it through the Facebook sharing debugger.
https://developers.facebook.com/tools/debug/?q=https%3A%2F%2Fbusiness-students.net%2Ff3-fa-mcqs-quiz-1-acca%2F
Once I clicked 'Scrape Again' it updated to the newest image.


text:
Q: What is the best way to build a database from a MS Word document? Please advise me on how to approach this problem:
I have a sequential list of metadata in a document in MS Word. The basic idea is to create a Python algorithm to iterate over the information, retrieving just the name of the PROCESS, when is made a queue, from a database.
Example metadata:

Process: Process Walker (1965)
Exact reference: Walker Process Equipment., Inc. v. Food Machinery Corp.
Link: http://caselaw.lp.findlaw.com/scripts/getcase.pl?court=US&vol=382&invol=
Type of procedure: Certiorari to the United States Court of Appeals for the Seventh Circuit.
  Parties: Walker Process Equipment, Inc.
Sector: Systems is ...
Start Date: October 12-13 Arguedas, 1965
Summary: Food Machinery Company has initiated a process to stop or slow the entry of competitors through the use of a patent obtained by fraud. The case concerned a patent on "knee action swing diffusers" used in aeration equipment for sewage treatment systems, and the question was whether "the maintenance and enforcement of a patent obtained by fraud before the patent office" may be a basis for antitrust punishment.
  Report of the evolution process: petitioner, in answer to respond...
Importance: a) First case which established an analysis for the diagnosis of dispute…

There are about 200 pages containing the information above.
I have in mind the idea of implementing an algorithm in Python to be able to break this information sequence and try to store it in a web database (an open source application that I'm looking for) in order to allow for free consultations.

A: Check out AntiWord for converting the document to plaintext, then grep and sed to convert to a format you can pipe into your script.

A: Recent versions of Word allow you to save documents in XML format. This can either be done by explicitly "saving as" and choosing XML, or unzipping a .docx file and parsing its XML. The XML formats are documented online depending on the version of Word: 2003 Office XML or 2007/2010 Office Open XML.
Anything more powerful (e.g. requiring manipulation of the documents) requires interfacing with .NET (MS Open XML SDK or Aspose.Words).


text:
Q: Parameterized table name in pandas I'm trying to parameterized the table name, so my select can be "Dynamic" in Pandas
My objectives is that , I wanted to create bunch of csv from all the table in my schema.
import pyodbc
import pandas as pd
# Some other example server values are
# server = 'localhost\sqlexpress' # for a named instance
# server = 'myserver,port' # to specify an alternate port
server = 'DESKTOP\SQLEXPRESS'
database = 'AdventureWorks2019'
username = 'sa'
password = 'password'
cnxn = pyodbc.connect('DRIVER={SQL Server};SERVER='+server+';DATABASE='+database+';UID='+username+';PWD='+ password)
cursor = cnxn.cursor()
# select 26 rows from SQL table to insert in dataframe.
query = "select t.name as table_name from sys.tables t where schema_name(t.schema_id) = 'Person' order by table_name"
df = pd.read_sql(query, cnxn)
print(df)

That's how I connect to the SQL Server and i wanted to get all table name from "Person" schema.
param=df['table_name'].iloc[0]
query = "select * from {param}"
df = pd.read_sql(query, cnxn)

But now i tried to read the tablename, it's not possible.
Because if i have 1000s tables, it would take too long and repetitive tasks to create the csv.
Sorry if my code looks not good, I'm currently still learning python and pandas
##UPDATE
So this is what i made with for loop to create txt files
for index, row in df.iterrows():
    param=row["table_name"]
    query = f"select * from Person.{param}"
    df = pd.read_sql(query, cnxn)
    filepath="C:\Users\imbea\Desktop\test"+{param}+".txt"
    df.to_csv(filepath, index=None, sep='|', mode='a')

I got an error of
SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 2-3: truncated \UXXXXXXXX escape

What i was trying to do with my new cell of code, to concate the path with the table name, and with file format of txt


text:
Q: How do I get the ObjectID associated with the authenticated Azure service principal? I created an Enterprise Application in Azure AD. I'm using that to authenticate and create resources:
AzureCredentials creds = SdkContext.AzureCredentialsFactory.FromServicePrincipal(
    ClientId, ClientSecret, TenantId, AzureEnvironment.AzureGlobalCloud);

IAzure az = Azure.Authenticate(creds);

I don't know how to get the ObjectId associated with the Enterprise Application that I used to authenticate. Is there a way?

A: You could use Microsoft Graph SDK to do that, refer to the sample below, it calls the Microsoft Graph API - List servicePrincipals, filter with appId i.e. ClientId.
GraphServiceClient graphClient = new GraphServiceClient( authProvider );

var servicePrincipals = await graphClient.ServicePrincipals
    .Request().Filter("appId eq '<ClientId here>'")
    .GetAsync();

When using the code, choose the authProvider you want, and make sure you have enough permission to call the API, it works fine on my side, the Id is the ObjectId of the service principal i.e. enterprise application.


text:
Q: Get data from dynamically compiled form i have a static variable _testVar at form that i dynamically compiled. How can i get it's value from my main program? I can execute function but i can't return value. I tryed with ref, but it's just don't work.
Example where i execute test function inside Form1 class
using System;
using System.CodeDom.Compiler;
using System.IO;
using Microsoft.CSharp;

namespace myConsoleCompiler
{
    class Program
    {
        static void Main(string[] args)
        {
            using (var foo = new CSharpCodeProvider())
            {
                var parameters = new CompilerParameters
                {
                    GenerateInMemory = true,
                    GenerateExecutable = false
                };

                parameters.ReferencedAssemblies.Add("System.dll");
                parameters.ReferencedAssemblies.Add("System.Core.dll");
                parameters.ReferencedAssemblies.Add("System.Drawing.dll");
                parameters.ReferencedAssemblies.Add("System.Windows.Forms.dll");

                var source = File.ReadAllText("form.txt");
                CompilerResults results = foo.CompileAssemblyFromSource(parameters, source);
                Type type = results.CompiledAssembly.GetType("myForm.Form1");
                object compiledObject = Activator.CreateInstance(type);

                // Execure test function from dynamically compiled form
                type.GetMethod("test").Invoke(compiledObject, new object[] { });
            }
        }
    }
}

form.txt source:
using System.Windows.Forms;

namespace myForm
{
    public partial class Form1 : Form
    {
        public static int _testVar = 0; // how can i get this var value?
        public Form1()
        {
            InitializeComponent();
        }

        public void test()
        {
            MessageBox.Show("test");
        }
    }
}

namespace myForm
{
    partial class Form1
    {
        /// <summary>
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Windows Form Designer generated code

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.richTextBox1 = new System.Windows.Forms.RichTextBox();
            this.button1 = new System.Windows.Forms.Button();
            this.SuspendLayout();
            //
            // richTextBox1
            //
            this.richTextBox1.Location = new System.Drawing.Point(12, 12);
            this.richTextBox1.Name = "richTextBox1";
            this.richTextBox1.Size = new System.Drawing.Size(260, 204);
            this.richTextBox1.TabIndex = 0;
            this.richTextBox1.Text = "";
            //
            // button1
            //
            this.button1.Location = new System.Drawing.Point(12, 222);
            this.button1.Name = "button1";
            this.button1.Size = new System.Drawing.Size(260, 40);
            this.button1.TabIndex = 1;
            this.button1.Text = "button1";
            this.button1.UseVisualStyleBackColor = true;
            //
            // Form1
            //
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(284, 274);
            this.Controls.Add(this.button1);
            this.Controls.Add(this.richTextBox1);
            this.Name = "Form1";
            this.Text = "Form1";
            this.ResumeLayout(false);

        }

        #endregion

        private System.Windows.Forms.RichTextBox richTextBox1;
        private System.Windows.Forms.Button button1;
    }
}

A: FieldInfo info = type.GetField("_testVar", BindingFlags.Public | BindingFlags.Static);
object value = info.GetValue(null);


text:
Q: URL with multiple anchor tag I have to build the URL that point directly to expedia review.
I think the best solution is to append to the URL multiple Anchor tag ID.
something like this:
http://www.expedia.it/Padova-Hotel-Hotel-M14.h4214808.Hotel-Information#reviews#BVRRDisplayContentReviewID_39211683
But it doesn't work, this url doesn't go directly to the user review.
Appending #reviews at the end of the URL the page tab is correct but i have to go directly to the user review using ID anchor Tag.
http://www.expedia.it/Padova-Hotel-Hotel-M14.h4214808.Hotel-Information#reviews
Reviews ID is BVRRDisplayContentReviewID_39211683
Does anybody knows how to hack this?

A: You can't actually 'double-anchor'..
Best place to start is to read the existing share links they provide and then hack with
that:
http://reviews.expedia.com/6510-<country/language site>/<hotel id>/review/<review id>/redirect.htm

e.g.
http://reviews.expedia.com/6510-it_it/4214808/review/39312750/redirect.htm


text:
Q: JSON parsing for ObjectiveC How to get detail data from below JSON data ?
I used Objective-C.
{
  "success" : "Y"
  "data": [
    {
      "insertId": "1",
    }
  ]
  "err" : ""
}

A: what exact data you required.
If you get response then get that response in
  NSDictionary *data = [NSJSONSerialization JSONObjectWithData: [responseString dataUsingEncoding:NSUTF8StringEncoding] options:0 error:&error];

For data:
   NSArray *array=[dictionary objectforKey:@"data"];

You get array  [ { "insertId": "1", } ]
    NSdictionary *dict=[array objectAtIndex:0];

you get dictionary in array { "insertId": "1", }

A: I will give you detail solution.
First when you get response check,whether it starts with array or dictionary.
id jsonRes = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];

I checked your response.It starts with dictionary.If you have also some doubts, check with below condition.After that get the results from the response using key.
if([jsonRes isKindOfClass:[NSDictionary class]]){
        NSDictionary *dictRes = [jsonRes copy];
        NSString *strSuccess = [dictRes objectForKey:@"success"];
        NSString *strError = [dictRes objectForKey:@"err"];
        NSString *strInsertedId = [[[dictRes objectForKey:@"data"]objectAtIndex:0] objectForKey:@"insertId"];

        NSLog(@"The Success is - %@",strSuccess);
        NSLog(@"Error is - %@",strError);
        NSLog(@"Inserted id is - %@",strInsertedId);
    }
else {
        NSLog(@"The response starts with array");
}

Below I tried your code manually,it works fine.I created json using string and I checked the result.
NSString *strJson = @"{ \"success\": \"Y\", \"data\": [{\"insertId\": \"1\" }],\"err\": \"\"}" ;
NSError *jsonError;
NSDictionary *dictRes =  [NSJSONSerialization JSONObjectWithData: [strJson dataUsingEncoding:NSUTF8StringEncoding] options:kNilOptions error:&jsonError];
NSLog(@"The response are - %@",dictRes);
NSString *strSuccess = [dictRes objectForKey:@"success"];
NSString *strError = [dictRes objectForKey:@"err"];
NSString *strInsertedId = [[[dictRes objectForKey:@"data"]objectAtIndex:0] objectForKey:@"insertId"];

NSLog(@"The Success is - %@",strSuccess);
NSLog(@"Error is - %@",strError);
NSLog(@"Inserted id is - %@",strInsertedId);

Output result is


text:
Q: Does a factor-by-factor interaction term have any literal interpretation? Following the explanations in What is the baseline level in a factor-by-factor interaction?, it is my understanding that a factor-by-factor interaction term has no literal interpretation. At the very least, it has no clear, straightforward interpretation...
Consider this example from Fox 2003. In the regression below, these two variables are categorical: year={1997,..,2002} and colour={black,white}.
require(effects)
require(lmtest)
Arrests$year <- as.factor(Arrests$year)
arrests.mod <- glm(released ~ employed + citizen + checks
                         + colour*year + colour*age,
                         family=binomial, data=Arrests)

Which yields:
> coeftest(arrests.mod)

z test of coefficients:

                       Estimate Std. Error  z value  Pr(>|z|)
(Intercept)           0.3444334  0.3100749   1.1108 0.2666514
employedYes           0.7350645  0.0847701   8.6713 < 2.2e-16 ***
citizenYes            0.5859841  0.1137717   5.1505 2.598e-07 ***
checks               -0.3666425  0.0260322 -14.0842 < 2.2e-16 ***
colourWhite           1.2125167  0.3497751   3.4666 0.0005272 ***
year1998             -0.4311794  0.2603589  -1.6561 0.0977023 .
year1999             -0.0944343  0.2615447  -0.3611 0.7180519
year2000             -0.0108975  0.2592073  -0.0420 0.9664655
year2001              0.2430630  0.2630151   0.9241 0.3554129
year2002              0.2129549  0.3532786   0.6028 0.5466444
age                   0.0287279  0.0086191   3.3330 0.0008590 ***
colourWhite:year1998  0.6519565  0.3134898   2.0797 0.0375555 *
colourWhite:year1999  0.1559504  0.3070430   0.5079 0.6115161
colourWhite:year2000  0.2957537  0.3062034   0.9659 0.3341076
colourWhite:year2001 -0.3805413  0.3040538  -1.2516 0.2107305
colourWhite:year2002 -0.6173178  0.4192551  -1.4724 0.1409086
colourWhite:age      -0.0373729  0.0102003  -3.6639 0.0002484 ***
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

In the table above, how would one interpret the coefficient for e.g. colourWhite:year1998 (significant at 5%)?
Since the baseline level is colourBlack:year1997 (or the Intercept), the level for Blacks in 1998 would be computed as follows:
Intercept + year1998

Whereas the level for Whites in 1998 would be:
Intercept + year1998 + colourWhite + colourWhite:year1998

Thus it seems to me that the coefficient for colourWhite:year1998 doesn't stand for much, really. At least it doesn't look like having any intuitive, straightforward interpretation. Does it?

A: colourWhite:year1998 is called an interaction effect. As you say, blacks in 1998 would be  Intercept + year1998. Also whites in 1997 would be Intercept + colourWhite. We would hope that color and year would just be a simple additive effect and that whites in 1998 would be Intercept + colourWhite + year1998. But sometimes, the two explanatory variables may "interact" with each other and, when combined, give a larger/smaller effect than when considered individually.
If modeled without interaction effects, with all other variables known and the same, year1998 has an -0.4311794  effect on the logit. (This is not exactly true because the estimates would be different) Now, with interaction effects, year1998 has an -0.4311794 effect if black and (-0.4311794 + 0.6519565) effect if white.
For your data, it looks like all the variables are factor variables except for age and checks? If this is correct, then variables for all the factors that are not White or 1998 are zero and drop out of the equation. The formula becomes
\begin{align}
\log{ \frac{p}{1-p}} &= Intercept + -0.3666425 * checks + 0.0287279 * age \\
& \qquad  + colourWhite + year1998 + colourWhite:year1998 \\
& \qquad  -0.0373729 * colourWhite:age \\
& \\
&= 0.3444334 - 0.3666425 * checks + 0.0287279 * age  \\
& \qquad + 1.2125167 - 0.4311794 + 0.6519565 \\
& \qquad -0.0373729 * age
\end{align}


text:
Q: Proving that a $2\times 2$ matrix set is closed under addition I have the following matrix $C$ whose elements $a$ and $b$ are real.
$\begin{bmatrix}
a & b\\
 -b&a
\end{bmatrix}$
I am supposed to show that the set of such matrices is closed under addition. I am not really sure how I am supposed to do this. Could somebody give me a hint ?

A: $\begin{bmatrix}
a & b\\
 -b&a
\end{bmatrix}+\begin{bmatrix}
c & d\\
 -d&c
\end{bmatrix}=\begin{bmatrix}
a+c & b+d\\
 -(b+d)&a+c
\end{bmatrix}$

A: I think it means that if you have two matrices with that structure and you add them, you get another matrix with the same structure. This is, let a,b,c and d be real numbers and consider the following matrices:
$$ A=
\left( \begin{array}{cc}
a & b \\
-b & a \end{array} \right)
$$ and  $$ B=
 \left( \begin{array}{cc}
c & d \\
-d & c \end{array} \right) $$
then
$$
A+B=
\left( \begin{array}{cc}
a+c & b+d \\
-(b+d) & a+c \end{array} \right) $$
which has the same structure as the two matrices that you're adding together. These matrices are really useful to represent complex numbers, where A represents the complex number a+bi and B represents the complex number c+di. They're useful because the product of these numbers is
$$(a+bi)(c+di)=(ac-bd) +(ad+bc)i$$
which is represented by the matrix
$$ P=
\left( \begin{array}{cc}
ac-bd & ad+bc \\
-(ad+bc) & ac-bd \end{array} \right)
$$
and you can check that $P=AB$, the product of both matrices.


text:
Q: change file names inside a directory I need to change all file names inside my directory from name.sql to tbl_name.sql  for example:

city.sql -> tbl_city.sql or  usr_station.sql -> tbl_usr_staion.sql

could you tell me why the following code snippet is not right please.
for file in *.sql
do
  echo $file
  fnew = 'tbl_${file}.sql'
  eval mv ${file} ${fnew}
done

A: Following these steps should make the script work:

*

*Remove eval and using just plain mv commands (try to avoid eval whenever possible, because it's considered a bad practice and can lead to some serious security issues).

*Remove the trailing spaces between the fnew, the = and the string value.

*Replace the quotes ' with double quotes " so the $file is evaluated inside the fnew assignation expression .

for file in *.sql
do
   echo $file
   fnew="tbl_${file}"
   mv "$file" "$fnew"
done

A: You may try
for file in *.sql; do mv "$file" tbl_"$file"; done

Please note, that in the mv destination there is no additional .sql suffix. It is already contained in the $file variable.


text:
Q: What is the proper way to show AlertDialog when processing onActivityResult? I am using a QR/barcode scanner library and one of the endpoints is onActivityResult.
Upon reading the result I get an invalid format (to my app) how can I prompt an AlertDialog properly. Currently, I am getting

Activity com.binscanner.*.scanner.QrScan has leaked window
  DecorView@48dd8f3[Trouble connecting to server] that was originally
  added here

Here is a snippet of how I am using the Dialog.
    private AlertDialog showSimpleAlertDialog(String title, String message, final DialogInterface.OnClickListener okListener) {
        AlertDialog alertDialog = new AlertDialog.Builder(QrScan.this).create();
        alertDialog.setCanceledOnTouchOutside(false);

        alertDialog.setTitle(title);
        alertDialog.setMessage(message);
        alertDialog.setButton(AlertDialog.BUTTON_POSITIVE, "OK", okListener);

//      alertDialog.show();
        return alertDialog;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        IntentResult result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
        showSimpleAlertDialog("Trouble connecting to server", "Going back main menu", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
             // Go to some other view
            }
        }).show();

    }

I am unsure how to get this flow work as intended.
An Intent starts by the library to start the scanner. When I scan the barcode/qrcode I do onActivityResult. I want an AlertDialog to show up, but in  the process, activities are somehow different. How can I get them properly synced up?

A: You are somehow quitiing QRScan Activity before showing dialog. The cause of quiting of that Activity might be an unhandled Exception that causes Activity to Shutdown.
Call dismiss() on the Dialog instance you created in onPause() or onDestroy().

A: One probable cause for this behavior would be un-handled orientation change. When you try to access camera for QR code, your orientation might be changed based on the capture method. This would cause your current activity to be killed and restarted.
Try to handle the orientation configuration changes by yourself. Tutorial to do so can be found here


text:
Q: Rails object will not be created Ruby 1.8.7, Rails 2.3.11
Main question: what could cause Rails to send me the index page for an object type after trying to create a new object of that type?  No errors produced, no success message, no new entries in the database
I used ruby script/generate scaffold poster owner_id:integer event_id:integer to create a standard scaffold, then ran rake db:migrate.  Without changing any files, I tried to create a new poster object, and it sent me to /posters rather than /posters/show/1, as it's supposed to do.
Other information which may be of help:
There are other object types already in place on the server.  This problem originally cropped up when I was trying to have the poster belong_to :owner and belong_to :event.
If the information was getting to the model to be validated, it would return an error blank required entries.  If I enter the data manually into the MySQL database, it shows up in the index page, and can be edited (and saved) without issue.  Because of that, I think that the issue is either in the controller file or the database itself, but nothing raised a red flag when I looked through.
I have minimal (4 weeks of a class) experience with Rails, and have been stuck on this for three days now.
routes.rb: (commented lines stripped)
ActionController::Routing::Routes.draw do |map|
  map.resources :posters
  map.resources :place_informations
  map.resources :building_polygon_coordinates
  map.resources :alternate_names
  map.resources :events
  map.resources :hours_listings
  map.resources :locations

  map.connect 'json/buildings', :controller => 'json', :action => 'buildings'
  map.resources :users
  map.resources :buildings

  map.root :controller => "home"

  map.connect ':controller/:action/:id'
  map.connect ':controller/:action/:id.:format'
end

Applicable part of development.log: (the very end; just the attempt to create a new poster; SQL calls stripped out)
Processing PostersController#index (for <my IP address> at 2011-05-26 20:32:44) [GET]
~~ SQL stuff, call timings ~~~
Rendering template within layouts/posters
Rendering posters/index
~~ SQL stuff, call timings ~~~

Processing PostersController#new (for <my IP address> at 2011-05-26 20:32:48) [GET]
~~ SQL stuff, call timings ~~~
Rendering template within layouts/posters
Rendering posters/new
~~ SQL stuff, call timings ~~~

Processing PostersController#index (for <my IP address> at 2011-05-26 20:32:56) [GET]
~~ SQL stuff, call timings ~~~
Rendering template within layouts/posters
Rendering posters/index
~~ SQL stuff, call timings ~~~

It is "get index, get new, get index"
It should be* "get index, get new, post create, get show, get index"

A: I got it fixed.
The DirectorySlash toggle in Apache had to be set to "Off".  I'm not sure why that affected it in the way that it did, but the issue was resolved after adding the line DirectorySlash Off to ".htaccess".


text:
Q: SwaggerUI through Swashbuckle documenting two different models against 1 ASP.NET WEB API action I have a scenario where my ASP.NET WEB API returns 2 different models depending upon the request object. I am using swagger UI (through swashbuckle) to document my ASP.NET WEB API and currently is unable to find a way to document these 2 models against 1 ASP.NET WEB API action.
I have tried googling but was not fruitful. any help will be appreciated.

A: The OpenAPI (formerly known as Swagger) specification version 2 does not have any way of describing two different models for the same operation.  With the new OpenAPI V3 you can use a schema with the oneOf attribute to describe multiple possible response shapes.
However, there isn't much tooling available yet for V3.


text:
Q: Selenium hanging forever while finding the preceding-sibling elements of 1st element I am trying to get the preceding element Of and from the same webelement. But as the webelement is the first webelement, there are no preceding-sibling elements, the process hangs forever.
And as I am trying to find the webelements from another webelement (rather than using driver), the implicit wait is not working as well.
@BeforeTest
public void init(){
    driver = new FirefoxDriver();
    driver.manage().timeouts().implicitlyWait(2000, TimeUnit.SECONDS);
    driver.get("https://account.box.com/login");
}

    @Test
public void testWebElem(){
    WebElement source = driver.findElement(By.xpath(".//*[@id='login-form']/div/h2"));
    System.out.println(getPositionOfWebElem(source));
}

private int getPositionOfWebElem(WebElement elem){
    String xpathExpressionFollowing = "./following-sibling::*";
    System.out.println("xPath Expression :: " + xpathExpressionFollowing);
    List<WebElement> elemsFollowing = elem.findElements(By.xpath(xpathExpressionFollowing));
    printWebelems(elemsFollowing);
    String xpathExpression = "./preceding-sibling::*";
    System.out.println("xPath Expression :: " + xpathExpression);
    List<WebElement> elemsts = elem.findElements(By.xpath(xpathExpression));
    printWebelems(elemsts);
    return 0;
}

A: Reduce your implicit wait since 2000 seconds is very L-O-N-G wait!Else webdriver will wait for 2000 seconds to find the preceding elements which isn't present!BTW if your fond of 4 digit integers, use TimeUnit.MILLISECONDS
Below Snippet worked for me
import java.util.List;
import java.util.concurrent.TimeUnit;
import org.junit.Before;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.BeforeTest;

public class Test22{

WebDriver driver;

@Before
public void init(){
 driver = new FirefoxDriver();
 driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
 driver.get("https://account.box.com/login");
}

@Test
  public void testWebElem(){
WebElement source = driver.findElement(By.xpath(".//*[@id='login-form']/div/h2"));
System.out.println(getPositionOfWebElem(source));
}

private int getPositionOfWebElem(WebElement elem){
String xpathExpressionFollowing = "./following-sibling::*";
System.out.println("xPath Expression :: " + xpathExpressionFollowing);
List<WebElement> elemsFollowing = elem.findElements(By.xpath(xpathExpressionFollowing));
System.out.println(elemsFollowing.size());
String xpathExpression = "./preceding-sibling::*";
System.out.println("xPath Expression :: " + xpathExpression);
List<WebElement> elemsts = elem.findElements(By.xpath(xpathExpression));
System.out.println(elemsts.size());
return 0;
}

}


text:
Q: Use imports with string that comes from localStorage I need to show/hide different menu based on rights that are send from database and saved in localStorage.
Here is the imported menus
import tripOrders from './tripOrders';
import orders from './orders';
import employees from './employees';

Then I use them here:
const menuItems = {
    items: [tripOrders, orders, employees]
};

I tried to make something like this, but nothing happens.
let menuFromDB = localStorage.getItem('menu-items') // <== in 'menu-items' I set tripOrders, orders, employees

const menuItems = {
    items: [menuFromDB]
};

A: You get a string from localStorage, so you can use split() to convert it to the array