Q:

RemoteWebDriver IE Clicking Links doesn't work

I am using the RemoteWebDriver and trying to execute a couple of UI tests on a remote machine under Internet Explorer:
RemoteWebDriver driver = new RemoteWebDriver(new URL("http://127.0.0.1:4444/wd/hub"),  DesiredCapabilities.internetExplorer());`
driver.get("http://bing.com");
driver.findElement(By.id("sb_form_q")).sendKeys("Cheese");
driver.findElement(By.id("sb_form_go")).click();

Using the following code works in FireFox and Chrome but not in IE.  IF I run a plain web driver on my local machine it works fine.  Does anyone know why this is the case or if there is a work around?
I am using Selenium-Server-Standalone-2.8.0 and the Selenium-Java-2.8.0 client drivers.
Thanks in advance.

A:

I had problems with clicking using RemoteWebDriver and IE capabilities. I solved it by using sendKeys(Keys.ENTER) for links/buttons and sendKeys(Keys.SPACE) for radio buttons/checkboxes.


Q:

Controller action in IFrame "src" attribute - YII Framework

I am trying to call the controller action in IFrame src,
$('#iframe').attr('src', 'controller/action');

How to call the controller action in the above line inside JavaScript function ?
 <?php
 echo CHtml::imageButton(Yii::app()->request->baseUrl.'/images/new.jpg'
,array('id'=>'reflist-button'
,'style'=>'display:inline-block',
'onclick'=>'$("#cru-frame-RefNew").attr("src","-----How to call controller action -------");
$("#RefList-New").dialog("open"); return false;'));?>

A:

try this
// save your url in a varible first
$myPath=Yii::app()->createUrl('controller/action');

and then change this
'onclick'=>"$('#cru-frame-RefNew').attr('src',$myPath);
$('#RefList-New').dialog('open'); return false;"


Q:

issue with XMLHttpRequest - returning status of 0 on local machine and live server

i am having trouble getting this XMLHttpRequest to work properly, this is my first time using ajax so i'm not sure if i'm formatting everything correctly. i have looked all over the web and i keep finding basically the same info and examples but certain elements are in different orders so i'm not sure which is correct and i've tried them all and nothing seems to work. here is my code:
function ajaxRequest(){
    var activexmodes=["Msxml2.XMLHTTP", "Microsoft.XMLHTTP"]
    if (window.XMLHttpRequest)
        return new XMLHttpRequest()
    else if (window.ActiveXObject){
        for (var i=0; i<activexmodes.length; i++){
            try{
                return new ActiveXObject(activexmodes[i])
            }
            catch(e){
                //suppress error
            }
        }
    }
    else
        return false
}
function getData(fileName){
    var fileLoc =encodeURI("assets/"+fileName+".html")
    alert(fileLoc)
    var request = new ajaxRequest()
    request.open("GET",fileLoc,true)
    var response = request.responseText
    alert(request.status)
    alert(response)
    request.send(null)
    return response
}
function home() {
    var data = getData("home")
    var contentDiv = document.getElementByClassName(content)
    contentDiv.innerHTML = data;
}

home is triggered when the user clicks on a div in the page. i know that getData is being accessed because the alerts pop up, however i get a status code of 0, this happened on both my local machine and on a live server. i read that localhosts can throw a 0 status regardless of the actual status but its happening on a live server as well. if someone could help me fix this issue and/or clarify the correct order of events in the function i would greatly appreciate it.
EDIT:
new code:
function getData(fileName){
    fileLoc = encodeURI("assets/"+fileName+".html")
    alert(fileLoc);
    request.onreadystatechange = processData;
    request.open("GET",fileLoc, false);
    request.send();
    alert(request.readyState);
    alert(response);
}
function processData(){
    if (request.readyState==4){
        if (request.status==200){
            document.getElementsByClassName('content').innerHTML = request.responseText;
        }
        else{
            alert("An error has occured making the request");
        }
    }
}

A:

You are telling XMLHTTPRequest to send the request asynchronous, which means the rest of your script gets executed while you wait for the response. You will get a reponse code 0 (uninitialized) and an empty response, because at the time you return from the function that is the current status and response.
Instead you want to define a function to call when the state changes, or let XMLHTTPRequest work synchronous.
Please refer to this tutorial for a simple example that should help you out.


Q:

Yield item from a thread

from threading import Thread
import time
print 'start of script'

class MyThread(Thread):
    def __init__(self, start, end):
        self.start = start
        self.end = end
    def run(self):
        for i in xrange(self.start,self.end):
            yield i

my_threads = []

my_thread = MyThread(1,6)
my_thread.start()
my_threads.append(my_thread)

my_thread = MyThread(6,11)
my_thread.start()
my_threads.append(my_thread)

my_thread = MyThread(11,16)
my_thread.start()
my_threads.append(my_thread)

for t in my_threads:
    print t.join()

print 'end of script'

How can I do this correctly?
I'm trying to print the numbers: range(1,16) where I"m getting this number from the output of a function run in a separate threads.
I understand that I won't get this range of numbers sequentially, as is the nature of functions run in separate threads.
I also know I can simply print them in the thread's function itself, but that's not the point, I'd like to print what I've yielded back in the main thread or main portion of my code.

A:

Threads don't return values, so you won't be able to yield values back to your main thread as you hope to. If you were to get your script to run (you would need to change the name of your start variable to something else since you're shadowing the start method), you would observe that the return value of t.join() is None. A common way to solve this is with a Queue, as was suggested in this similar question: Return value from thread
In your case, instead of calling yield i I would call queue.put(i) where queue was the Queue.Queue passed in during construction, then have a loop in the main thread before I joined my threads:
while True:
    try:
        print outqueue.get(True, 1)
    except Empty:
        break

for t in my_threads:
    print t.join()

That will wait up to 1 second for a new item before throwing Empty and breaking out of the while loop.


Q:

Why is this MySQL insert so slow?

CREATE  TABLE IF NOT EXISTS `church` (
  `church_id` INT(11) NOT NULL AUTO_INCREMENT ,
  `name` VARCHAR(40) NOT NULL ,
  `city_id` SMALLINT(4) UNSIGNED ZEROFILL NOT NULL ,
  `validated` TINYINT(1) NULL ,
  PRIMARY KEY (`church_id`) ,
  INDEX `church.city_id-city.city_id_idx` (`city_id` ASC) ,
  UNIQUE INDEX `church-city_id` (`name` ASC, `city_id` ASC) ,
  CONSTRAINT `church.city_id-city.city_id`
    FOREIGN KEY (`city_id` )
    REFERENCES `city` (`city_id` )
    ON DELETE RESTRICT
    ON UPDATE RESTRICT)
ENGINE = InnoDB
DEFAULT CHARACTER SET = utf8

I have this table church on my localhost (laptop). When I do an insert on it (it has 10 rows right now), it takes 160ms.

The church_id is used as a foreign key in other tables.
The name and city_id should together be unique.
The city_id is a foreign key

Isn't this a but much, and have I done something wrong?

A:

Inserts have to do quite a bit of work:

Lock the table
Check unique index constraints
Check foreign key constrains
Write the new record
Update indexes
Unlock the table
Write the transaction log


Q:

Is it safe to call ConnectivityManager's requestNetwork() on Main thread?

Is it safe to call requestNetwork() Interface of ConnectivityManager via Main thread or it pauses threat of ANR error ?

A:

Yes. This is an async operation. You'll receive updates via ConnectivityManager.NetworkCallback callback.
Don't forget to unregister with unregisterNetworkCallback when updates are no longer needed to avoid memory leaks.


Q:

mysterious difference between rake test and ruby

Here is the mysterious:
I have a scope which looks like this (in Image.rb)
  scope :moderate_all, delegates.where("moderation_flag = #{$moderation_flags[:not_moderated]}")

Note that delegates is another scope that I am defining before moderate_all
When I leave it like this, I can run my test that checks if an image has been "checked-out" it is not available anymore. I don't put the code of the test, because it does not matter actually.
With this code, when I run "rake test" it fails, but if I do "ruby test/unit/image_test.rb" it works! I was thinking I am starting to have a bad day. Then I tried
  scope :moderate_all, lambda {
    delegates.where("moderation_flag = #{$moderation_flags[:not_moderated]}")
  }

And "rake test" passes!
So my problem is solved, but why?

A:

$moderation_flags looks like a global, and  the value of the named scope depends on it. My guess is that rake test loads the class before the global is ready, but invoking the test directly goes the other way.
Introducing the lambda causes the where clause to be evaluated when the scope is used, so it always happens late when the global is ready.


Q:

How to create audit log / audit trail in asp.net mvc

When we are used code first or entity framework then there is easiest way to audit trail the actions like add , update and delete.

A:

Create a class for capture the changes or track the changes when entity added, modifies or deleted.
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Linq;
using System.Text;
using System.Web;

namespace MVC_AuditTrail.Models
{
public class AuditTrailFactory
{
    private DbContext context;

    public AuditTrailFactory(DbContext context)
    {
        this.context = context;
    }
    public Audit GetAudit(DbEntityEntry entry)
    {
        Audit audit = new Audit();
        // var user = (User)HttpContext.Current.Session[":user"];
        audit.UserId = "swapnil";// user.UserName;
        audit.TableName = GetTableName(entry);
        audit.UpdateDate = DateTime.Now;
        audit.TableIdValue = GetKeyValue(entry);

        //entry is Added
        if (entry.State == EntityState.Added)
        {
            var newValues = new StringBuilder();
            SetAddedProperties(entry, newValues);
            audit.NewData = newValues.ToString();
            audit.Actions = AuditActions.I.ToString();
        }
        //entry in deleted
        else if (entry.State == EntityState.Deleted)
        {
            var oldValues = new StringBuilder();
            SetDeletedProperties(entry, oldValues);
            audit.OldData = oldValues.ToString();
            audit.Actions = AuditActions.D.ToString();
        }
        //entry is modified
        else if (entry.State == EntityState.Modified)
        {
            var oldValues = new StringBuilder();
            var newValues = new StringBuilder();
            SetModifiedProperties(entry, oldValues, newValues);
            audit.OldData = oldValues.ToString();
            audit.NewData = newValues.ToString();
            audit.Actions = AuditActions.U.ToString();
        }

        return audit;
    }

    private void SetAddedProperties(DbEntityEntry entry, StringBuilder newData)
    {
        foreach (var propertyName in entry.CurrentValues.PropertyNames)
        {
            var newVal = entry.CurrentValues[propertyName];
            if (newVal != null)
            {
                newData.AppendFormat("{0}={1} || ", propertyName, newVal);
            }
        }
        if (newData.Length > 0)
            newData = newData.Remove(newData.Length - 3, 3);
    }

    private void SetDeletedProperties(DbEntityEntry entry, StringBuilder oldData)
    {
        DbPropertyValues dbValues = entry.GetDatabaseValues();
        foreach (var propertyName in dbValues.PropertyNames)
        {
            var oldVal = dbValues[propertyName];
            if (oldVal != null)
            {
                oldData.AppendFormat("{0}={1} || ", propertyName, oldVal);
            }
        }
        if (oldData.Length > 0)
            oldData = oldData.Remove(oldData.Length - 3, 3);
    }

    private void SetModifiedProperties(DbEntityEntry entry, StringBuilder oldData, StringBuilder newData)
    {
        DbPropertyValues dbValues = entry.GetDatabaseValues();
        foreach (var propertyName in entry.OriginalValues.PropertyNames)
        {
            var oldVal = dbValues[propertyName];
            var newVal = entry.CurrentValues[propertyName];
            if (oldVal != null && newVal != null && !Equals(oldVal, newVal))
            {
                newData.AppendFormat("{0}={1} || ", propertyName, newVal);
                oldData.AppendFormat("{0}={1} || ", propertyName, oldVal);
            }
        }
        if (oldData.Length > 0)
            oldData = oldData.Remove(oldData.Length - 3, 3);
        if (newData.Length > 0)
            newData = newData.Remove(newData.Length - 3, 3);
    }

    public long? GetKeyValue(DbEntityEntry entry)
    {
        var objectStateEntry = ((IObjectContextAdapter)context).ObjectContext.ObjectStateManager.GetObjectStateEntry(entry.Entity);
        long id = 0;
        if (objectStateEntry.EntityKey.EntityKeyValues != null)
            id = Convert.ToInt64(objectStateEntry.EntityKey.EntityKeyValues[0].Value);

        return id;
    }

    private string GetTableName(DbEntityEntry dbEntry)
    {
        TableAttribute tableAttr = dbEntry.Entity.GetType().GetCustomAttributes(typeof(TableAttribute), false).SingleOrDefault() as TableAttribute;
        string tableName = tableAttr != null ? tableAttr.Name : dbEntry.Entity.GetType().Name;
        return tableName;
    }
}

public enum AuditActions
{
    I,
    U,
    D
}
}

Then create audit table entity and context class.
And Override savechanges method in this method get audit changes and save before base entity saved.
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Linq;
using System.Web;

namespace MVC_AuditTrail.Models
{
    public class Student
    {
        public int StudentID { get; set; }

        public string Name { get; set; }

        public string  mobile { get; set; }
    }

    public  class Audit
    {
        public long Id { get; set; }
        public string TableName { get; set; }
        public string UserId { get; set; }
        public string Actions { get; set; }
        public string OldData { get; set; }
        public string NewData { get; set; }
        public Nullable<long> TableIdValue { get; set; }
        public Nullable<System.DateTime> UpdateDate { get; set; }
    }

    public class StdContext : DbContext
    {
        private AuditTrailFactory auditFactory;
        private List<Audit> auditList = new List<Audit>();
        private List<DbEntityEntry> objectList = new List<DbEntityEntry>();
        public StdContext() : base("stdConnection")
        {
            Database.SetInitializer<StdContext>(new CreateDatabaseIfNotExists<StdContext>());
        }

        public DbSet<Student> Student { get; set; }
        public DbSet<Audit> Audit { get; set; }

        public override int SaveChanges()
        {
            auditList.Clear();
            objectList.Clear();
            auditFactory = new AuditTrailFactory(this);

            var entityList = ChangeTracker.Entries().Where(p => p.State == EntityState.Added || p.State == EntityState.Deleted || p.State == EntityState.Modified);
            foreach (var entity in entityList)
            {
                Audit audit = auditFactory.GetAudit(entity);
                bool isValid = true;
                if (entity.State == EntityState.Modified && string.IsNullOrWhiteSpace(audit.NewData) && string.IsNullOrWhiteSpace(audit.OldData))
                {
                    isValid = false;
                }
                if (isValid)
                {
                    auditList.Add(audit);
                    objectList.Add(entity);
                }
            }

            var retVal = base.SaveChanges();
            if (auditList.Count > 0)
            {
                int i = 0;
                foreach (var audit in auditList)
                {
                    if (audit.Actions == AuditActions.I.ToString())
                        audit.TableIdValue = auditFactory.GetKeyValue(objectList[i]);
                    this.Audit.Add(audit);
                    i++;
                }

                base.SaveChanges();
            }

            return retVal;
        }
    }
}


Q:

Why is this JavaScript code invalid in Firefox?

I accidentially typed in \s instead of " ",
while(cname.charAt(cname.length-1) == "\s")

Aren't special characters resolved in all string literals?
Also, what is a proper regular expression to cut off all tabs and spaces from EOL?
The my /(.*)[\s\t]/ selector just won't work! So I had to fallback to while(if.. substr).

A:

\s is only a character class for spaces, tabs and newlines in a regular expression. "\s" becomes just "s" in this case.
Removing tabs and spaces from EOL with:
cname = cname.replace(/\s+$/mg, '');

\s+ matches one or more spaces or tabs
$ matches the end of the subject
The m flag causes $ to match the end of a line, and not the string.
the g flag causes all matches to be replaced.


Q:

Chaining background NSURLSession uploads

Has anyone been successful in chaining NSURLSession background uploads?
I am trying to upload a huge video file in 5 MB parts using background upload of NSURLSession. The uploads has to be in order. The whole thing works fine in foreground. I am using AFNetwoking for this, and its a multi part upload. But when the app is in background, the first item uploads fine and starts the second one in background (in setDidFinishEventsForBackgroundURLSessionBlock of AFURLSessionManager). But it stops abruptly (my best guess is in 30 seconds, as an app woken up in background has a max lifetime of 30 sec) and then nothing happens. I expected the second session will finish in background and call up the third etc - a chain behaviour, but this just does not seem to work.
I have tried adding all file parts to a single NSURLSession in one go with a HTTPMaximumConnectionsPerHost = 1 - this works fine and uploads the full file in parts. But the file parts are picked in random order, i.e. part 1 gets uploaded, then part 5, part 3, part 10 etc …. I tried adding this in an NSOperationQueue with dependency between operations and this seems to mess up the entire thing - the upload does not work at all.
I know that the video file can be uploaded as a single file in background, but the server expects this in 5 MB parts. Hence I guess my only option is to chain uploads, or add all the parts to a NSURLSession, but make sure they are always uploaded in the order they are added.
Any help would be appreciated.
My code:
 - (void)viewDidLoad {

    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    NSURLSessionConfiguration *config = [NSURLSessionConfiguration backgroundSessionConfigurationWithIdentifier:[NSString stringWithFormat:@"%d", rand()]];
    AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:config];
    config.HTTPMaximumConnectionsPerHost = 1;
    [manager setDidFinishEventsForBackgroundURLSessionBlock:^(NSURLSession *session) {

        dispatch_async(dispatch_get_main_queue(), ^{
            // Call the completion handler to tell the system that there are no other background transfers.
            //                completionHandler();
            [self upload];
        });
    }];
}

- (IBAction)start:(id)sender {

    [self upload];
}

-(void) upload {

    NSString *filePath = [[NSBundle mainBundle] pathForResource:@"Sample" ofType:@"mp4"];
    AFHTTPRequestSerializer *serializer = [AFHTTPRequestSerializer serializer];

    NSDictionary *parameters = [NSDictionary dictionaryWithObjectsAndKeys:@"234", @"u", @"Sample.mp4", @"f",nil];
    NSMutableURLRequest *request = [serializer multipartFormRequestWithMethod:@"POST" URLString:urlString parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
        [formData appendPartWithFileURL:[NSURL fileURLWithPath:filePath] name:@"data" fileName:@"Sample.mp4" mimeType:@"video/mp4" error:nil];
    } error:nil];

    __block NSString *tempMultipartFile = [NSTemporaryDirectory() stringByAppendingPathComponent:@"Test"];
    tempMultipartFile = [tempMultipartFile stringByAppendingString:[NSString stringWithFormat:@"%d", rand()]];
    NSURL *filePathtemp = [NSURL fileURLWithPath:tempMultipartFile];
    __block NSProgress *progress = nil;
    [serializer requestWithMultipartFormRequest:request writingStreamContentsToFile:filePathtemp completionHandler:^(NSError *error) {
        NSURLSessionUploadTask *uploadTask = [manager uploadTaskWithRequest:request fromFile:filePathtemp progress:&progress completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {

            NSLog(@"Request--> %@.\n Response --> %@ \n%@",  request.URL.absoluteString ,responseObject, error? [NSString stringWithFormat:@" with error: %@", [error localizedDescription]] : @""); //Lets us know the result including failures
            [[NSFileManager defaultManager] removeItemAtPath:tempMultipartFile error:nil];

        }];
        [uploadTask resume];
        [manager setTaskDidSendBodyDataBlock:^(NSURLSession *session, NSURLSessionTask *task, int64_t bytesSent, int64_t totalBytesSent, int64_t totalBytesExpectedToSend) {

            NSLog(@"uploading");
        }];
    }];
}

A:

Well, finally I reached out to Apple for clarifications on chaining background uploads - This is not possible in iOS.NSURLSession has a Resume Rate Limiter which prevents apps from executing chained tasks in background as explained in https://forums.developer.apple.com/thread/14854. Instead, apple suggests batch transfers or other options like https://forums.developer.apple.com/thread/14853. The other thing I was asking was to order the multiple tasks in upload queue - i.e, force NSURLSession to upload tasks in the order in which they are added. As pointed by dgatwood, using an NSOperationQueue is not possible and Apple also mentioned the same.As mentioned by eskimo in response mail "NSURLSession does not guarantee to run your requests in order and there’s no way to enforce that." So I am pretty much left option less on my original problem.


Q:

Login to salesforce with oauth 2.0 directly from external app using ajax

I want to be able to login directly from my .net application's login (without having to use the user's security token). And I was wondering if it was possible to send my username and password to the salesforce OAuth endpoints via Ajax and then retreive the access token and other values without getting redirected to the salesforce page. And if it were possible how would I implement it? Since I'm a complete beginner when it comes to this so any help would be appreciated.
And I'm not sure about this but wouldn't sending the username and password be a security risk? Or is there a way to protect these informations.
And if someone wanted to clarify this a bit it would be great since I'm still looking around these solutions.

A:

Using OAuth, you will need to redirect to Salesforce. Salesforce employs a number of login security features depending on the user's permissions and customization. For example, you can use the Lightning Login app, an SMS single-use code, an email single-use code, etc; if their browser is already authenticated, no code will be required and they may even log in automatically. The security token is only required if you use the SOAP login() call. Your app doesn't need to open a new window; you can just use a WebView (or similar) to perform the login action if you prefer to keep everything in the same window. However, the downside is that the user will likely need to use whatever 2FA is configured (e.g. one-time code).


Q:

Redundancy when reading USB serial port (C;Mac OSX;Arduino)

I'm writing a simple C program that can read data from a USB port that is connected to my Arduino device. The Arduino outputs data at a baud rate of 9600 in chunks of 4 bytes.
I want the input from the Arduino to my computer to look something like this:
136.134.132.130.129.127.126.124.121.119.117.115.113.111.
However, I'm getting something like this:
271.274.281..2.4062.4022.40225.4021
Question: How do I get the input in my C program to neatly synchronize with out loosing data/ rereading data? Are there some kind of flags that could tell my program when the port has new data?
Code:
#include <stdio.h>   /* Standard input/output definitions */
#include <string.h>  /* String function definitions */
#include <unistd.h>  /* UNIX standard function definitions */
#include <fcntl.h>   /* File control definitions */
#include <errno.h>   /* Error number definitions */
#include <termios.h> /* POSIX terminal control definitions */
#include <sys/types.h>

int open_port(void)
{
  int fd; /* File descriptor for the port */

  fd = open("/dev/tty.usbmodemfd121", O_RDWR | O_NOCTTY | O_NDELAY);
  if (fd == -1)
  {
    perror("open_port: Unable to open /dev/tty");
  }
  else
    fcntl(fd, F_SETFL, 0);

  struct termios options;
  tcgetattr(fd,&options);
  cfsetospeed(&options,B9600);
  options.c_cflag |=(CLOCAL | CREAD);
  tcsetattr(fd, TCSANOW, &options);

  return (fd);
}

int main (){

    int i;
    for(i=0; i<50; i++){

    fcntl(open_port(), F_SETFL, FNDELAY);
    char buf[5];
    size_t nbytes;
    ssize_t bytes_read;

    nbytes = sizeof(buf);
    bytes_read = read(open_port(), buf, nbytes);
    printf("%s ", buf);
    buf[0]=0;
    }

    return 0;

}

A:

Your program does not properly open() the serial port for reading it.
In fact it repeatedly opens it two times every iteration of the for loop.
The device should be opened only once by your program.
Instead of
for (i=0; i<50; i++) {

   fcntl(open_port(), F_SETFL, FNDELAY);

   bytes_read = read(open_port(), buf, nbytes);

}

the main program should be structured like
fd = open_port();
if (fd < 0) {
    /* handle error condition */
}
rc = fcntl(fd, F_SETFL, FNDELAY);
if (rc < 0) {
    /* handle error condition */
}
for (i=0; i<50; i++) {

   bytes_read = read(fd, buf, nbytes);
   if (bytes_read < 0) {
        /* handle error condition */
    }

}
close(fd);

Your program is too "simple".  It sets only a few attributes, and doesn't bother to check the return codes of system calls.
Is this supposed to be canonical or non-canonical (aka raw) mode (i.e. is the data ASCII text or binary)?
Refer to this Serial Programming Guide for proper setup of the serial port.

read data from a USB port

USB is a bus.
The device your program reads from is a serial port attached to that USBus.
Second coding issue
Your original code may print garbage data.
nbytes = sizeof(buf);
bytes_read = read(open_port(), buf, nbytes);
printf("%s ", buf);
buf[0]=0;

The bytes returned by the read() operation are not likely to be terminated by a NULL byte, so a string operation on that read buffer could exceed the bounds of the allocated array.
Code that would not misbehave would be something like:
nbytes = sizeof(buf) - 1;

bytes_read = read(fd, buf, nbytes);
if (bytes_read < 0) {
    /* handle error condition */
} else {
    buf[bytes_read] = 0; /* append terminator */
    printf("%s ", buf);
}

Note that nbytes is one less than the allocated size of the buffer.
This is to ensure that there is an available byte to store the string terminator byte when the read() operation returns a "full" buffer of nbytes.
For efficiency the assignment of nbytes should be performed before entering the for loop, rather than within the loop.


Q:

orgtbl-aggregate: how to handle periods (.) in column header names

I'm new to org mode and have been using Orgtbl Aggregate for tables.  I import space-separated files as org tables, add an hline to make the first row into a header, name them with #+NAME (aside: is there a better way to name a table than to just write this tag by hand above it?) and then I use org-insert-dblock:aggregate to aggregate data in a new table below.
My header-names have periods in them because they are LaTeX pgfplots-friendly.  I can't use spaces, dashes, or underscores.  The MWE below shows that Aggregate doesn't like the periods, and exhibits unpredictable behaviour when I try escaped quotes.
Can/should aggregate dblock work with the periods (how) or should I simply clean my headers first (this is what I ended up doing)?
#+NAME: mwe-table                                                                 |
| A | b.b | cc  |                                                                 |
|---+-----+-----|                                                                 |
| 1 |   3 |   4 |                                                                 |
| 1 |   4 |   5 |                                                                 |
| 2 |   6 |   7 |                                                                 |
| 2 |   8 |   9 |                                                                 |
#+BEGIN: aggregate :table "mwe-table" :cols "A mean(b.b) mean('b.b') mean(\"b.b\")"
| A | mean(b.b)                 | mean('b.b')                    |   mean("b.b") ||
|---+---------------------------+--------------------------------+---------------||
| 1 | error(7, '"Expected `)'") | error(6, '"Expected a number") | 80.6666666667 ||
| 2 | error(7, '"Expected `)'") | error(6, '"Expected a number") | 80.6666666667 ||
#+END:                                                                            |
#+BEGIN: aggregate :table "mwe-table" :cols "A mean(cc) mean(bb) mean(\'b.b\')"   |
| A | mean(cc) | mean(bb)  | mean('b.b')                    |                     |
|---+----------+-----------+--------------------------------|                     |
| 1 |      4.5 | vmean(bb) | error(6, '"Expected a number") |                     |
| 2 |        8 | vmean(bb) | error(6, '"Expected a number") |                     |
#+END:                                                                            |

A:

A new version of orgtbl-aggregate is available on Melpa and https://github.com/tbanel/orgaggregate. Column names can now contain arbitrary characters (space, dot, semicolon, etc.). Just quote them with single or double quotes.
#+NAME: funnynames
| first column | observed;number | computed/expected |
|--------------+-----------------+-------------------|
| a/experiment |             2.3 |               2.4 |
| a/experiment |            15.4 |              12.1 |
| b/test       |           -98.7 |               0.0 |
....

#+BEGIN: aggregate :table "funnynames" :cols "\"first column\" mean('observed;number');%.3f mean('computed/expected');%.4f" :cond (>= (string-to-number "observed;number") 0)
| 'first column' | mean('observed;number') | mean('computed/expected') |
|----------------+-------------------------+---------------------------|
| a/experiment   |                   8.633 |                    7.1333 |
| b/test         |                   3.350 |                    3.1500 |
#+END:

To install from Melpa, add this to your .emacs file:
(require 'package)
(add-to-list 'package-archives '("melpa" . "http://melpa.milkbox.net/packages/") t)

then type M-x package-list and search for orgtbl-aggregate.


Q:

Using Matlab to scan up from a specified row in an image to detect a new region based on intensity variation

Here is the type of images I'm working with:

You can see the pink line Ive plotted using the code below:
A=imread('b20.bmp');
AR=A(:,:,1);
[rows, columns] = size(AR);
y1 = 200;
y2 = 315;
row1 = AR(y1, :); % Extract this line of gray levels from the image.
figure, image(AR,'CDataMapping','scaled'); colormap('gray');
title('Input Image in Grayscale')
hold on;
plot([0, columns], [y2, y2], 'm');

Im looking to scan upwards from the highlighted row (315) to the first row of the image in an effort to detect the dark region, once that region is detected I'm looking to plot another line at the midpoint of the dark region, similar to  the first (the whole way across the image).
the reason I'm looking to do this is once the midpoints of the 2 regions are detected Im looking to obtain statistical information  from the 2 lines such as standard deviations and means, in an attempt to process the 2 segments to give the surrounding rows or segments an overall average value.

A:

Jonas pretty much told you how to solve it.  However, because I like playing with images, I decided to write an answer.  What I would do is extract out a sub-image that goes from rows 1 to 315, then I would independently find the average of each row.  This would give you a 315 element vector... then from this result, whatever location gives us a huge spike, that's probably where the subdivision begins.  Here's an artificial example.  I tried recreating your's with some minimal code.  I'm going to create a black and white image where the top half is black and the bottom half is white.  Once I do that, I'll add some random Gaussian noise to it with an amplitude of 10, mean of 0 and standard deviation of 1.  After this, I'll normalize the image so that it's between [0,1] in terms of the dynamic range:
%// Set random seed generator
rng(123);

%// Create black and white image.  First 250 rows is black, next 250 rows is gray
im = [zeros(250, 256); 128*ones(250,256)];

%// Add Gaussian random noise of amplitude 10, mean 0, std.dev = 1
im_noise = im + 10*randn(size(im));

%// Normalize image so it's between [0,1]
AR = (im_noise - min(im_noise(:))) / (max(im_noise(:)) - min(im_noise(:)));

I've made the noisy image stored in AR so that you can copy and paste what I'm going to try next.  For completeness, this is what the image looks like:

Now here's where the magic begins.  Let's find the average of each row between rows 1 and 315:
avgs = mean(AR(1:315,:), 2);

The 2 parameter means to operate along the columns, which means that we will find the average of each row.  This means that we will get a 315 element vector where each element is the average of a row.... so the first element is the average of row 1, second element is the average of row 2 and so on.  If we plot these averages on a normal plot, where the row number is the horizontal axis and the mean intensity is on the vertical axis, this is what we get:
plot(1:315, avgs);

As you can see, there's a clear spike at 250, and in the image I designed, right at row 250 is where I made the gray square appear.  We can determine where this spike appears by doing diff combined with max where we compute pairwise distances between elements in an array.  diff works where the first output is the second element minus the first, then the second element is the third pair minus second, and so on.  In this case, because we're transitioning from low to high, this means that whatever location gives us the highest difference means that we took a number from the right (or the highest value of the edge) to the left (or the lowest value of the edge.  Therefore, we find pairwise distances and determine the point where we have a pairwise distance that is the highest possible.  So, do something like:
[~,ind] = max(diff(avgs));

What's nice about max here is that if there are multiple values that are seen in the data that share the same maximum, we only return the first occurring value.  This is nice because once we detect our spike in the plot, we will find this result immediately.  If you did this correctly, ind should be 250.
One thing I'd like to note is that the above syntax is assuming you're transitioning from black to white.  Should you have the opposite behaviour, you'll either want to look into use min, or if you want this to be agnostic of the type of gradient you are experiencing, use max combined with abs.  That way, when we find the biggest difference, it'll either be a large positive number if it's going from black to white or a large negative number if it's going from white to black.  If we remove all of the negative values with abs, this means that no matter what the sign is, we will see this as a large positive value and so we should be able to detect the jump regardless.  Therefore, what you should do is:
[~,ind] = max(abs(diff(avgs)));

Now, all you have to do is show this image, then plot a line where this location is at:
figure;
imshow(AR);
hold on;
plot([1 size(AR,2)], [ind ind], 'r', 'LineWidth', 2);

I've made the thickness of the line 2 pixels so you can see the line clearly, and I've made it in red.  This is what we get:

Therefore, if you want to copy and paste this into MATLAB for you to run, here's the code:
avgs = mean(AR(1:315,:), 2);
[~,ind] = max(abs(diff(avgs)));
figure;
imshow(AR);
hold on;
plot([1 size(AR,2)], [ind ind], 'r', 'LineWidth', 2);


Q:

Python condition variable timeout

I have thread1 which is waiting on a condition from thread2. But it could be that thread2 is never signalling the condition variable. So I have added a timeout to the wait call in thread 1, like this:
cv.acquire()
cv.wait(1.0)
cv.release()

How can I know if the condition variable was signaled or a timeout occurred? wait does not seem to return any value. The python documentation on Condition Objects gives no clues about this.

A:

You are not supposed to care; the typical case is that your waiting thread checks some shared state until that state matches some condition.
The documentation example is thus:
cv.acquire()
while not an_item_is_available():
    cv.wait()
get_an_available_item()
cv.release()

and the documentation also states:

[…] threads that are interested in a particular change of state call wait() repeatedly until they see the desired state

If you do have a pressing need to distinguish between a timeout and a signal, you'll need to use Event objects instead; the .wait(timeout) call on an Event object returns None if the flag wasn't set (which only happens when the timeout was reached).

A:

Martijn's answer was true for older versions of Python, however in 3.2, this changed.  The method wait() now returns False on timeout.
Interestingly, there is now a wait_for() method as well. This takes a predicate method, and waits for it to evaluate to True.  Upon timing out, it returns False.


Q:

Releasing View Controllers associated with Navigation Controllers

I hav a navigation controller and one thing I couldn't seem to grasp is why when I pop a view controller, it isn't released.
When I add it to the navigation controller I release it, this to me meant that now the navigation controller is responsible for managing the view controller.
But when I pop the navigation controller, I can see that the view controllers that are popped still hang around. I know this because the notification observers are still executing.
Also I tried removing the navigation controller from the view, releasing and setting it to nil, and yet still my view controllers are hanging around.
Where and how can I release the view controllers form a navigation controller either when they are popped or when I release the navigation controller itself?
Thanks.

A:

You mention notification observers...is the view controller added to the notification center then? If that is the case I think the notification center is retaining the view controller. In viewWillDisappear remove it as an observer then in dealloc throw out an NSLog and see if it's releasing correctly now.


Q:

Camera Preview does not fill screen

This is how I am setting up the camera preview in landscape mode in my iPad3
- (void)viewDidAppear:(BOOL)animated

{
AVCaptureSession *session = [[AVCaptureSession alloc] init];
session.sessionPreset = AVCaptureSessionPreset640x480;

CALayer *viewLayer = self.vImagePreview.layer;

NSLog(@"viewLayer = %@", viewLayer);

AVCaptureVideoPreviewLayer *captureVideoPreviewLayer = [[AVCaptureVideoPreviewLayer alloc] initWithSession:session];

captureVideoPreviewLayer.frame = self.vImagePreview.bounds;
[self.vImagePreview.layer addSublayer:captureVideoPreviewLayer];

AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];

NSError *error = nil;
AVCaptureDeviceInput *input = [AVCaptureDeviceInput deviceInputWithDevice:device error:&error];
if (!input) {
    // Handle the error appropriately.
    NSLog(@"ERROR: trying to open camera: %@", error);
}
[session addInput:input];

stillImageOutput = [[AVCaptureStillImageOutput alloc] init];
NSDictionary *outputSettings = [[NSDictionary alloc] initWithObjectsAndKeys: AVVideoCodecJPEG, AVVideoCodecKey, nil];
[stillImageOutput setOutputSettings:outputSettings];

[session addOutput:stillImageOutput];

[session startRunning];

}
In the storyboard, I set the view to fill the entire screen, however it ends up looking like this:

And furthermore, the image is also rotated 90º degrees. How can I change this, so I can make the camera preview fill the entire screen?
Thanks.

A:

Rotate your layer:
    switch (self.interfaceOrientation)
    {
     case UIInterfaceOrientationLandscapeRight:
       [captureVideoPreviewLayer setAffineTransform:CGAffineTransformMakeRotation(-M_PI / 2)];
       break;
     case UIInterfaceOrientationLandscapeLeft:
       [captureVideoPreviewLayer setAffineTransform:CGAffineTransformMakeRotation(M_PI / 2)];
       break;
    }

[self.vImagePreview.layer addSublayer:captureVideoPreviewLayer];


Q:

Should we allow question about the developers?

Should we allow question about the developers?
Where do we draw the line?

A:

In my opinion, a security relevant and trust demanding software like bitcoin, justifies  that questions about the developers are allowed.. So I'm in favor to allow questions about the developers, if they

don't provoke an debate, have an clear answer
are related to the development somehow
don't get to personal

A:

I certainly agree that questions about the devs should be allowed, but only to a point. If someone really wants to don the tinfoil hat that is their prerogative, provided they do their own research somewhere other than this site.
The question you cited in your question was closed not because it is irrelevant or because questions about the devs shouldn't/can't be asked but because it was a duplicate. Perhaps not an exact duplicate, but this specific question is a subset of another question requestiong Satoshi's bio. This question should have been posed in the comments on the original.
Per Robert Cartaino (one of our SE-supplied mods, until we elect our own):

It's off topic. This site is about Bitcoin. It doens't need to become fodder for Who-is-Satoshi-Nakamoto trivia. Any biographical information you feel the need to expound on can easily be contained in the other thread. No need to perpetuate this this content of dubious value through the site.

A:

Questions about the developers are some of the most frequently asked when I talk about Bitcoin. Closing threads of this nature only prolongs the amount of time it takes for people to find answers...
It's counter-productive to obscure this information when it is one of the most commonly asked questions!


Q:

How to dynamically add and remove a tab in p:tabView component

I am trying to add a PrimeFaces <p:tab> dynamically. While adding the second tab I am getting the following exception:

"java.lang.IllegalStateException: Component ID tab0 has already been found in the view".

How can I solve this?
Here is the view code:
<h:form prependId="false">
    <p:tabView id="tabview" dynamic="true" cache="false"
        binding="#{testBean.tabView}"
        activeIndex="#{testBean.activeTab}" >
        <h:commandButton value="Close" action="#{testBean.removeTab}"/>
    </p:tabView>
    <h:commandButton value="Add Tab" action="#{testBean.addTab}"/>
</h:form>

Here is the bean code:
public String addTab() {
    String tabId="tab"+id;
    System.out.println("Gen Id: "+tabId);
    tab = new Tab();
    tab.setTitle("Title: "+tabId);
    tab.setId(tabId);

    System.out.println("Tab Id: "+tab.getId());
    tabView.getChildren().add(id,this.tab);
    id++;
    return "tabtest.jsf";
}

public String removeTab() {
    tabView.getChildren().remove(activeTab);
    return "tabtest.jsf";
}

A:

Don't manually create components if everything can just be done in the view. This construct will fail if the bean is in a broader scope than the request scope. See also e.g. Binding attribute causes duplicate component ID found in the view
Follow the showcase example "TabView with Model" which allows you to dynamically populate tabs via a sane model and <p:tabView value="..." var="..."> like as <ui:repeat>/<h:dataTable>.
E.g. this view
<h:form>
    <p:tabView value="#{bean.tabs}" var="tab">
        <p:tab title="#{tab.title}">
            #{tab.content}
            <p:commandButton value="Close" action="#{bean.remove(tab)}" update="@form" />
        </p:tab>
    </p:tabView>
    <p:commandButton value="Add Tab" action="#{bean.add}" update="@form" />
</h:form>

with this controller
@ManagedBean
@ViewScoped
public class Bean implements Serializable {

    private List<Tab> tabs;

    @PostConstruct
    public void init() {
        tabs = new ArrayList<>();
    }

    public void add() {
        tabs.add(new Tab("tab" + tabs.size(), "some content"));
    }

    public void remove(Tab tab) {
        tabs.remove(tab);
    }

    public List<Tab> getTabs() {
        return tabs;
    }

}

and this model
public class Tab {

    private String title;
    private String content;

    public Tab(String title, String content) {
        this.title = title;
        this.content = content;
    }

    public String getTitle() {
        return title;
    }

    public String getContent() {
        return content;
    }

}


Q:

value from a range in .interior.color \ VBA EXCEL 2013

I have in column F numbers , each number refers to a color code, I'm trying to auto change each cell color in F based on its value , BUT ALL COMES ONLY IN BLACK , below is my code :
Sub Highlight()
 For Each C In Worksheets("Sheet3").Range("F3:F1000")

With Sheet3.Range("$F1:$F1000")
    .FormatConditions.Delete

    With .FormatConditions.Add(Type:=xlExpression, Formula1:="=($F1<>"""")")
        .Interior.Color = C.Value
        .Font.Color = vbWhite
 End With

 End With
 Next C

End Sub
Help please & thank you in advance.

A:

I would split your code to 2 Subs:

Sub CondFormat - to apply conditional formatting (once).
Sub Highlight - to apply cell color based on it's value - more frequently.

Code
Option Explicit

Dim LastRow As Long

Sub CondFormat()

With Worksheets("Sheet3")
    LastRow = .Cells(.Rows.Count, "F").End(xlUp).Row

    With .Range("F1:F" & LastRow)
        .FormatConditions.Delete
        .FormatConditions.Add Type:=xlExpression, Formula1:="=($F1<>" & Chr(34) & Chr(34) & ")"
    End With

End With

End Sub

Sub Highlight()

Dim Rng As Range

With Worksheets("Sheet3")
    LastRow = .Cells(.Rows.Count, "F").End(xlUp).Row
    For Each Rng In .Range("F3:F" & LastRow)
        Rng.Interior.Color = Rng.Value
        Rng.Font.Color = vbWhite
    Next Rng
End With

End Sub


Q:

Does integral extension of finitely generates $k$-algebras implies finite module?

Let $k$ be a field, $ A \subseteq B$ finitely generated $k$-algebras, with $B$ integral over $A$. Is it true that $B$ is a finite $A$-module?
In the case where $A=k[x]$, $x$ transcendental over $k$, and $B$ is the integral closure of $A$ in a finite extension $L$ of the field of fractions $K=k(x)$ this follows from the properties of Dedekind domains (and/or function fields). What about the more general cases?

A:

Yes. Note that because $B$ is a finitely generated $k$-algebra, $B$ is also a finitely generated $A$-algebra (as $k$ is a field, the homomorphism $k \to A$ is injective, thus wlog $k \subset A$.)
We need two lemmas which are not difficult to prove.

Lemma 1 If $A$ is a commutative ring and $x$ is integral over $A$, then $A[x]$ is a finitely generated $A$-module

Proof: Let $x^n+a_{n-1}x^{n-1}+\dots+a_0=0$, then it is easy to see that $1,x, \dots x^{n-1}$ generates $A[x]$ as an $A$-module.

Lemma 2 If $B$ is a $A$-algebra such that $B$ is a finite $A$-module and $M$ is a finite $B$-module, then $M$ is a finite $A$-module (by restriction of scalars).

Proof: Let $b_1, \dots b_n$ be a $A$-generating system of $B$ and $m_1, \dots m_k$ be a $B$-generating system of $M$. Then obviously $(b_i m_j)_{1 \leq i \leq n, 1 \leq j \leq k}$ is an $A$-generating system of $M$.
Now we have the following proposition (note that no hypothesis on any ring being an algebra over a field is needed.)

If $B$ is a finitely generated integral $A$-algebra, then $B$ is a finite $A$-module

Proof: We proceed by induction of the number of generators $n$ of $B$ as an $A$-algebra. Lemma 1 takes care of the case $n=1$.
For the induction step, assume that $B$ is generated by $x_1, \dots x_{n+1}$ as an $A$-algebra. By the induction hypothesis, the $A$-algebra $B'$ generated by $x_1, \dots x_n$ is a finite $A$-module. But we have $B=B'[x_{n+1}]$ such that by lemma 1, $B$ is a finite $B'$-module. Thus by lemma 2, $B$ is a finite $A$-module.

A:

Right, if $B$ is a finitely generated $k$-algebra then it is a fortiori a finitely generated $A$-algebra*. Since $B$ is finitely generated and integral over $A$, it is finite over $A$ (see for example Lang's Algebra, Proposition VII.1.2).
*To be finitely generated over $k$ means there are elements $x_1,\dots,x_n$ such that every element of $B$ is a polynomial in $x_1,\dots,x_n$ with coefficients in $k$. Since $k \subseteq A$, a polynomial with coefficients in $k$ is also a polynomial with coefficients in $A$. So every element of $B$ can be written as a polynomial in $x_1,\dots,x_n$ with coefficients in $A$.


Q:

Resize a Manipulate by grabbing a corner

The following code produces an output of a Plot.
Plot[x,{x,-3,3}]

I can then resize the output by grabbing onto one of the corners of the image and dragging.
The following code produces an output of a Manipulate Plot.
Manipulate[Plot[x,{x,-3,3}],{a,0,10}]

I cannot resize the output by grabbing a corner.  The image size is fixed.  I would like to be able to change it by dragging the corner of the image with the mouse.  I realize I can program in the image size in the code above, but for convenience, I would like the ability to resize with the mouse.  Ideas?

A:

Does it fit your needs?
magnifier[expr_] := DynamicModule[{initImageSize, imageSize, mag = 1}
  , initImageSize = imageSize = Rasterize[expr, "RasterSize"]
  ; Pane[
   Magnify[expr, Dynamic@mag],
   AppearanceElements -> "ResizeArea",
   ImageSize -> Dynamic[imageSize, {Automatic, (mag = Mean[imageSize/initImageSize]) &}]
   ]
  ]

magnifier@Manipulate[Plot[a x, {x, -3, 3}], {a, 0, 10}]


Q:

How can I make an Ubuntu recovery image on external media?

I am about to expand my Ubuntu partition, so I think I should make a backup of the current one in case something goes wrong.
Is there some software to make a bootable USB and recovery image?

A:

Remastersys is the tool to go for. It allows you to make an ISO image of your system including if you want your data. You can than create a bootable USB stick. My last experience was that the live usb/cd didnt work, but installation worked. In conclusion a perfect toll for your needs and or if you want to transfer a system to a friends computer.

A:

This is rather basic, but it's guaranteed to work, provided you have an external hard drive with enough free space to hod your entire internal drive (including free space)
To Backup

Boot into a live CD/USB environment.
Determine the name of your internal hard drive. Probably, it's /dev/sda, but you should check somewhere to be absolutely sure. I use GParted for this purpose.
Mount your external drive somewhere. I'll use /media/external in these instructions. Be sure that your internal drive is not mounted!
Choose one of the following, depending on your situation. Both make use of dd to image your entire disk, not just individual partitions (you can also use this technique to migrate to an entirely different hard drive of the same size or larger):

If your external drive's filesystem can handle a single file the size of your entire internal drive, you can use the simplest option:
sudo dd if=/dev/sda of=/media/external/internal_disk.img

If you need compression or need to split the image file into multiple smaller files, use this more complex command (see the man pages for any commands you don't understand):
cd /media/external
sudo dd if=/dev/sda | bzip2 | split --bytes=2G -d - internal_disk.img.

This will first compress the contents of your disk (bzip2), then split it into 2GB chunks.

Your backup is complete.

To Restore

Boot into a live CD/USB environment.
Mount your external drive. I'll make the same path assumptions as I did above.
Choose the option that corresponds to the choice you made above:

Just copy the image to your hard drive:
sudo dd if=/media/external/internal_disk.img of=/dev/sda

Make sure that there are no other files in your backup directory that have names beginning the same as your backup chunks. Then:
cd /media/external
cat internal_disk.img.* | bunzip2 | sudo dd of=/dev/sda

Reboot. You're finished.


Q:

javascript - array does not get set back to [] (blank)

I have this code and every time that the first for loop starts again I want it to reset the array to blank as it is using a new user, but I get an out put with all the values in one array.
var items = [];
    for (var i = 0; i < userArray.length; i++) {

        items.length = 0;
        for (var i2 = 0; i2 < test.length; i2++) {

            var UserFavourite = Parse.Object.extend("UserFavourite");
            var queryUserFav = new Parse.Query(UserFavourite);
            queryUserFav.equalTo('item', test[i2].get('item'));
            queryUserFav.equalTo('school', test[i2].get('school'));
            queryUserFav.equalTo('user1', userArray[i])
            queryUserFav.find().then(function(res) {

                    for (var i3 = 0; i3 < res.length; i3++){
                        var item = res[i3];
                        var itemName = item.get('item');
                        items.push(itemName);
                        if (items !== []) {
                            console.log(items.toString()+" + ")
                        }
                    }

            });

        }
    }

userArray.length is equal to 2 and test.length is equal to 20. If you were wondering. And when it get to the first for loop I want the array to be set back to blank but it isn't?
Thanks for the help in advance.

A:

I thnk you should use set this:
items.length = 0

because items = []
creates a new array which is not the same.
Also add some promises to make the async requests wait


Q:

Override OnClose()

I got this class
class CWebBrowser2 : public CWnd

And i want to override OnClose What i have done so far is in the header file I added  void OnClose(); and in the .cpp file i added
void CWebBrowser2::OnClose ()
{
        int i=0;
        i++;
}

But the OnClose is never called.
Then I tried to to modify the header file to
afx_msg void OnClose();
DECLARE_MESSAGE_MAP()

And added this to the .cpp file
BEGIN_MESSAGE_MAP(CWebBrowser2, CWnd)
    //{{AFX_MSG_MAP(CBrowserDlg)
    ON_WM_CLOSE()
    //}}AFX_MSG_MAP
END_MESSAGE_MAP()

But still OnClose is never called. I have tried to Change to OnClose to OnDestroy but that isnt called either.
any ideas on what Im doing wrong?

A:

After adding the ON_WM_CLOSE() it should work.  In which way are you closing the window?
In your header file of your class do you have this line? DECLARE_MESSAGE_MAP()


Q:

Home and End keys stop working correctly

I am running a session of emacs in an xterm+256color terminal, i.e., with the command emacs -nw. At the start of my session, the Home and End keys work just fine. However, after a while, the Home key eventually starts producing the key code ^[[H instead of ^[OF. Why does this happen? What can I do to fix this problem?

A:

xterm has multiple keyboard modes (e.g. application mmode), and accepts escape sequences to switch between them. For example you can make the keypad send "1", "2" etc or you can get it to send sequences.
The simplest way to get it back to normal is to run 'reset' or 'tput reset', which will consult the termcap or terminfo terminal database and should output the correct escape sequences to put all the keys into a standard state.
To avoid the problem in the first place avoid using 'cat' on binary files and other sources of random escape sequences being output to your terminal which can change the modes.


Q:

RPG Game loop and class structure (cocos2D for iPhone)

I'm looking to make an RPG with Cocos2D on the iPhone. I've done a fair bit of research, and I really like the model Cocos2D uses for scenes. I can instantiate a scene, set up my characters etc. and it all works really nicely... what I have problems with is structuring a game loop and separating the code from the scenes.
For example, where do I put my code that will maintain the state of the game across multiple scenes? and do I put the code for events that get fired in a scene in that scene's class? or do I have some other class that separates the init code from the logic?
Also, I've read a lot of tutorials that mention changing scenes, but I've read none that talk about updating a scene - taking input from the user and updating the display based on that. Does that happen in the scene object, or in a separate display engine type class.
Thanks in advance!

A:

It sounds like you might do well to read up on the Model-View-Controller pattern. You don't have to adhere slavishly to it (for example, in some contexts it makes sense to allow some overlap between Model and View), but having a good understanding of it will help you to build any program that has lots of graphical objects and logic controlling them, and the need to broadcast state or persist it to disc (game save), etc.
You also have to realize that cocos2d provides a good system for structuring the graphical scene graph and rendering it efficiently, but it doesn't provide a complete infrastructure for programming games. In that sense it's more of a graphics engine than a game engine. If you try to fit your game's architecture into the structure of cocos2d, you might not end up with the most maintainable result. Instead, you should treat cocos2d as what it is: a great tool to take care of your display and animation needs.
You should definitely have an object other than the scenes that maintain the game state, because otherwise where will all the state go when you switch between scenes? And within scenes/levels, you should simply try to use good Object Oriented design to have state distributed over objects of various classes. Each character object remembers its own state etc. Here you can see where MVC becomes useful: when you save the game to disc, you want to remember each character's health level, but probably not which exact frame index the sprite animation was showing. So you need to distinguish between the sprite and the character (model) itself. That said, as I mentioned before, for game objects that don't have a lot of logic attached to them, or which don't need to be saved, it might be ok to just fuse the Model and View together into one class (basically by subclassing CCSprite).
To pull off MVC the way it's supposed to be, you should also learn the basics of Key-Value Observing. (And you'd do well to use this replacement for Apple's interface.) In more intensely real-time games, techniques like this might be too slow, but since you're making a RPG (good choice for starting out) you could probably sacrifice performance for a more maintainable architecture.
The game scene (which is just another cocos2d sprite) plays the role of Controller, in terms of the MVC pattern. It doesn't draw anything itself, but tells everything else to draw itself based on inputs and state. It's tempting to put all kinds of logic and functionality into the game scene, but when you notice that it swells, you should ask yourself how you could separate that functionality into other classes. Analyze which type of functionality you're implementing. Is it to do with data and state (Model)? Or is it about animation and rendering (View)? Or is it about connecting logic with rendering (in which case you should try to make the View observe the Model directly)?
The game scene/Controller is basically a dispatch center, which takes input events (from the user or from sprites reporting that they've hit something, for example) and decides what to do with them: it might tell one or several of the Model objects to update themselves in some way, or it might just trigger an animation in some other sprites, for example.
In a real-time game, you'd have a "tick" or "step" method in the scene which tells all objects to update themselves. This method (the game loop) is the heart of the program and is run every time a new frame is drawn. (In modern game engines there's a lot of multi-threading but let's not think about that.) But in your case, you might want to create a module that can "play the game" completely separate from the game scene. Imagine creating a program that can play chess through the terminal, using only text input. If you create the whole game system in that manner, and then connect it to the graphics engine through a small and clean interface, you'll have a really maintainable app with lots of reusable code for future projects!
Some good rules of thumb: the model (data) shouldn't know anything about sprites or display states; the view (sprites) shouldn't contain any of the game's actual logic (the game rules) but only know how to do simple things like moving and bouncing and reporting to the scene if something complicated happens. Whenever possible, the view should react to changes in the model directly, without the controller having to interfere.


Q:

Haskell UUID generation

I am new to Haskell and need help. I am trying to build a new data type that has to be somehow unique, so I decided to use UUID as a unique identifier:
data MyType = MyType {
   uuid :: UUID,
   elements :: AnotherType
}

in this way, I can do following:
instance Eq MyType where
    x == y = uuid x == uuid y
    x /= y = not (x == y)

The problem is that all known (to me) UUID generators produce IO UUID, but I need to use it in a pure code as mentioned above. Could you please suggest if there is any way to extract UUID out of IO UUID, or maybe be there is a better way to do what I need in Haskell? Thanks.

UPDATE
Thanks for all the great suggestions and the code example. From what is posted here I can say you cannot break a referential transparency, but there are smart ways how to solve the problem without breaking it and, probably the most optimal one, is listed in the answer below.
There is also one alternative approach that I was able to explore myself based on provided recommendations with the usage of State Monad:
type M = State StdGen
type AnotherType = String

data MyType = MyType {
    uuid :: UUID,
    elements :: AnotherType
} deriving (Show)

mytype :: AnotherType -> M MyType
mytype x = do
    gen <- get
    let (val, gen') = random gen
    put gen'
    return $ MyType val x

main :: IO ()
main = do
    state <- getStdGen
    let (result, newState) = runState (mytype "Foo") state
    putStrLn $ show result
    let (result', newState') = runState (mytype "Bar") newState
    setStdGen newState'
    putStrLn $ show result'

Not sure if it is the most elegant implementation, but it works.

A:

If you're looking at the functions in the uuid package, then UUID has a Random instance.  This means that it's possible to generate a sequence of random UUIDs in pure code using standard functions from System.Random using a seed:
import System.Random
import Data.UUID

someUUIDs :: [UUID]
someUUIDs =
  let seed = 123
      g0 = mkStdGen seed -- RNG from seed
      (u1, g1) = random g0
      (u2, g2) = random g1
      (u3, g3) = random g2
  in [u1,u2,u3]

Note that someUUIDs creates the same three "unique" UUIDs every time it's called because the seed is hard-coded.
As with all pure Haskell code, unless you cheat (using unsafe functions), you can't expect to generate a sequence of actually unique UUIDs without explicitly passing some state (in this case, a StdGen RNG) between calls to random.
The usual solution to avoid the ugly boilerplate of passing the generator around is to run at least part of your code within a monad that can maintain the needed state.  Some people like to use the MonadRandom package, though you can also use the regular State monad with a StdGen somewhere in the state.  The main advantages of MonadRandom over State is that you get some dedicated syntax (getRandom) and can create a monad stack that includes both RandomT and StateT so you can separate your RNG state from the rest of your application state.
Using MonadRandom, you might write an application like:
import Control.Monad.Random.Strict
import System.Random
import Data.UUID

-- monad for the application
type M = Rand StdGen

-- get a generator and run the application in "M"
main :: IO ()
main = do
  g <- getStdGen  -- get a timestamp-seeded generator
  let log = evalRand app g  -- run the (pure) application in the monad
  putStr log

-- the "pure" application, running in monad "M"
app :: M String
app = do
  foo <- myType "foo"
  bar <- myType "bar"
  -- do some processing
  return $ unlines ["Results:", show foo, show bar]

type AnotherType = String
data MyType = MyType {
   uuid :: UUID,
   elements :: AnotherType
} deriving (Show)

-- smart constructor for MyType with unique UUID
myType :: AnotherType -> M MyType
myType x = MyType <$> getRandom <*> pure x

Note that substantial parts of the application will need to be written in monadic syntax and run in the application M monad.  This isn't a big restriction -- most non-trivial applications are going to be written in some monad.


Q:

can i do this transformation with any finite group?

I have a finite alphabet $\{e_1, e_2, \cdot \cdot\cdot, e_N, a_1, a_2, \cdot\cdot\cdot, a_n \}$ where we pair $e_i$ and $a_i$ as ``opposites'' - like opposite vertexes on a regular $2N$ sided polygon but we are not restricted to the dihedral group. There is some transitive finite group of allowed transformations on these elements, but it could be any group as long as its transitive on the set. My question is: can I always realise the transformation that swaps every $e_i \leftrightarrow a_i$, i.e. swaps every element with its opposite?
If the group is ``all possible permutations'' then of course the answer is yes. If it is the cyclic group then yes again. If it is the dihedral group or either of its sub-groups then yes again. But does there exist a group that is transitive but wouldn't allow for this transformation?

A:

The alternating group $A_6$, acting on $\{e_1, e_2, e_3, a_1, a_2, a_3\}$ in the obvious way is transitive, but the "opposition" transformation is an odd permutation.


Q:

XSL Transform - select node id by string content

I have xml like this
    <mets:mets xmlns:mets="http://www.loc.gov/METS/">
  <mets:fileSec>
    <mets:fileGrp ID="REP1">
      <mets:file ID="FL1">
        <mets:FLocat LOCTYPE="URL" xlin:href="1.jpg" xmlns:xlin="http://www.w3.org/1999/xlink"/>
      </mets:file>
    </mets:fileGrp>
    <mets:fileGrp ID="REP2">
      <mets:file ID="FL2">
        <mets:FLocat LOCTYPE="URL" xlin:href="1.tif" xmlns:xlin="http://www.w3.org/1999/xlink"/>
      </mets:file>
    </mets:fileGrp>
    <mets:fileGrp ID="REP3">
      <mets:file ID="FL3">
        <mets:FLocat LOCTYPE="URL" xlin:href="2.jpg" xmlns:xlin="http://www.w3.org/1999/xlink"/>
      </mets:file>
    </mets:fileGrp>
  </mets:fileSec>
</mets:mets>

I want to get as output IDs only files with jpg extention -> FL1, FL3.
I have problems with my xsl file :
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:mets="http://www.loc.gov/METS/"
    xmlns:dc="http://purl.org/dc/elements/1.1/"
    xmlns:dcterms="http://purl.org/dc/terms/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:mods="http://www.loc.gov/mods/v3 http://www.loc.gov/standards/mods/v3/mods-3-0.xsd"
    exclude-result-prefixes="xlin">
    <xsl:output method="html" omit-xml-declaration="yes" indent="yes" />

    <xsl:template match="/">
        <xsl:for-each select="//mets:fileSec/mets:fileGrp/mets:file">
            <xsl:variable name="currentID" select="@ID" />
            <xsl:for-each select="//mets:fileSec/mets:fileGrp/mets:file/mets:FLocat">
                <xsl:variable name="testVariable" select="@xlink:href" xmlns:xlink="http://www.w3.org/1999/xlink" />
                <xsl:choose>
                    <xsl:when test="contains($testVariable, '.jpg')"><xsl:value-of select="$currentID"/>,</xsl:when>
                 </xsl:choose>
            </xsl:for-each>
        </xsl:for-each>
    </xsl:template>
</xsl:stylesheet>

But after transform I get error output as : FL1,FL1,FL2,FL2,FL3,FL3,
Please, help me with XSL.
Thank you!

A:

Would something like this work for you?
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:mets="http://www.loc.gov/METS/"
xmlns:xlin="http://www.w3.org/1999/xlink">
<xsl:output method="text" encoding="UTF-8"/>

<xsl:template match="/">
    <xsl:for-each select="mets:mets/mets:fileSec/mets:fileGrp/mets:file[contains(mets:FLocat/@xlin:href, '.jpg')]">
        <xsl:value-of select="@ID"/>
        <xsl:if test="position()!=last()">
            <xsl:text>, </xsl:text>
        </xsl:if>
    </xsl:for-each>
</xsl:template>

</xsl:stylesheet>


Q:

querying mongodb with nested where conditions

{
   "name": "comments",
   "rid": 456,

   "refs": [
     {
       "no": 1,
       "info": "this is first"
    },
     {
       "no": 2,
       "info": "this is second"
    },
     {
       "no": 3,
       "info": "this is third"
    }
  ]
}
{
   "name": "comments",
   "rid": 321,

   "refs": [
     {
       "no": 1,
       "info": "this is first-h"
    },
     {
       "no": 2,
       "info": "this is second-h"
    },
     {
       "no": 3,
       "info": "this is third-h"
    }
  ]
}

Assume I have a document structure like above. I need to get the array whose rid is 456 and no is 2. So, I just want to get the array
     {
       "no": 2,
       "info": "this is second"
    }

How could I do that?

A:

In addition to JohnnyHK's use of the positional operator, there are a few more ways to approach this in MongoDB 2.2+:
Approach #1: use an $elemMatch projection
The $elemMatch projection can be used to include a single matching element of an array.  By default the result also includes the document _id, but you can exclude this if not needed:
db.comments.find(
    { rid: 456 },
    { _id:0, refs: { $elemMatch: { no: 2 } }}
)

Example output:
{ "refs" : [ { "no" : 2, "info" : "this is second" } ] }

Approach #2: use the Aggregation Framework
The Aggregation Framework includes operators to $unwind arrays and $match document criteria.  This approach has more flexibility than using an $elemMatch projection, because multiple matches per array can now be returned.
db.comments.aggregate(

    // Find matching documents of interest (can use an index)
    { $match: { rid: 456 }},

    // Create stream of documents based on the `refs` array
    { $unwind: "$refs" },

    // Match the specific refs element(s) of interest
    { $match: { "refs.no" : 2 }},

    // Project the desired output
    { $project: {
        _id: 0,
        no: "$refs.no",
        info: "$refs.info"
    }}
)

Example output:
{
    "result" : [
        {
            "no" : 2,
            "info" : "this is second"
        }
    ],
    "ok" : 1
}


Q:

Angularjs with jquery auto complete not working

I am trying for the past 5 hours without success...
 Here is the code..
In View:
<input type="text" ng-model="foo" auto-complete/>Foo = {{foo}}

In controller:
    myapp.directive('autoComplete', function(autoCompleteDataService) {
    return {
        restrict: 'A',
        link: function(scope, elem, attr, ctrl) {
            elem.autocomplete({
                source: autoCompleteDataService.getSource(), //from your service
                select: function( event, ui ) {
                    scope.foo= ui.item.label;
                    scope.$apply;
                },
                change:function (event, ui) {
                    if (ui.item === null) {
                        scope.foo = null;
                    }
                },
                minLength: 2
            });
        }
    };
});

    myapp.factory('autoCompleteDataService', [function() {
    return {
        getSource: function() {
            return ['apples', 'oranges', 'bananas'];
        }
    }
}]);

Here is the issue...
The selected item is getting into the input box, but foo variable next to input box is not updating.
Where is the mistake.
Please suggest...

A:

Change
scope.$apply;

to
scope.$apply(function(){
    scope.foo= ui.item.label;
});


Q:

React accessing state in nested components

React newbie here. I'm building a simple voting app and have it all just about working but have one remaining item. In the code below, I'm getting an 'Uncaught TypeError: Cannot read property 'state' of undefined at Votes' error. I'm sure this is because my Votes function is outside the scope of the array items but I don't know how to code this to fix it. Help appreciated.
class Ratings extends React.Component {
    constructor(props){
        super(props);
        this.state = {
            votes: 0
        };
        this.add = this.add.bind(this);
        this.subtract = this.subtract.bind(this);
        this.reset = this.reset.bind(this);
    }
    add(event){
        this.setState ({
            votes: this.state.votes + 1
        })
    }
    subtract(event){
        this.setState ({
            votes: this.state.votes - 1
        })
    }
    reset(event){
        this.setState ({
            votes: 0
        })
    }
    render () {
        this.movies = this.props.list.map(x => {
            return (

                <MoviePoster poster={x.img}/>

{x.name}

                        <button onClick={this.add}></button>
                        <Votes />
                        <button onClick={this.subtract}></button>

                <button onClick={this.reset} className="reset">Reset</button>

            )
        });
        return (

                {this.movies}

        );
    }
}

function MoviePoster(props) {
    return (

    );
}

function Votes(props) {
    return (

Votes: {this.state.votes}

    );
}

var movieposters = [
    {id: 1, img:"http://www.impawards.com/2017/posters/med_alien_covenant_ver4.jpg", name: "Alien Covenant"},
    {id: 2, img:"http://www.impawards.com/2017/posters/med_atomic_blonde_ver4.jpg", name: "Atomic Blonde"},
    {id: 3, img:"http://www.impawards.com/2017/posters/med_easy_living_ver3.jpg", name: "Easy Living"},
    {id: 4, img:"http://www.impawards.com/2017/posters/med_once_upon_a_time_in_venice_ver3.jpg", name: "Once Upon a Time in Venice"},
    {id: 5, img:"http://www.impawards.com/2017/posters/med_scorched_earth.jpg", name: "Scorched Earth"},
    {id: 6, img:"http://www.impawards.com/2017/posters/med_underworld_blood_wars_ver9.jpg", name: "Underworld: Blood Wars"},
    {id: 7, img:"http://www.impawards.com/2017/posters/med_void.jpg", name: "The Void"},
    {id: 8, img:"http://www.impawards.com/2017/posters/med_war_for_the_planet_of_the_apes.jpg", name: "War for the Planet of the Apes"},
]

ReactDOM.render(
    <Ratings list={movieposters} />,
    document.getElementById('app')
);

A:

You have to do just like you are doing in MoviePoster. Pass a prop to Votes like this
<Votes votes={this.state.votes} />

And then in your Votes function use that prop like this
function Votes(props) {
    return (

Votes: {props.votes}

    );
}


Q:

Inserting a foreign key when creating an object with a foreign key field

i cant really understand what is the problem i have this model :
class Upload_files(models.Model): #uploaded files(for approval) are stored here
file=models.FileField(upload_to=""+strftime("%j", gmtime())+"/")
cont = models.ForeignKey(Contractor)
def __unicode__(self):
    return self.file.name

and the form :
class uploadFile(forms.ModelForm):
file = forms.FileField(label=(u'file'))

cont = forms.ModelChoiceField(label="cont",
                             queryset=Contractor.objects.all(),
                             required = False
                             )

and in the method that i create in it the object :
cont = Contractor.objects.get(id=contractor_id)
file = Upload_files.objects.create(file=file,cont=cont)
file.save()

and thats the error that i get :
shoghlanah_upload_files has no column named cont_id

i cant really understand whats wrong with my code so please any ideas ?

A:

You need to either delete your database and recreate it using syncdb, or setup south and run a migration on your current database.


Q:

Prove by a theorem.

I was given a statement and then asked for my opinion whether the statement is True or False with some additional proof.
Surprisingly, I found out that the statement was an actual theorem showing that the statement was indeed true.
My question is: Would it be enough, to say that the statement is "True" simply because the statement was an actual theorem?

A:

It really depends on what the examiner intends to test you. The best thing is to write down a proof of the result to show that it is true. If the proof is very complicated, perhaps he just wants you to know that it indeed has been proven already.


Q:

How to calculate a child UI image's anchoredPosition(?) based on screen position input?

How to calculate a child UI image's anchoredPosition(?) based on screen position input?
I'm trying to have the child UI image (Spotlight) show up where the eyeball UI is, but it seems to always be offset. The eyeball correctly shows up based on the Screen Position.

It is perfect when the Canvas is at 1080x1920 (set to scale)
But when I try it using others screen resolutions such as 1125x2436, the issue above shows up.
None of these attempts work. The gif is based on the one not commented out here:
p=Input.mousePosition; // screenPosition

    public static void SetRTPos(Transform g,Vector2 p,Canvas c)
    {
        RectTransform rt = g.GetComponent<RectTransform>();
        rt.anchorMin = Vector2.zero;rt.anchorMax = Vector2.zero;
        rt.pivot = Vector2.zero;
        // rt.anchoredPosition = RectTransformUtility.PixelAdjustPoint(p,g.parent,c);
        //rt.anchoredPosition = new Vector2(p.x* (float)c.pixelRect.x, p.y*(float)c.pixelRect.y);//  c.scaleFactor;
        rt.anchoredPosition = new Vector2(p.x*1080f/Screen.width,p.y*1920f/Screen.height );
        //rt.localPosition = RectTransformUtility.ScreenPointToLocalPointInRectangle(rt.parent.GetComponent<RectTransform>(),p,Camera.main,out p2)
   }

The UI RectTransform for rt.parent:

The UI RectTransform for g (not the x,y,z are updated at runtime):

A:

You had the right answer, you just used it wrong. ScreenPointToLocalPointInRectangle returns a boolean true/false, indicating whether the point is in the rectangle. To get its position inside that rectangle, you need to read the out parameter.
public static void SetRTPos(/*ask for the type you want*/ RectTransform rt, Vector2 p, Canvas c)
{
    var center = new Vector2(0.5f, 0.5f);
    rt.anchorMin = center;
    rt.anchorMax = center;
    rt.pivot = center;

    RectTransformUtility.ScreenPointToLocalPointInRectangle(
        (RectTransform)rt.parent, // No GetComponent needed, just cast it.
        p,
        Camera.main,              // Use null if canvas is Screenspace Overlay.
        out Vector2 localPoint    // The position is given as an out parameter.
    );

    rt.anchoredPosition = localPoint;
}


Q:

Android password manager that imports LastPass passwords

I'm searching for a free Android password manager that

integrates with Firefox Android version easily
imports my passwords that I have exported from LastPass to a CSV file
(Bonus) allows syncing with Dropbox or Google Drive

I use LastPass on my computers, I want a free alternative on Android since I very rarely use my phone to browse the web and login, so I won't pay for it.

A:

I used keeper password manager, imported the csv using their web portal.
The downside is that no firefox integration, they claim that it works on any browser, I'm going to report the bug on firefox and see how it goes. It works on Chrome and other browsers. And backups are limited for none premium users.
Update
Keeper support gave me 6 months premium membership for reporting Firefox bug, they are working to fix it, I will update my answer when the issue is fixed. I'm thinking to stay with them simply because the support is nice, it's good to know that when you report an issue, someone is listening.


Q:

Is there finest topology which makes given vector space into a topological vector space?

I we are given a vector space $(V,+,\cdot)$ over a field $\mathbb K$ (where $\mathbb K=\mathbb R$ or $\mathbb K=\mathbb C$), is there the finest topology $\mathcal T$, such that $(V,\mathcal T)$ is a topological vector space?

I'll explain below what I have tried. This seems a very natural question to me, so I guess the answer (whether it is affirmative or negative) should be well known, at least to some local experts in topological vector spaces.

First guess would be the discrete topology, but discrete topology does not give a topological vector space. Indeed, if $\cdot \colon \mathbb K\times V\to V$ is continuous then for each fixed $v\in V$ the map $\alpha \mapsto \alpha\cdot v$ from $\mathbb K$ to $V$ should be continuous. Since the map is injective for $v\ne0$, this would imply that $\mathbb K$ has discrete topology too.
Perhaps we could get a topology such that the maps $\alpha \mapsto \alpha\cdot u$, $v \mapsto \beta\cdot v$, $v\mapsto v+u$ are continuous for each $u\in V$ and $\beta\in\mathbb K$ by iteratively taking the initial topology w.r.t. these maps, starting from the discrete topology on $V$ and the usual topology on $\mathbb K$ and iterating this proces. But even if this worked, we would get only separate continuity for $\cdot \colon \mathbb K\times V\to V$, and we want this map to be jointly continuous.

While looking for answer to my question, I found out about the existence of finest locally convex topology (Google Books), which is mentioned, for example
in this question
or this question.
This is different from what I am asking here.

A:

I would say that there is a finest vector space topology. However, my argument may be completely wrong...
Let $(\tau_i)_{i\in I}$ be the family of all vector space topologies on $V$. Call a set $\mathcal E\subset V$ $elementary$ if it can be written as $\mathcal E=\mathcal U_{i_1}\cap \cdots \cap \mathcal U_{i_N}$, where $\mathcal U_{i_k}\in\tau_{i_k}$. Finally, let $\tau$ be the family of all subsets of $V$ which are unions of elementary sets.
Since the family of elementary sets contains $\emptyset$ and $V$ and is stable under finite intersections, it is rather clear that $\tau$ is a topology on $V$. Obviously, $\tau$ is finer than all $\tau_i$; so it remains to check that $\tau$ is a vector space topology.
Take $x,x'\in V$ and let $\mathcal W$ be a $\tau$-neighbourhood of $x+x'$. Choose an elementary set $\mathcal E=\mathcal U_{i_1}\cap \cdots \cap \mathcal U_{i_N}$ such that $x+x'\in \mathcal E\subset\mathcal W$. Since each $\tau_{i_k}$ is a vector space topology, one can choose $\mathcal V_k, \mathcal V'_k\in\tau_k$ such that $x\in\mathcal V_k$, $x'\in\mathcal V'_k$ and $\mathcal V_k+\mathcal V'_k\subset \mathcal U_{i_k}$. Then $\mathcal V=\bigcap_k \mathcal V_k$ and $\mathcal V'=\bigcap_k\mathcal V'_k$ are $\tau$-neighbourhoods of $x$ and $x'$ such that $\mathcal V+\mathcal V'\subset\mathcal E\subset \mathcal W$. This shows that addition is jointly continuous on $(V,\tau)\times (V,\tau)$.
Continuity of scalar multiplication can be checked in the same way.
Please let me know if this seems correct!


Q:

Why did sshd delete my /dev/zero?

When I do lsof +c 0 | grep /dev/zero, I see the following two lines:
sshd    19064    root  DEL    REG    0,4    497862    /dev/zero
sshd    19064    root  DEL    REG    0,4    498725    /dev/zero

The DEL keyword is what intrigues me - from the manpages, it means:

DEL for a Linux map file that has been deleted

However, last time I checked my /dev/zero was still there, even if I reboot... So why would sshd attempt to delete this character device and why would it even succeed given that:

It is a character device, not a file
it is owned by root

OS info: Linux localhost 3.4.103 #1 SMP PREEMPT Thu Dec 18 13:07:12 CST 2014 armv7l GNU/Linux (Arch Linux)

A:

DEL doesn't indicate that that process deleted /dev/zero, but that that process is using /dev/zero and the instance of /dev/zero that was being used has since been deleted. For example, if I have a command (say some-command) that uses /some/file and I do:
$ some-command &
$ rm /some/file
$ touch /some/file

Then lsof for /some/file would look like:
some-command    ...    ...  DEL    ...    ...    ...    /some/file

The contents of the deleted file continue to remain on disk until the process lets go or is killed, but won't be directly accessible.
The version of /some/file that I created using touch is not the one that some-command is using.


Q:

Maven archetype for simple Servlet application

Is there a Maven 2 archetype for a simple Servlet (2.5) web application?

A:

There is an archetype for webapp:
mvn archetype:generate -DgroupId=com.acme \
                       -DartifactId=my-webapp \
                       -Dversion=1.0-SNAPSHOT \
                       -DarchetypeArtifactId=maven-archetype-webapp \
                       -DinteractiveMode=false

This will generate the following structure:

$ tree my-webapp/
my-webapp/
├── pom.xml
└── src
    └── main
        ├── resources
        └── webapp
            ├── index.jsp
            └── WEB-INF
                └── web.xml

Where the web.xml is a Servlet 2.3 web.xml:
$ cat my-webapp/src/main/webapp/WEB-INF/web.xml
<!DOCTYPE web-app PUBLIC
 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 "http://java.sun.com/dtd/web-app_2_3.dtd" >

<web-app>
  <display-name>Archetype Created Web Application</display-name>
</web-app>

For a Servlet 2.5 web application, replace it with something like this:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
  version="2.5">
  <display-name>Archetype Created Web Application</display-name>
</web-app>

I don't know for NetBeans but Eclipse (more precisely M2Eclipse) relies on the web.xml to set the project facets (so you need to change the web.xml before the import, Eclipse won't update the web facet if you change the web.xml after the facts).

A:

I have created simple archetype for creating Servlet 3 based webapps: https://github.com/maciejwalkowiak/servlet3-maven-archetype
Just clone it, install and generate project that uses Servlet 3, no XML, Tomcat7 ready (plugin included)


Q:

Retrieve & update 20000 data records stops working

I am using the following code do get all data records from a MS SQL database and I try to update every single record. The code is used in a WebService. The issue is, that the code runs fine if I have 1000 data records but now I have 20000 data records an the code first returned with an timeout. Then I set the cmd.CommandTimeout to zero to have no timeout. Now when I invoke the function in the IE WebSvc the IE window is still blank and still try to load something but nothing happens. Only 150 datarecords are updated.
Do you have any idea where the issue might be ? Is the code not the best, so what should I change ?
Thank you very much!
WorldSignia
MyCode:
 private string AddNewOrgBez()
        {
            try
            {
                SqlConnection sqlconn = new SqlConnection(this.connectionString);
                SqlCommand cmd;
                SqlDataReader reader;
                sqlconn.Open();

                cmd = new SqlCommand("SELECT * FROM dbo.mydata", sqlconn);
                cmd.CommandTimeout = 0;
                reader = cmd.ExecuteReader();

                while (reader.Read())
                {
                    // Felder holen
                    string okuerzel = reader["O_KURZ"].ToString();
                    string bezeichnung = reader["O_BEZ"].ToString();

                    string[] lines = CreateNewOrgBez(bezeichnung);

                    string sqlcmd = "UPDATE dbo.mydata SET WEB_OBEZ1 = '" + lines[0] + "', WEB_OBEZ2 = '" + lines[1] + "', WEB_OBEZ3 = '" + lines[2] + "' WHERE O_KURZ = '" + okuerzel + "'";

                    SqlConnection sqlconn2 = new SqlConnection(this.connectionString);
                    sqlconn2.Open();
                    SqlCommand cmd2 = new SqlCommand(sqlcmd, sqlconn2);
                    cmd2.CommandTimeout = 0;
                    cmd2.ExecuteNonQuery();
                    sqlconn2.Close();
                }

                reader.Close();
                sqlconn.Close();

                return "OK";
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }

A:

You were using two different connections to read and to update, and one of them was blocking another. This is why when you read all your data first, it began to work.


Q:

How to reject names (people and companies) using whitelists with C# regex's?

I've run into a few problems using a C# regex to implement a whitelist of allowed characters on web inputs. I am trying to avoid SQL injection and XSS attacks. I've read that whitelists of the allowable characters are the way to go.
The inputs are people names and company names.
Some of the problems are:

Company names that have ampersands. Like "Jim & Sons". The ampersand is important, but it is risky.
Unicode characters in names (we have asian customers for example), that enter their names using their character sets. I need to whitelist all these.
Company names can have all kinds of slashes, like "S/A" and "S\A". Are those risky?

I find myself wanting to allow almost every character after seeing all the data that is in the DB already (and being entered by new users).
Any suggestions for a good whitelist that will handle these (and other) issues?
NOTE: It's a legacy system, so I don't have control of all the code. I was hoping to reduce the number of attacks by preventing bad data from getting into the system in the first place.

A:

This SO thread has a lot of good discussion on protecting yourself from injection attacks.
In short:

Filter your input as best as you can
Escape your strings using framework based methods
Parameterize your sql statements

In your case, you can limit the name field to a small character set.  The company field will be more difficult, and you need to consider and balance your users need for freedom of entry with your need for site security.  As others have said, trying to write your own custom sanitation methods is tricky and risky.  Keep it simple and protect yourself through your architecture - don't simply rely on strings being "safe", even after sanitization.
EDIT:
To clarify - if you're trying to develop a whitelist, it's not something that the community can hand out, since it's entirely dependent on the data you want.  But let's look at a example of a regex whitelist, perhaps for names.  Say I've whitelisted A-Z and a-z and space.
Regex reWhiteList = new Regex("^[A-Za-z ]+$")

That checks to see if the entire string is composed of those characters.  Note that a string with a number, a period, a quote, or anything else would NOT match this regex and thus would fail the whitelist.
if (reWhiteList.IsMatch(strInput))
   // it's ok, proceed to step 2
else
   // it's not ok, inform user they've entered invalid characters and try again

Hopefully this helps some more!  With names and company names you'll have a tough-to-impossible time developing a rigorous pattern to check against, but you can do a simple allowable character list, as I showed here.

A:

Do not try to sanitize names, especially with regex!
Just make sure that you are properly escaping the values and saving them safely in your DB, and them escaping them back when presenting in HTML


Q:

Preferred return type, pointer or value, when the method/function can also return an error

In Go we can choose to make something a pointer or not. We can also support multiple return types. A common signature on functions or methods is:
type MyType struct{}

// Value Return Type
func (m MyType) FindOne(key string)(MyType, error) {...}

// Pointer Return Type
func (m MyType) FindOne(key string)(*MyType, error) {...}

In reviewing the repos on Github (non-exhaustive) for signatures like the above, it seems to be preferred to use the pointer style return type when something can also return an error. Is that the general consensus?
Few Examples (again non-exhaustive I have definitely not seen everything there is to see):
https://github.com/etcd-io/etcd/blob/9c5426830b1b8728af14e069acfdc2a64dea768c/clientv3/kv.go#L48-L54
https://github.com/go-redis/redis/blob/d19aba07b47683ef19378c4a4d43959672b7cec8/cluster.go#L329
https://github.com/bradfitz/gomemcache/blob/master/memcache/memcache.go#L317
In thinking about it, and here's where my question lies, I would think the pointer style would be preferred on calls where a result might not exist:
service := MyType{}
result, err := service.FindOne("not-found-key")

In this way result can be nil and only the err has a value. Effectively preventing anyone from operating result. Whereas in the value type return, if nothing is found, we would still need to return an empty MyType{}. Assuming we are good Go citizens, we would naturally error check things always. Nothing is perfect and things slip by, so in the case where someone were to do something like this:
service := MyType{}
result, _ := service.FindOne("not-found-key")

// do stuff with `result` because of course it will ALWAYS succeed
// we don't need to error check (until we do)

The execution will continue even though we are now in a potentially unknown state. Where as is we tried to do things to that pointer return value, since it's nil, it would panic and we'd know about it right away.
This has additional implications as well in the design of our MyType service. To keep things consistent, if we introduced at FindMany method:
type MyType struct{}

func (m MyType) FindOne(key string)(*MyType, error) {...}
func (m MyType) FindMany(key string)([]*MyType, error) {...}

We would probably benefit from keeping the Pointer return types consistent so callers don't have to think too much as it's always the same either a Pointer or Value of MyType.

A:

I don't think it particularly matters which you use, at least not relating to error handling.  The whole point of returning an err along with a result is so that you can test for an error before accessing the return result.  So ultimately it shouldn't matter if your return a valid , because if you are properly checking the error result first, an invalid  would never be referenced.


Q:

Using expect script for gpg - password decryption - does not work

Hi I am fairly new to expect scripting. I am trying to use the gpg for password encryption/decryption.  Encryption has no issues. For Decryption, I am trying to automate it using expect script.
The basic command I am trying to use is: gpg -o  -d <.gpg file with encrypted password>
When I run this command, stand alone, it asks for passphrase, when I enter it, it creates the output file, as expected. The output file has password in it.
When I run this command using an expect script so that the passphrase can be provided automatically at run time, the expect does not create the output file.
Any help is appreciated. It does not show any errors! The output is:
spawn gpg -o /home/gandhipr/passwdfile -d /home/gandhipr/passfile.gpg
gpg: CAST5 encrypted data
Enter passphrase:

Below is my expect script.
#!/usr/bin/expect
set timeout 1
set passdir [lindex $argv 0]
set passfile [lindex $argv 1]
set passfilegpg [lindex $argv 2]
set passphrase [lindex $argv 3]
spawn gpg -o $passdir$passfile -d $passdir$passfilegpg
expect "Enter passphrase:"
send "$passphrase\n"
exp_internal 1
exit 0;
interact

A:

Use \r instead of \n in the send command: \r is the carriage return characters which mimics the user hitting Enter.


Q:

How can i stop unity from script?

I need to close unity from my scripts. As if I clicked on the stop-button in GUI.
Can i do this directly from code, or not? I know, how i can close a scene, but need to close all processes.

A:

Application.Quit(); // Quit the deployed game/App

Or as Chris commented, use below code to quit Unity Editor:
EditorApplication.Exit(0);

Or you wish to pause the player:
EditorApplication.isPaused = true;

Or consider using boolean property:
EditorApplication.isPlaying = false;

Or you are talking about this? Then try:
Debug.Break();  //stop running at run-time,

See online documentation here and here.
Choose whichever that matches your intents.


Q:

How to print and show log using Fabric or Fire base Crashlytics in Android?

I am using fabric Crashlytics in my project, Crash message is working good. But the problem is that I am not able to print log on my fabric dashboard.

Code
Fabric.with(this, new Crashlytics());
Crashlytics.log("value");

List item

I am not able to see any log message in the dashboard please help me from this.Thank you in advance

A:

Logs get attached to crash sessions. If you click into a Crashlytics issue and select "View all sessions", the logs will appear in the section above the stacktrace.


Q:

Shortcut to bring an app to front if the window title is not constant?

For example, applications like Files or Document Viewer in Ubuntu:
If I want to focus a window like Sublime Text, then wmctrl -a "Sublime" is straightforward, but for Files, the title can be "Desktop" or "Documents" or whatever folder I'm in.
Basically, I'm trying to adapt the directions here:
Custom hotkey/shortcut to open/bring to front an app so that they work when there isn't a constant unique string in the title.

A:

You could use xdotool:
xdotool search --all --onlyvisible --class nautilus windowactivate %@

It will saerch for windows in the WM_CLASS "nautilus" and then focuses those windows.
To find out the WM_CLASS of a window use that command:
xprop WM_CLASS

Then click at the desired window. The output would be (in case of nautilus):
WM_CLASS(STRING) = "nautilus", "Nautilus"

The first one is the class the second one the class name. You can use those values with xdotool as above. It doesn't matter what title the window has.