Monday, April 16, 2012

Flip, Grow, and Translate Animation

Look at this video of the MLB At Bat app. Basically, I just want to present a modalViewController with the UIModalPresentationFormSheet style and have it grow from another view then flip. Like when you tap on a game in the scoreboard on the MLB app. Anyone know how I can accomplish this?



Thanks



EDIT: My main view is pretty much the same setup as the MLB app. I'm using AQGridView and want the animation to occur when a cell in the grid view is tapped.



EDIT 2: I'd also be open to ditching the UIViewController concept and just using a plain UIView, then replicate the style of UIModalPresentationFormSheet manually if that's easier.



EDIT 3: Okay, forget using a UIViewController to do this, since I haven't gotten any responses, I'll assume it isn't possible. My new question is just how do I replicate the animation in the posted video using just UIView's? So basically, the initial view needs to grow, move, and flip all at the same time.



EDIT 4: I think I have the actual animation figured out, now my only problem is calculating coordinates to feed into CATransform3DTranslate. My view needs to animate pretty much exactly like in the video. It needs to start over another view and animate to the center of the screen. Here's how I'm trying to calculate the coordinates for the view that pops up in the center:



CGPoint detailInitialPoint = [gridView convertPoint:view.frame.origin toView:detailView.frame.origin];
CGPoint detailFinalPoint = detailView.frame.origin;


gridView is the container view of my main view that holds the smaller grid items. view is the specific grid item that we are animating from. And detailView is the view that comes up in the middle of the screen.





Draw clickable rectangles and I do not know how set params before onDraw method

I am trying to make clickable rectangles. I've looked around and I created quite good code :)



I create constructor of my own rectangle class, then i set some values of it.
However, onDraw method looks like creates and draw rectangle but without constructor's new variables' values.
What do I do wrong?



This is default MyActivity class:



ll = (LinearLayout)findViewById(R.id.linearlayout);
List<MiniRectangle> miniRectangleList = new ArrayList<MiniRectangle>();

for(int i=0;i<8;i++)
{
int numberRandom = r.nextInt(3);

MiniRectangle miniRectangle = new MiniRectangle(this);
miniRectangle.set_color(colors.get(numberRandom));
miniRectangle.set_size(50);
miniRectangle.set_id_color(numberRandom);
miniRectangle.set_number(i);

ll.addView(miniRectangle);

miniRectangleList.add(miniRectangle);
}

setContentView(ll);


This is my own rectangle class



public class MiniRectangle extends View implements View.OnClickListener {

Context context;
int _size;
int _color;
int _id_color;
int _number;

public MiniRectangle(Context context) {
super(context);
this.context = context;
setOnClickListener(this);
}

@Override
public void onClick(View view) {
System.out.println(get_number());
Toast.makeText(context, get_number(), Toast.LENGTH_SHORT).show();
}

@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);

Paint paint = new Paint();
paint.setColor(get_color());
paint.setStrokeWidth(1);

int kleft = (get_number() % 8) * get_size();
int kright = kleft + get_size() - 2;

int ktop = 1 * get_size();
int kbottom = ktop + get_size() - 2;

canvas.drawRect(kleft, ktop, kright, kbottom, paint);
}
}


I can say that after run project I get only one rectangle. No wonder if every rectangle has the same position. Please Help.





Accessing self from outside of a class

I'm attempting to implement a decorator on certain methods in a class so that if the value has NOT been calculated yet, the method will calculate the value, otherwise it will just return the precomputed value, which is stored in an instance defaultdict. I can't seem to figure out how to access the instance defaultdict from inside of a decorator declared outside of the class. Any ideas on how to implement this?



Here are the imports (for a working example):



from collections import defaultdict
from math import sqrt


Here is my decorator:



class CalcOrPass:
def __init__(self, func):
self.f = func

#if the value is already in the instance dict from SimpleData,
#don't recalculate the values, instead return the value from the dict
def __call__(self, *args, **kwargs):

# can't figure out how to access/pass dict_from_SimpleData to here :(
res = dict_from_SimpleData[self.f.__name__]
if not res:
res = self.f(*args, **kwargs)
dict_from_SimpleData[self.f__name__] = res
return res


And here's the SimpleData class with decorated methods:



class SimpleData:
def __init__(self, data):
self.data = data
self.stats = defaultdict() #here's the dict I'm trying to access

@CalcOrPass
def mean(self):
return sum(self.data)/float(len(self.data))

@CalcOrPass
def se(self):
return [i - self.mean() for i in self.data]

@CalcOrPass
def variance(self):
return sum(i**2 for i in self.se()) / float(len(self.data) - 1)

@CalcOrPass
def stdev(self):
return sqrt(self.variance())


So far, I've tried declaring the decorator inside of SimpleData, trying to pass multiple arguments with the decorator(apparently you can't do this), and spinning around in my swivel chair while trying to toss paper airplanes into my scorpion tank. Any help would be appreciated!





In a hash, how do you add two values for the same key instead of overwriting?

Basically I have these files (medline from NCBI). Each is associated with a journal title. Each has 0, 1 or more genbank identification numbers (GBIDs). I can associate the number of GBIDs per file with each journal name. My problem is that I may have more than one file associated with the same journal, and I don't know how to add the number of GBIDs per file into a total number of GBIDs per journal.



My current code:
jt stands for journal title, pulled out properly from the file. GBIDs are added to the count as encountered.



... up to this point, the first search is performed, each "pmid" you can think of
as a single file, so each "fetch" goes through all the files one at a time...



  pmid_list.each do |pmid|

ncbi_fetch.pubmed(pmid, "medline").each do |pmid_line|

if pmid_line =~ /JT.+- (.+)\n/
jt = $1
jt_count = 0
jt_hash[jt] = jt_count

ncbi_fetch.pubmed(pmid, "medline").each do |pmid_line_2|

if pmid_line_2 =~ /SI.+- GENBANK\/(.+)\n/
gbid = $1
jt_count += 1
gbid_hash["#{gbid}\n"] = nil
end
end

if jt_count > 0
puts "#{jt} = #{jt_count}"

end
end
end
end


My result:



 Your search returned 192 results.
Virology journal = 8
Archives of virology = 9
Virus research = 1
Archives of virology = 6
Virology = 1


Basically, how do I get it to say Archives of virology = 15, but for any journal title? I tried a hash, but the second archives of virology just overwrote the first... is there a way to make two keys add their values in a hash?



Full code:



 #!/usr/local/bin/ruby

require 'rubygems'
require 'bio'


Bio::NCBI.default_email = 'kepresto@uvm.edu'

ncbi_search = Bio::NCBI::REST::ESearch.new
ncbi_fetch = Bio::NCBI::REST::EFetch.new


print "\nQuery?\s"

query_phrase = gets.chomp

"\nYou said \"#{query_phrase}\". Searching, please wait..."

pmid_list = ncbi_search.search("pubmed", "#{query_phrase}", 0)

puts "\nYour search returned #{pmid_list.count} results."

if pmid_list.count > 200
puts "\nToo big."
exit
end

gbid_hash = Hash.new
jt_hash = Hash.new(0)


pmid_list.each do |pmid|

ncbi_fetch.pubmed(pmid, "medline").each do |pmid_line|

if pmid_line =~ /JT.+- (.+)\n/
jt = $1
jt_count = 0
jt_hash[jt] = jt_count

ncbi_fetch.pubmed(pmid, "medline").each do |pmid_line_2|

if pmid_line_2 =~ /SI.+- GENBANK\/(.+)\n/
gbid = $1
jt_count += 1
gbid_hash["#{gbid}\n"] = nil
end
end

if jt_count > 0
puts "#{jt} = #{jt_count}"

end
jt_hash[jt] += jt_count
end
end
end


jt_hash.each do |key,value|
# if value > 0
puts "Journal: #{key} has #{value} entries associtated with it. "
# end
end

# gbid_file = File.open("temp_*.txt","r").each do |gbid_count|
# puts gbid_count
# end




Return "True" on Empty jQuery Selector Array?

I'm working on creating a more semantic way of checking for elements with jQuery. Using $("#element").length > 0 just doesn't really feel very well worded to me, so I'm making my own selector addition for use in .is:



if($("#element").is(":present")) {
console.log("It's aliiiveeee!!");
}


That part was easy, like this:



$.extend($.expr[':'],{
present: function(a) {
return $(a).length > 0;
}
});


I want to go a step further, and make it easy to see if an element doesn't exist, using similar syntax:



$.extend($.expr[':'],{
present: function(a) {
return $(a).length > 0;
},
absent: function(a) {
return $(a).length === 0;
}
});

$(function() {
if($("#element").is(":absent")) {
console.log("He's dead, Jim.");
}
});


But this part is surprisingly hard to do. I think it's because I'm paring down the returned elements to get a result, and paring the selector to .length === 0 is the same as asking for no elelements: it returns false no matter what.



I've tried a lot of different ways to reverse things and get this to return true when the element doesn't exist, and false if it does:



return $(a).length === 0;

return !($(a).length > 0);

if(!($(a).length > 0)) {
return true;
}

if($(a).length > 0) {
return false;
} else {
return true;
}

return !!($(a).length === 0);

// etc...


Is there an easy way to get this to just return true if the element doesn't exist, and false if it does?





How can I get LINQ to accept my argument?

I want to make "Create" option in ASP.NET MVC 3 in C#.
I am working with entity framework.



I want to make a method in one of my models that could insert all the data I posted into my action.



my model looks like this :



public class person { 
public int id { get; set; }
public string name{ get; set; }
public string carBrand { get; set; }
public string streetname{ get; set; }
}


My view is strongly typed with this class above, making a "Create" page. So it creates the textboxes automatically for me.



The object Person, I gave my Controller has a parameter.



public ActionResult Index(person objectPerson)
{
//invoke method here
}


Then I wanted my method, which came from the model, to take this object and add its properties to my database... but the problem is, it doesn't work the way I thought it would.



public void createPerson(person objectPerson)
{
db.MyTable.AddObject(objectPerson)
}


giving the following error : the best overloaded method match has some invalid arguments





Is there a tool where you give a list of things and it returns related words?

Is there some kind of tool you can enter simple queries and it will use AI to process it and provide you an answer relating your query to it's possible meanings? For example:



relate: animal, fast, not bird -> cheetahs, lions, etc
relate: python, else if -> elif, condition blocks, programming
relate: avogadro, constant -> 6.02E23, chemistry, atom, etc
relate: current time, Javascript -> Date.now(), (new Date()).getTime(), etc
relate: [1,5,4,6,2], [1,2,4,5,6] -> sorting algorithm, bubblesort, quicksort
relate: [2,3,6,7], [5,10,37,43] -> x²+1 function
relate: cup, glass, break, sound -> ressonance frequency, waves
relate: wii, controller, movements, electronic component -> accelerometer
relate: cell, division -> mitosis, meiosis, dna, histology, etc
relate: pokemon, red, not game, not version -> charmander, charizard, moltres, etc


Possibly showing relation rates in %, using similar methods to those used on Watson?





Getting JSON Object Result from $.post()

I'm attempting to call a web service via AJAX in a WebForms application.



My script looks something like this:



$.post('UpdateServer.asmx/ProcessItem',
'itemId=' + $(this).text(),
function (result) {
alert(result);
});


My web service looks something like this.



[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
[System.Web.Script.Services.ScriptService]
public class UpdateServer : System.Web.Services.WebService
{
[WebMethod]
public string ProcessItem(int itemId)
{
return new JavaScriptSerializer().Serialize(
new { Success = true, Message = "Here I am!" });
}
}


The web method is called as expected and with the expected argument. However, the argument passed to my success function (last parameter to $.post()) is of type document and does not contain the Success and Message members that I'm expecting.



What's are the magic words so that I can get back the object I'm expecting?



EDIT



On closer inspection, I can find the data I'm looking for as follows:




result.childNodes[0].childNodes[0].data:
"{"Success":true,"Message":"Server successfully updated!"}"






C/C++ strcpy unhandled read violation

unsigned char* Data::getAddress(unsigned char* address)
{
strcpy((char*)address, (char*)this->_address);
return (unsigned char*)address;
}

int main()
{
Data d;
d.makealinkedlisthere();
while (d)
{
unsigned char address[256];
printf("0x%08x \r\n",d.getAddress(address));
d = d.getNext();
}
return 0;
}


It returns the first two (which is the same, and it should be different [can tell from the debugger]...) then crashes out.



It just makes a linked list. protected member Data* _next ... a chain of them.



The unsigned char* is from Windows function VirtualQueryEx part of the MEMORY_BASIC_INFORMATION data structure it returns.



this->_address = (unsigned char*)meminfo->BaseAddress; // casted from void*


It is void*, but I see it converted to unsigned char* in other's codes. In the debugger I can see it represented as a hex number.



D1: +    _address   0x7ffd5000 <Bad Ptr>    unsigned char * 
D1->_next:+ _address 0x7f6f0000 "áå•Ãº`©" unsigned char *
D1->_next->_next+ _address 0x7ffb0000 " " unsigned char *




Android. How to Do Audio Recording with High Volume?

I will describe briefly my trouble with audio recording.



So, I am doing audio recording using MediaRecorder, but unfortunately when I playback the recorded audio, I have media with a very low volume. I hardly hear anything.



Is there any possibility to setup recording volume?



Thanks.





Haskell (:) and (++) differences

I m sorry for a question like this. But i m not too sure about the difference of : and ++ operator in haskell.



x:y:[] = [x,y]


also



[x] ++ [y] = [x,y]


as for the reverse function which arose this question for me,



reverse ::[a]->[a]
reverse [] = []
reverse (x:xs) = reverse(xs)++[x]


why doenst the following work?



reversex ::[Int]->[Int]
reversex [] = []
reversex (x:xs) = reversex(xs):x:[]


giving a type error.





Loop in two lists

I have these lists:



list1 = [3, 5, 2, 1, 9]
list2 = [6, 9, 1, 2, 4]
list3 = []
list4 = []


and I want to pass these formula:



x = a/b
y = 1/b


in which a is every value in list1 and b is every value in list2 and append the result of calculations into two empty lists - list3 and list4.



This is what I have but it's a disaster haha :(



u = 0
while u<len(list1):
for a in list1:
for b in list2:
x = a/b
y = 1/b
u+=1
list3.append(x,)
list4.append(y,)


Anyone can help me with this?





is this the right way to do login logic in meteor to display a simple "invalid login" message?

I started this example project to learn meteor:



https://github.com/andrewarrow/question-raven/



I'm trying to duplicated a popular question/answer site functionality just to learn meteor.



Above my login form I have this in the template:



 {{#if invalid }}
<div style="background-color: yellow; padding: 3px 3px 3px 3px;">
login invalid, please try again.
</div>
{{/if}}


and I'm starting the login logic like this:



Template.hello.events = {
'click #login' : function () {
var email = $('#email').val();
var password = $('#password').val();
if (false) {
Session.set('user_id', 1);
} else {
Session.set('invalid', 1);
}
}
};


Then in order for the invalid variable to work in the template I have this function:



Template.hello.invalid = function () {
return Session.get('invalid') != null;
};


Is this the right way to do this? Does every variable the template references have to be a function? Should I use the Session store to record a login was invalid so a function can return true/false?





What is the best way to create an array of all images found in a string?

I am looking to create an array of all the images in a string of HTML.



I've tried using the following but it generates errors if the complete URL path is not present in the src.



var found = $(html).find('img');




MYSQL Query suddenly no longer works

I have the following MySQL that fecthes data from several tables:



SELECT * FROM $wpdb->posts
LEFT JOIN userContests ON ($wpdb->posts.ID = taxi.taxiID)
LEFT JOIN $wpdb->term_relationships ON ($wpdb->posts.ID = $wpdb->term_relationships.object_id)
LEFT JOIN $wpdb->term_taxonomy ON ($wpdb->term_relationships.term_taxonomy_id = $wpdb->term_taxonomy.term_taxonomy_id)
WHERE $wpdb->posts.post_status = 'publish'
AND $wpdb->posts.post_type = 'post'
AND $wpdb->posts.post_date < NOW()+INTERVAL 1 DAY
AND $wpdb->term_taxonomy.taxonomy = 'category'
AND $wpdb->term_taxonomy.term_id IN(3)
AND ($wpdb->postmeta.meta_key = 'EndDate' AND $wpdb->postmeta.meta_value > DATE_ADD(NOW(), INTERVAL 3 HOUR))


As of yesterday, the query is NOT returning any results but here's the kicker: PHP MyAdmin does still return the proper results!



After a lot of trial and error, I've narrowed the problem down to this one line:



AND ($wpdb->postmeta.meta_key = 'EndDate' AND $wpdb->postmeta.meta_value > DATE_ADD(NOW(), INTERVAL 3 HOUR))


The line does function on my server but when it comes to running on the site itself, no results get displayed. Something is suddenly not working, does anyone have any ideas why? Again, the query has been working for two weeks but suddenly as of yesterday, it won't return results on the site, but does return results on my server!





Building a scatterplot class

Here is the way that I think a scatter plot should be built in C# (at a decently high level of abstraction).




  1. Create a blank image

  2. Use TextRenderer to draw the axis labels and scales (horizontal will not be so trivial, but will still be manageable).

  3. Draw some lines that will be the ticks on the axes and the lines for the axes themselves

  4. Draw some circles (not 100% of how to do that, but it can't be too hard) based on the points listed in some data-set.

  5. Display the image in a pictureBox.

  6. Create a function that will be called on MouseHover that will display some details about that point in a tool-tip.



Does this even make sense? Am I using the wrong controls for the job? Is there some code in .NET that will do a large part of this already (the chart class seems good only for bar graphs)? Is there a way to access excel's plotting capabilities from C#?



To me, all of this seems quite contrived, and I would appreciate input on how to better design a scatter-plot class.





Youtube upload - how to limit upload speed

How can I limit speed upload video on youtube because when i start upload my internet extremely slow down



YouTubeRequestSettings settings = new YouTubeRequestSettings("example app", developerKey, Login, Passw);

YouTubeRequest request = new YouTubeRequest(settings);

Video newVideo = new Video();

newVideo.Title = Title;
newVideo.Keywords = Tags;
newVideo.Description = Description;
newVideo.YouTubeEntry.MediaSource = new MediaFileSource(@PathVideo, "video/quicktime");
newVideo.Tags.Add(new MediaCategory("Howto", YouTubeNameTable.CategorySchema));
newVideo.YouTubeEntry.Private = false;

request.Upload(newVideo);




Reading data from a file into an array of class objects

I'm reading data from a file that I need to be put into my array of objects (myEmployees). I believe my code is correct until the end of this example, but I am not sure how to read the data from the file, split it, and then put it correctly into my array of class objects.



//declare an array of employees
Employee[] myEmployees = new Employee[10];

//declare other variables
string inputLine;
string EmpName;
int EmpNum;
double EmpWage;
double EmpHours;
string EmpAdd;

//declare filepath
string environment = System.Environment.GetFolderPath
(System.Environment.SpecialFolder.Personal) + "\\";

//get input
Console.Write("\nEnter a file name in My Documents: ");
string input = Console.ReadLine();
string path = environment + input;
Console.WriteLine("Opening the file...");

//read file
StreamReader myFile = new StreamReader(path);
inputLine = (myFile.ReadLine());


So I am reading data from a file that is structured like:



Employee Number
Employee Name
Employee Address
Employee wage Employee Hours


I need to read data from this file and parse it into the array of Employees that I've created. Here is the class data for class Employee:



public void Employeeconst ()
{
employeeNum = 0;
name = "";
address = "";
wage = 0.0;
hours = 0.0;
}
public void SetEmployeeNum(int a)
{
employeeNum = a;
}
public void SetName(string a)
{
name = a;
}
public void SetAddress(string a)
{
address = a;
}
public void SetWage(double a)
{
wage = a;
}
public void SetHours(double a)
{
hours = a;
}
public int GetEmployeeNum()
{
return employeeNum;
}
public string GetName()
{
return name;
}
public string GetAddress()
{
return address;
}
public double GetWage()
{
return wage;
}
public double GetHours()
{
return hours;
}




Tried to Drop Database from phpMyAdmin but failed. Now I can't do anything with it

I wrote a java application that interacts with my database and there was a problem with it. I had to delete the database since there were too many erroneous changes made by my application. I was careful and backed up my database before I ran the program, so I proceeded to drop the entire database with the intention of reverting back to the original.



I used phpMyAdmin to drop the database in question, but after 20 minutes it seemed like nothing was happening so I forced the browser to close and reloaded PMA. Expectedly, the database I wanted to delete still shows up in the list of databases in PMA, but when I try to access it, the browser goes blank and hangs. I tried to access the database from the terminal (I'm using OS X 10.4.11), and when I type 'use name_of_database', the terminal itself hangs too. I also tried to drop the database once again in the terminal, but that also hangs.



How can I get rid of this database now? I could always reload my database under a different name, but this one will still be here and I really want to get rid of it. Any ideas?





Weird behavior : sending image from Android phone to Java server (code working)

I'm writing an android app that sends an image to a server running a java app, and it's working in a very weird way!



Here is what I do




  1. Compile and run the Java app on the desktop with the receive part that acts as server

  2. Compile,deploy and run the android part that has to send the image to the server. The android app finishes execution but the java app doesn't

  3. Run the android app activity that has the code to send the image AGAIN, and this time, the android app progress dialog gets stuck, BUT, the java app finishes execution and also the image is transferred d successfully...



Following is the code for the RECEIVE part of the Java app:



import java.net.ServerSocket;
import java.net.Socket;
import java.io.*;

class ProjectServer
{
ServerSocket serSock;
Socket sock;

BufferedReader in;
PrintWriter out;
public static void main(String ar[])
{
try
{
ProjectServer cs=new ProjectServer();
cs.startServer();
}
catch(Exception e)
{

}
}

public void startServer()
{
try
{
serSock=new ServerSocket(8070);
System.out.println("Waiting for client...");
sock=serSock.accept();

System.out.println("Connections done");

//Accept File
System.out.println("Connected");

//receive code
int filesize=450660;
int bytesRead;
int current=0;
// receive file
byte [] mybytearray = new byte [filesize];
InputStream is = sock.getInputStream();
FileOutputStream fos = new FileOutputStream("C:\\Project Server\\Capture.png");
BufferedOutputStream bos = new BufferedOutputStream(fos);
bytesRead = is.read(mybytearray,0,mybytearray.length);
current = bytesRead;

do {
bytesRead =
is.read(mybytearray, current, (mybytearray.length-current));
if(bytesRead >= 0) current += bytesRead;
} while(bytesRead > -1);

bos.write(mybytearray, 0 , current);
bos.flush();

System.out.println("end-start");
}
catch(Exception e)
{
System.out.println(e);
e.printStackTrace();
}

}
}


Following is the code for the SEND part on the Android app:



package com.site.custom;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;

import android.app.Activity;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;


public class Act2 extends Activity
{
private ProgressDialog pd;
private String serverIP="58.146.100.187";
private BufferedReader in;
private PrintWriter out;
private String path;
private Socket cliSock;

public void onCreate(Bundle onCreateInstance)
{
super.onCreate(onCreateInstance);
setContentView(R.layout.act2);
this.setTitle("This has started");
path=getIntent().getStringExtra("path");

//Establish Connection
try
{
cliSock=new Socket(serverIP,8070);
in=new BufferedReader(new InputStreamReader(cliSock.getInputStream()));

((TextView)findViewById(R.id.tview)).setText(path);
}
catch(Exception e)
{
Log.v("MERA MSG",e.toString());
}

//Send file
ProgressDialog pd=ProgressDialog.show(this, "Sending image", "Image chosen:"+path.substring(path.lastIndexOf("//")+1),false,true);

try
{
File myFile = new File (path);
System.out.println((int)myFile.length());
byte[] mybytearray = new byte[450560];
FileInputStream fis = new FileInputStream(myFile);
BufferedInputStream bis = new BufferedInputStream(fis);
bis.read(mybytearray,0,mybytearray.length);
OutputStream os = cliSock.getOutputStream();
System.out.println("Sending...");
os.write(mybytearray,0,mybytearray.length);
os.flush();
System.out.println("Completed");

pd.dismiss();
System.out.println("Done");
}
catch(Exception e)
{
Log.v("MERA MSG",e.toString());
}

}
}




Is it a mistake (or trade-off) that size_t is unsigned?

Bjarne Stroustrup wrote in The C++ Programming Language:




The unsigned integer types are ideal for uses that treat storage as a
bit array. Using an unsigned instead of an int to gain one more bit to
represent positive integers is almost never a good idea. Attempts to
ensure that some values are positive by declaring variables unsigned
will typically be defeated by the implicit conversion rules.




size_t seems to be unsigned "to gain one more bit to represent positive integers". So was this a mistake (or trade-off), and if so, should we minimize use of it in our own code?



Another relevant article by Scott Meyers is here. To summarize, he recommends not using unsigned in interfaces, regardless of whether the value is always positive or not.





Update UI from an AsyncTaskLoader

I've converted my AsyncTask to an AsyncTaskLoader (mostly to deal with configuration changes). I have a TextView I am using as a progress status and was using onProgressUpdate in the AsyncTask to update it. It doesn't look like AsyncTaskLoader has an equivalent, so during loadInBackground (in the AsyncTaskLoader) I'm using this:



getActivity().runOnUiThread(new Runnable() {
public void run() {
((TextView)getActivity().findViewById(R.id.status)).setText("Updating...");
}
});


I am using this in a Fragment, which is why I'm using getActivity(). This work pretty well, except when a configuration change happens, like changing the screen orientation. My AsyncTaskLoader keeps running (which is why I'm using an AsyncTaskLoader), but the runOnUiThread seems to get skipped.



Not sure why it's being skipped or if this is the best way to update the UI from an AsyncTaskLoader.





sql incorporating c++

i'm writing sql and c++ code that adds a technician into the database. there's 3 sql insert statements that has to be performed. i have that include in my code, but my code doesn't conform or do what is asked. here is what is asked.



the program should prompt the user for an ssn.



if that ssn/employee is already in the Employee table, the program should inform the user that the employee is already in the DB and ask the user if he wants to update the union-membership-number of that employee; if the user's answer is yes, the program should ask the user for the new union-member-number and update it in the DB.



if the ssn/employee is not already in the DB, the program should ask the user for the union-membership-number of that employee and then store that record in the Employee table. Assuming the employee is a technician the program should ask the user for the information to be stored about that technician (name, address and phone number) and store it in the Technician table; then the program should ask the user for the airplane model-number that the technician is an expert on and add the corresponding record into the Experts table.



here is my code:



void add_technician() {
EXEC SQL BEGIN DECLARE SECTION;
char sn[9];
int s=0;
char answer;
int umn;
char tname[30];
char tadd[30];
char tpho[10];
char tmod[15];
EXEC SQL END DECLARE SECTION;

cout << "Enter social security number:";
cin >> sn;

EXEC SQL SELECT SSN into :s from Employee where SSN= :sn;

if (s == sn)
{
cout << "Employee already exists in the database.";
cout <<"Would you like to update the union-membership-number?";
cin >> answer;
if (answer == 'y'|| 'Y')
{cout <<"Enter new union member number:";
cin >> umn;
EXEC SQL
INSERT INTO Employee (ssn, union_member_no)
VALUES (:sn, :umn);
}
}
else {
cout << "Enter in union membership number of the new employee: ";
cin >> umn;
EXEC SQL INSERT INTO Employees (ssn, union_member_no)
VALUES (:sn, :umn);
EXEC SQL COMMIT WORK;
cout << "Enter the address of the technician.";
cin >> tadd;
cout << "Enter the name technician name.";
cin >> tname;

EXEC SQL INSERT INTO Technicians (address, name, phone)
VALUES (:tadd, :tname, :tpho);
EXEC SQL COMMIT WORK;
cout << "Enter airplane model number that you are an expert on." ;
cin >> tmod;
EXEC SQL INSERT INTO Experts (model_no, ssn)
VALUES (:tmod);
EXEC SQL COMMIT WORK; }

}


when i run the program, it skips my first two IF statements. i can't seem to understand why.





Open web browser from terminal

I know OS X has an open command, where you can pass in a URL, and it'll open up the default browser and point it to the given domain.



But how would I go about doing this for other unix-based AND windows-based machines? Basically, I'd like to make a CLI (written in python), and have a cross-OS way of opening the browser from the terminal.





invalidate() for call onDraw() dose not work in ViewFlipper

In my android app project,I designed a custom component(extends ImageView).At first It works well,I use invalidate() to call my Ondraw(canvas) method.
But then I decide to refact my code to bring the ImageView extendsed custom component in a ViewFlipper,it dose not show.
From debugging I see that my onDraw(canvas) method dose not excuted at all,even if I used invalidate() in my onlayout().
?I tried postInvalidate() method ,but it not work too?



Any suggestion would be appreciated.



I tried to change my custom component to extends View(originaly extend ImageView),it worked.But I don't know WHY?





How do you use Git? I would like to push a file back into the Github repo?

I am currently collaborating with a few others on a large Java project, and have cloned the repository to work on it from my home PC. I went ahead and changed 2 files within the whole directory/subdirectory structure of this gigantic project, and would like to just push those two files I've edited back into the repository.



Is there a command I can use in order to accomplish this? Thanks.





jQuery - Ruby Rails - fadeTo fades all div

I am trying jQuery fadeTo to fade background color of a div (error class), while keeping a inner div unchanged. But in Chrome and firefox both the "error" div and any text inside an inner div both get faded. In IE it works, just the error div gets faded but not any div inside it. How do I make work for all browsers?



View -



<div class="error" style="display: inline-block;z-index:1;">
<div style="position:relative;z-index:2;">Error: <%= @a[:error] %>
</div>
</div>


html -



<div class="error" style="z-index:1;height=300px;width=500px;">
<div style="position:relative; z-index:2;">Error: some error</div>
</div>


javascript -



$(document).ready(function(){
$(".error").fadeTo("slow",0.20);
});




Windows Registry, how to add your Native-Program for boot-exectuing?

I have done my Native program for Windows.



( which, I've compiled with #pragma comment(linker, "/SUBSYSTEM:NATIVE")).



I want to add my program to auto-executing list, how can I do it?



My exact questions are:



1). How can I do it in Windows Registry ( I have googled about BootExecute/SetupExecute table, but Setup is empty and BootExecute has only: autocheck autochk * ). So I was confused of empty tables ( cause , if it's empty, where are another auto-exec programs in Windows, which ntdll.dll does load ? )



2). Does it matter what is the version of the executable program: for 32/64 bits system?



I have put it in %windir%\system32, but there is also %windir%\WOW64 folder.



Should I highlight this detail in Registry or Windows loads each driver from both folders and just simply highliht them as *32 or 64 bits program in taskmgr?



3). Are there any other ways to do that?



Thanks,



Best Regards!





How to use inequalities in "iif" within a query in access

I have a combo box on one of my forms which returns a number, I am using this number in as criteria for a field in a query, however if no option in the combo box has been selected I want to use a default set of criteria, but access keeps telling me I have invalid syntax. Could someone tell me how I could do this?



IIf(IsNull([Forms]![frm_a]![cmbo_b]),<2 or >3,[Forms]![frm_a]![cmbo_b])



The problem occurs when I use <2 or >3 in the middle of the if statement.





print out all the list elements java

how to print out the elements of a list in java?
It is prining the object itselfe instead of the values
here what I did:
here what I have



 for(int i=0;i<list.size();i++){
System.out.println(list.get(i));
}