Search is based on starting characters, but i would like that will search everything. Here is part of my code, method onTextChanged isn't right, I think.. Thanks for help!
@Overridepublic void onCreate(Bundle savedInstanceState) { final ArrayListالثلاثاء، 31 ديسمبر 2013
Android: Searchview searches only whole words
Jquery datepicker format date not working
Thats the default, meaning it does not recognise your option.
try:
dateFormat: 'dd-mm-yy'(small letters)
السبت، 28 ديسمبر 2013
How can I use CSS transitions to animate a responsive layout's vertical orientation?
I am trying to figure out a way to smoothly animate a responsive change to some elements' display property when the browser size reaches a certain breakpoint. I would like to use CSS transitions, but they do not apply to the display property so I may have to figure out a workaround. To be clear, I am only having trouble animating changes to the vertical orientation of elements that were previously arranged horizontally. Other, simple, responsive animations have been set up without issue.
Here is a simple example
In that example, I have set up effective transitions for the div dimensions that activate at given breakpoints. The final (smallest window) transition causes the divs to line up vertically. At first, this was achieved by simply changing the divs from display:inline-block; to display:block;. However, this could not be animated using CSS transitions, so I tried an alternative method. The alternative involved changing the divs from position:relative; to position:absolute; and adjusting their top properties. I thought CSS transitions would be able to effectively animate the change in top but that does not seem to happen.
Does anyone have any suggestions?
الجمعة، 27 ديسمبر 2013
AVAssetWriterInputPixelBufferAdaptor appendPixelBuffer:buffer withPresentationTime returning error NSURLErrorCannotCreateFile
I am creating a video file from an array of images. I am able to create video file on simulator, however when I try to run the same code on device it gives following error:
NSURLErrorDomain Code=-3000 "Cannot create file" UserInfo=0x200be260 {NSUnderlyingError=0x200bb030 "The operation couldn’t be completed. (OSStatus error -12149.)", NSLocalizedDescription=Cannot create file}
I have searched a lot but couldn't find anything.
Here is the code for creating path.
NSString *path = [NSHomeDirectory() stringByAppendingPathComponent:[NSString stringWithFormat:@"Documents/movie.mp4"]];-(void)exportImages:(NSArray *)imageArray asVideoToPath:(NSString *)path withFrameSize:(CGSize)imageSize framesPerSecond:(NSUInteger)fps {NSLog(@"Start building video from defined frames.");NSError *error = nil;NSURL *url = [NSURL fileURLWithPath:path];AVAssetWriter *videoWriter = [[AVAssetWriter alloc] initWithURL: url fileType:AVFileTypeMPEG4 error:&error];NSParameterAssert(videoWriter);NSDictionary *videoSettings = [NSDictionary dictionaryWithObjectsAndKeys: AVVideoCodecH264, AVVideoCodecKey, [NSNumber numberWithInt:imageSize.width], AVVideoWidthKey, [NSNumber numberWithInt:imageSize.height], AVVideoHeightKey, nil];AVAssetWriterInput* videoWriterInput = [AVAssetWriterInput assetWriterInputWithMediaType:AVMediaTypeVideo outputSettings:videoSettings];AVAssetWriterInputPixelBufferAdaptor *adaptor = [AVAssetWriterInputPixelBufferAdaptor assetWriterInputPixelBufferAdaptorWithAssetWriterInput:videoWriterInput sourcePixelBufferAttributes:nil];NSParameterAssert(videoWriterInput);NSParameterAssert([videoWriter canAddInput:videoWriterInput]);videoWriterInput.expectsMediaDataInRealTime = YES;[videoWriter addInput:videoWriterInput];//Start a session:[videoWriter startWriting];[videoWriter startSessionAtSourceTime:kCMTimeZero];CVPixelBufferRef buffer = NULL;//convert uiimage to CGImage.int frameCount = 0;for(UIImage * img in imageArray) { buffer = [self pixelBufferFromCGImage:[img CGImage] andSize:imageSize]; while (1) { if (adaptor.assetWriterInput.readyForMoreMediaData) { break; } } BOOL append_ok = NO; int j = 0; while (!append_ok && j < 30) { NSString *border = @"**************************************************"; NSLog(@"\n%@\nProcessing video frame (%d,%d).\n%@",border,frameCount,[imageArray count],border); CMTime frameTime = CMTimeMake(frameCount,(int32_t) fps); append_ok = [adaptor appendPixelBuffer:buffer withPresentationTime:frameTime]; if(!append_ok){ NSError *error = videoWriter.error; if(error!=nil) { NSLog(@"Unresolved error %@,%@.", error, [error userInfo]); } } j++; } if (!append_ok) { printf("error appending image %d times %d\n, with error.", frameCount, j); } frameCount++;}//Finish the session:[videoWriterInput markAsFinished];[videoWriter finishWritingWithCompletionHandler:^{ NSLog(@"Write Ended");}];}
How can I get a single random number from multiple possible ranges?
Would you choose a random Range and then use Random.Next() on that?
No, because that would give numbers in shorter ranges more weight. For example, if one range contains a single number 42 and the other range contains 10,000 numbers, then 42 would be generated roughly 50% of the time.
Or would you keep choosing random numbers until you got one that was within each of the ranges?
No, because that would not be the too efficient. For example, if the first range is [1..3] and the second range is [200,000..200,001], getting a number in one of these ranges would take a while.
I would implement a Size property on the range, compute the total size, generate an int in the range index = [0..TotalSize-1], and then picked the item at the index as if all numbers in your ranges were numbered sequentially.
For example, in your ranges TotalSize would be 6+7+12=25. First, I would generate a random number in the range [0..24], say, 15. I would then see that 15 falls in the third range, so I'd return 21.
This would give each range a weight proportional to its size. If you would like to assign specific weights to your ranges, the algorithm would be different: you would compute an equivalent of TotalRange by multiplying the actual size by the weight of the range, and totaling up the products. You would then generate a number in the range of that weighted sum, pick the range by working backward from that random number, and then dividing out the weight of the specific range to obtain the position of the random item in the range.
Most efficient and standard-compliant way of reinterpreting int as float
Assume I have guarantees that float is IEEE 754 binary32. Given a bit pattern that corresponds to a valid float, stored in std::uint32_t, how does one reinterpret it as a float in a most efficient standard compliant way?
float reinterpret_as_float(std::uint32_t ui) { return /* apply sorcery to ui */;}I've got a few ways that I know/suspect/assume have some issues:
Via reinterpret_cast,
float reinterpret_as_float(std::uint32_t ui) { return reinterpret_castor equvalently
float reinterpret_as_float(std::uint32_t ui) { return *reinterpret_castwhich suffers from aliasing issues.
Via union,
float reinterpret_as_float(std::uint32_t ui) { union { std::uint32_t ui; float f; } u = {ui}; return u.f;}which is not actually legal, as it is only allowed to read from most recently written to member. Yet, it seems some compilers (gcc) allow this.
Via std::memcpy,
float reinterpret_as_float(std::uint32_t ui) { float f; std::memcpy(&f, &ui, 4); return f;}which AFAIK is legal, but a function call to copy single word seems wasteful, though it might get optimized away.
Via reinterpret_casting to char* and copying,
float reinterpret_as_float(std::uint32_t ui) { char* uip = reinterpret_castwhich AFAIK is also legal, as char pointers are exempt from aliasing issues and manual byte copying loop saves a possible function call. The loop will most definitely be unrolled, yet 4 possibly separate one-byte loads/stores are worrisome, I have no idea whether this is optimizable to single four byte load/store.
The 4 is the best I've been able to come up with.
Am I correct so far? Is there a better way to do this, particulary one that will guarantee single load/store?
Grid view row command showing error
I am getting this error:
Invalid postback or callback argument. Event validation is enabled using
in configuration or <%@ Page EnableEventValidation="true" %> in a page. For security purposes, this feature verifies that arguments to postback or callback events originate from the server control that originally rendered them. If the data is valid and expected, use the ClientScriptManager.RegisterForEventValidation method in order to register the postback or callback data for validation.
This is my code:
protected void GridViewCommandEventHandler(object sender, GridViewCommandEventArgs e){ if (e.CommandName == "view") { int row_id = Convert.ToInt32(e.CommandArgument); var result = (from test in je.jobposting where test.id==row_id select test).FirstOrDefault(); Session["id"] = result; } else { int row_id = Convert.ToInt32(e.CommandArgument); var result = (from test in je.jobposting where test.id==row_id select test).FirstOrDefault(); je.DeleteObject(result); je.SaveChanges(); Response.Redirect (""); }}zurb-foundation 5 data-interchange w/ xhtml
I am using Foundation 5 responsive pack , I would like to incorporate jsf and richfaces into my design. For the different screen sizes , is it possible to use jsf/ richfaces components embedded in xhtml for the data-interchange instead of just plain html and html elements?
WILL data-interchange[....] work with .xhtml ?
When I use just basic html elements (no jsf or richface components) everything works as it should. I try to incorporate an xhtml with the following for example :
This doesn't work: larger_slider.xhtml
This works:large_slider.html <--- note the html extension
Safe. Fun. Online Streaming TV For Kids
100% Free To Try. Let's Get Started!
I would like to do this: where xhtml contain a jsf richfaces form components
how to get a list from C# code into a list in python
I have a C# DLL that I am calling in python and one of its methods returns what should be like a list
this code works
data =[0,1]ch=['VCC_CORE0','VCCSFR']data[0],data[1] = myDaqControl.SpyMulti(ch)but I am trying to make it dynamic don't want to add the list arguments at the start because in this example I have ch = 2 variables but next time it can be 5 or 10
so typing data[0],data[1]..... doesn't make sense
doing data = myDaqControl.SpyMulti(ch) doesn't work and I get from interpreter is:
i found out the the C# code should be returning an Array
additional code priore to what i mentioned
import clrimport sysimport timeitimport timeChannel ='Iin_P1'ConfigFile='c:\NiDaq_spy.xml'start_time = time.time()sys.path.append(r'C:\daq\Bin')clr.AddReference('DaqBase.Factory')from Daq import DaqControlFactoryfrom Daq import IDaqControlmyDaqControl = DaqControlFactory.GetDaqControl("NiDaq")الخميس، 26 ديسمبر 2013
How would I convert this form into codeigniter
I have the form below for a login page
I'd like to convert this to use the form_helper packaged with CodeIgniter. My issue though is the documentation only showed the most basic of examples. I'm not sure how I would put so much extra data inside each label (including the form_input). What is the easiest way to convert this?
UITextView to Mimic UITextField [for basic round corner text field]
I want to have UITextField with multiple lines, after a quick google on this issue I found that I should use TextView so I did switch my code to use UITextView when I want multiple lines. My View still have other one line textField that I want to keep.
To make my TextView looks like TextField, I had to add code to set border and radius, but they look a little bit different on iOS7. Does anyone know:
what is the color for the UITextField border? when both enabled and disabled so I can sent my textview to match it.what is radius of the corner of TextField.what is the background color for UITextField when it is disabled[attached picture shows the text field has lighter shade of grey when it is disabled]? so i can set my text view to the same color when i disable user interaction.If there is away to keep using textfield for multiline text, I am all ears and i switch to use it.
Best Regards,
Cross-compiler vs JVM
I am wondering about the purpose of JVM. If JVM was created to allow platform independent executable code, then can't a cross-compiler which is capable of producing platform independent executable code replace a JVM?
the information about cross-compiler was retrieved from: http://en.wikipedia.org/wiki/Cross_compiler
CoffeeScript: how to do f(a(1), b(2), c(3)) braceless style?
This is what your code translates to:
var f5, f6, f7;f5 = function(x) { return 500 + x;};f6 = function(x) { return 600 + x;};f7 = function(x) { return 700 + x;};console.log(f5(5, f6(6, f7(7)))); //505console.log(f5(5, f6(6, f7(7)))); //505console.log(f5(5, f6(6, f7(7)))); //505console.log(f5(5), f6(6), f7(7)); //505, 606, 707So in your 1st 3 logs you are calling f5 which only takes in one parameter therefore the rest of the arguments are ignored.
What you can do is this:
console.log( f5 5 f6 6 f7 7 )The multiple lines forces it to run as individual functions
You can do the same for objects, putting newlines adds a comma:
obj = a: 42 b: 23how to pass complex object to Web API method?
i have two models :-
public class Builder { [Key] [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)] public int BuilderId { get; set; } public string BuilderName { get; set; } }public class Project{ [Key] [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)] public int ProjectId { get; set; } [Required] public string ProjectName { get; set; } [Required] public string Location { get; set; } [Required] public int BuilderId { get; set; } public Builder builder { get; set; }}When i am trying to post the builder class object from client side to the web api method, then it is reading the object from body. there is no problem in that. but when i am trying to add any Project with some Builder then it is not calling to desired method. and my Web Method :-
public HttpResponseMessage PostProject([FromUri] Project project) { if (ModelState.IsValid) { db.Projects.Add(project); db.SaveChanges(); HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.Created, project); response.Headers.Location = new Uri(Url.Link("DefaultApi", new { id = project.ProjectId })); return response; } else { return Request.CreateResponse(HttpStatusCode.BadRequest); } }my method to call the web api method :-
public async TaskAs per my knowledge, i think it is creating problem because my object is complex. I am new to Web API any suggestions from you are welcome. Please help.
Any way to avoid "android:" statements in Android XML layout file?
Is there any way to avoid hundreds of "android:" statements in an Android XML layout file? I am new to Android and I find the "android:" statements make layouts very hard to read. Plus they are a pain to constantly type.
For example, instead of this:
android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_column="2"I would like to just see this:
layout_width="wrap_content"layout_height="wrap_content"layout_column="2"How to Debug External Eval Scripts
Specific example: the haystack.js script from How Big is Your Haystack?
I've searched for an answer and everything seems to point to using the //# sourceURL=name.js comment. However, the mechanics of how to accomplish this elude me (maybe I'm just dense).
Everyone always points to Debugging JavaScript, but the demo is broken (same-origin error). Other common examples do not provide insight for working with an external script such as this.
I've tried using Live Edit to insert the sourceURL comment, but so far the eval script never shows up in the Sources tab.
Would someone please walk me through the steps to complete this task?
UPDATE: This has proved to be an interesting and annoying endeavour. This particular site makes the task needlessly difficult with the following complications:
The haystack.js script includes document.write() statements (which load the other scripts used). These must be removed before the script is reloaded, otherwise the DOM is cleared.
The author uses a queer, backtick cipher form of obfuscation on the code. Therefore, code modifications (including the sourceURL) have to be made after obfuscation is removed, but before the eval takes place.
I kludged a partial solution. After loading jQuery into the page, I run this script:
$.ajax({ url: '/js/haystack.js', dataType: 'text'}).done(function(data) { // Remove document.write() statements and append sourceURL comment after obfuscation is removed var refactored = data.replace(/return d/, "return d.replace(/document\.write[^;]+;/g, '') + '\\n//# sourceURL=haystack.js\\n';"); $('head').append('');});Now haystack.js appears in the (no domain) tree of the Sources tab. Breakpoints can be set, but there is odd behavior. Seems the DOM event handlers are still bound to the original script (breakpoints in reloaded script handlers are never reached). Executing pageInit() again rebinds the handlers to the modified script, but page updates are still erratic. Not sure why the behavior persists. I can step through the code and everything appears normal there, but page updates seem to lag behind the code. The fact that the code violates almost every javascript best practice is no doubt a factor.
Populate values from one table
I am trying to populate an empty table(t) from another table(t2) based on a flag field being set. He is my attempt below and the table data.
UPDATE 2014PriceSheetIssues AS tJOIN TransSalesAvebyType2013Combined AS t2 SET t.`Tran_Type`=t2.`Tran_Type` WHERE t.`rflag`='1';Tran_Type; RetailAvePrice; WholesaleAvePrice; Rflag; Wflag;125C 992 650 1 \n2004R 1500 \N 1 \N4EAT 1480 1999 1 1MySQL- combinie two queries
I can't solve this problem:
I have mysql DB with many geo-coordinates.
I liked to know which points are within a specific number of miles from specific coordinates AND Which are within specific square.
Points within a specific area:
(SELECT *, 'area' as type, ( 3959 * acos( cos( radians(".$Plat.") ) * cos( radians( lat ) ) * cos( radians( lng ) - radians(".$Plng.") ) + sin( radians(".$lat.") ) * sin( radians( lat ) ) ) ) AS distance FROM ".$db." HAVING distance < ".$radius."points within a specific square:
SELECT *, 'square' as type, -1 AS distance FROM ".$db." WHERE ((Alat <= ".$Alat." AND ".$Alat." <= Blat) OR (Alat >= ".$Alat." AND ".$Alat." >= Blat)) AND ((Alng <= ".$Alng." AND ".$Alng." <= Blng) OR (Alng >= ".$Alng." AND ".$Alng." >= Blng)) ...I use UNION to combine both queries but the thing is "type" and "distance" have different values. So I get the searched point twice. I liked to have every point just once.
But I have no idea how to handle that.
Edit:
For an overview I took just some of the data.
As result I get something like that:
+------+-----------+-----------+----------+-------------+| id | Alat | Alng | distance | type |+------+-----------+-----------+----------+-------------+| 42 | 53.704678 | 10.202164 | 12345 | area +------+-----------+-----------+------------------------+| 72 | 23.704678 | 15.202164 | 12345 | area+------+-----------+-----------+------------------------+ ......+------+-----------+-----------+------------------------+| 42 | 53.704678 | 10.202164 | -1 | square+------+-----------+-----------+------------------------+| 81 | 43.778 | 15.201212 | -1 | square+------+-----------+-----------+------------------------+ ......id(72) exists just in the area an not in the square. id(81) exists just in the square an not in the area.id(42) is in the area and in the square too. So it appears two times. But it only should once. The area should get priority.but it just should be
+------+-----------+-----------+----------+-------------+| id | Alat | Alng | distance | type |+------+-----------+-----------+----------+-------------+| 42 | 53.704678 | 10.202164 | 12345 | area +------+-----------+-----------+------------------------+| 72 | 23.704678 | 15.202164 | 12345 | area+------+-----------+-----------+------------------------+ ......+------+-----------+-----------+------------------------+| 81 | 43.778 | 15.201212 | -1 | square+------+-----------+-----------+------------------------+ ......Project Euler #3 in Ruby
Project Euler Problem#3:
The prime factors of 13195 are 5, 7, 13 and 29. What is the largest prime factor of the number 600851475143 ?
def is_prime?(number) prime = true (2...number).each { |x| prime = false if number % x == 0 } primeenddef largest_prime(number) primes = [] (number.downto(1)).each {|x| primes.push(x) if number % x == 0 && is_prime?(x) break if primes.count == 1 } primes[0]endMy answer is written in Ruby. The code works for smaller numbers but not larger, can anyone explain what exactly is going on and how to get around it? I've seen other people with this issue -- sorry to repost -- but I'm a programming newb and I don't truly understand their answers, also haven't seen any other posts answering in Ruby. Thanks!
Fabric - render OverlayImage code raise Type Error
The fiddle is here : http://jsfiddle.net/mC4jM/
var canvas = new fabric.Canvas ("c2");canvas.backgroundColor = "#ddd";canvas.add(new fabric.Circle({ radius: 30, fill: '#f55', top: 100, left: 100 }));canvas.setOverlayImage('http://jsfiddle.net/img/logo.png', canvas.renderAll.bind(canvas));When you select area of the canvas, it will raise Type Error, and google chrome indicates its at line 5853 in fabric.js:
ctx.drawImage(this.overlayImage, this.overlayImageLeft, this.overlayImageTop);I used fabric.js 1.4.0 and tested in google chrome and FF.
Uncaught TypeError: Type error fabric.StaticCanvas.fabric.util.createClass.renderTop fabric.util.object.extend.__onMouseMove fabric.util.object.extend._onMouseMoveHow to get last point of a CGPAth
I want to get the last point ofa CGPath.
CGMutablePAthRef path = CGPathCreateMutable();CGPathMoveToPoint(path,p1.x,p1.y);CGPathAddCurveToPoint(path,c1.x,c1.y,c2.x,c2.y,c3.x,c3.y);I want to know the the co-ordinates of last point by processing path I tried CGPathGetCurrentPoint but it gives P1 I tried CGPathApply and kCGPathElementCloseSubpath but it also give me P1
DataGridViewCheckBoxCell click handling issue
I created a DataGridView control where the first column is a checkbox. When I click inside the check box, the code correctly executes. HOWEVER, when the click occurs in the cell but not in the checkbox, the code correctly handles the state of the checkbox but does not update the checkbox itself, so it remains in the state it was before the click.
How do I correct this?
private void myDataGrid_CellClick(object sender, DataGridViewCellEventArgs e) { if (e.RowIndex == -1) return; //check if row index is not selected DataGridViewCheckBoxCell ch1 = new DataGridViewCheckBoxCell(); ch1 = (DataGridViewCheckBoxCell)myDataGrid.Rows[e.RowIndex].Cells[0]; if (ch1.Value == null) ch1.Value = false; switch (ch1.Value.ToString()) { case "False": ch1.Value = true; break; case "True": ch1.Value = false; break; } //BUT doesn't seem to matter what I do with ch1.Value. Inside the checkbox all is OK but //outside, no. }If I click in another cell on the row, the check box is handled correctly. ONLY when I click in the check box cell but NOT in the checkbox itself. Thanks RON
URL Rewrite giving 500 internal error
I'm trying to perform a URL Rewrite but giving me a 500 Internal Server Error
I have an index.php file that can take a parameter which I called cmd so the URL should look like:
http://localhost/some_folder/index.php?cmd=some_parameter
What I'm trying to achieve is allowing users to just type any of the following:
http://localhost/some_folder/some_parameter
OR
http://localhost/some_folder/index/some_parameter
Here is my .htaccess file:
RewriteEngine On # Turn on the rewriting engineRewriteRule ^index.php/?$ index.php?cmd=shifts [NC,L]I also tried:
Options +FollowSymLinksRewriteEngine onRewriteRule /cmd/(.*)/ index.php?cmd=$1I don't know what I am doing wrong here!
BPEL apache ODe deploy
Could anyone point me how to deploy a BPEL in Apache Ode from java? Is there any convenient way to create the deploy.xml file and then deploy it? Creating it with plain XML and then saving to the process directory doesn't look nice.
ng-options with disabled rows
I do not believe there is a way to do what you are asking just using ng-options. This issue was raised on the angular project and is still open:
https://github.com/angular/angular.js/issues/638
It seems that the work around is to use a directive which is referenced here and in the github issue: http://jsfiddle.net/alalonde/dZDLg/9/
Here is the entire code from the jsfiddle for reference (the code below is from alande's jsfiddle):
clarification needed on Java's 32-bit integer representation system?
I need some clarifications regarding the binary representation of decimal in Java (or any other language for that matter).
pardon, if this is too basic, but I need to understand it thoroughly.
x = 31 is represented in Java 32 bit as:x — > 00000000 00000000 00000000 00011111 // the binary to decimal conversion is achieved by: 2^4+2^3+2^2+2^1+2^0=31Now, if you consider all the bits turned on, except the signed bit (most significant bit), we get
y -> 01111111 11111111 11111111 11111111and binary to decimal conversion by summing powers of 2 will be: 2^31+2^30………+2^3+2^2+2^1+2^0=4294967295.however, if you do:
System.out.println(Integer.parseInt("1111111111111111111111111111111",2));you get: 2147483647 which is 2^31-1so it means, the when 31 bits are turned on, I do not get the additive sum of the powers of 2. why is this?
may be I did not understand something, if some one could clarify that will be very helpful.
In case this helps: All the two raise powers till 31 are in this list:
[1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048, 4096, 8192, 16384, 32768, 65536, 131072, 262144, 524288, 1048576, 2097152, 4194304, 8388608, 16777216, 33554432, 67108864, 134217728, 268435456, 536870912, 1073741824, 2147483648]EDIT: I corrected the y-representation, now it has 32 bits, but if you calculate the 31 bits that are turned on with summing the powers, you would get 4294967295. I have one liner in python here
>>> reduce(lambda x,y: x+y, [pow(2,i) for i in range(32)])4294967295الأربعاء، 25 ديسمبر 2013
Parse //t tabs out of a .tsv via UNIX?
We are receiving a file that is delimited into columns with tabs (\t). When there is a tab present in one of the "fields" of the file, it comes in as a special tab with two backslashes (\tab).
This is causing a problem with our ETL software, so I am wondering how to take these double backslash files out prior to processing, but the sed syntax I'm using is not working:
sed "s/`echo \\\t`/ /g"Any help would be greatly appreciated.
argparse optional positional argument and subparsers arguments
To argp the subparser argument looks just like another positional, one that takes choices (the names of the subparsers). Also argp knows nothing about pos_arg1. That's in tmpp's list of arguments.
When argp sees filename command1 otherarg, filename and command1 satisfy its 2 positionals. otherarg is then passed on the tmpp.
With command1 otherarg, again 2 strings, 2 argp positionals. command is assigned to inputfile. There's no logic to backtrack and say command1 fits subcommands better, or that `tmpp' needs one of those strings.
You could change the 1st positional to an optional, --inputfile.
Or you could inputfile another positional of tmpp. If a number of the subparsers need it it, consider using parents.
argparse isn't a smart as you, and can't 'think ahead' or 'backtrack'. If it appears to do something smart it's because it uses re pattern matching to handle nargs values (e.g. ?, *, +).
EDIT
One way to 'trick' argparse into recognizing the first positional as the subparser is to insert an optional after it. With command1 -b xxx otherarg, -b xxx breaks up the list of positional strings, so only command1 is matched against inputfile and subcommands.
p=argparse.ArgumentParser()p.add_argument('file',nargs='?',default='foo')sp = p.add_subparsers(dest='cmd')spp = sp.add_parser('cmd1')spp.add_argument('subfile')spp.add_argument('-b')p.parse_args('cmd1 -b x three'.split())# Namespace(b='x', cmd='cmd1', file='foo', subfile='three')While argparse allows variable length positionals in any order, how it handles them can be confusing. It's easier to predict what argparse will do if there is only one such positional, and it occurs at the end.
الثلاثاء، 24 ديسمبر 2013
How do I get to the source of a function?
I have this piece of code:
I am trying to decypher how to get to the function elevate() when you click the following button:
ApplyHow can I get to the js file where the function executes from?
Select and summarize data from three tables
i have three tables
customer
id | name 1 | johnorders
id | customer_id | date1 | 1 | 2013-01-012 | 1 | 2013-02-013 | 2 | 2013-03-01order_details
id | order_id | qty | cost1 | 1 | 2 | 102 | 1 | 5 | 103 | 2 | 2 | 104 | 2 | 2 | 155 | 3 | 3 | 156 | 3 | 3 | 15i need to select data so i can get the output for each order_id the summary of the order sample output. I will query the database with a specific customer id
output
date | amount | qty | order_id2013-01-01 | 70 | 7 | 12013-02-01 | 50 | 4 | 2this is what i tried
SELECT orders.id, orders.date, SUM(order_details.qty * order_details.cost) AS amount, SUM(order_details.qty) AS qtyFROM orders LEFT OUTER JOIN order_details ON order_details.order_id=orders.id AND orders.customer_id = 1 GROUP BY orders.datebut this returns the same rows for all customers, only that the qty and cost dont hav values
How to remove recursion in EditText TextChangedListener?
I agree with @njzk2 comments re:InputFilter, if the recursion is the trouble you want to solve, you can try something like this to prevent it:
// make your TextWatcher a class variableprotected TextWatcher mTextWatcher = new TextWatcher() { public void afterTextChanged(Editable s) { textFixerUpper(search_name, s.toString()); } public void beforeTextChanged(CharSequence s, int start, int count, int after){} public void onTextChanged(CharSequence s, int start, int before, int count){} };protected textFixerUpper(EditText t, String s){ t.removeTextChangedListener(mTextWatcher); // remove the listener t.setText(s.replace("something", "s**ething")); // update the text t.addTextChangedListener(mTextWatcher); // add the listener back}or by setting a Boolean flag instead of removing and re-adding the listener....though either seems a bit messy.
Pass Matlab parameters to a C program
I wrote a simple C program which takes a command line argument and displays that argument:
#includeNow I want to run this program from within Matlab using the system() function:
x=3.14;cmd=['/path/to/program/./test',x];[status,cmdout]=system(cmd)This doesn't seem to work when I try it. I really don't know how to solve this. I'm using a Mac. Thanks in advance.
How can I extend Collection to provide a filtered object collection?
I'm trying to create a collection that acts just like all other collections, except when you read out of it, it can be filtered by setting a flag.
Consider this (admittedly contrived) example:
var list = new FilteredStringList() { "Annie", "Amy", "Angela", "Mary"};list.Filter = true;I added four items, but then I set the "Filter" flag, so that whenever I read anything out of it (or do anything that involves reading out of it), I want to filter the list to items that begin with "A".
Here's my class:
public class FilteredStringList : CollectionMy theory is that I'm overriding and filtering the Items property from the base Collection object. I assumed that all other methods would read from this collection.
If I iterate via ForEach, I get:
AnnieAmyAngelaYay! But, if I do this:
list.Count()I get "4". So, Count() is not respecting my filter.
And if I do this:
list.Where(i => i[1] == 'a')I still get "Mary" back, even though she shouldn't be there.
I know I can override all sorts of the Collection methods, but I don't really want to override them all. Additionally, I want all the LINQ methods to respect my filter.
Not able to get correct simulation waveform result
You currently sample the address in one cycle, then drive the data in the next cycle using sequential logic. You need data to be a combinational decode of your address.
Change:
always @(posedge clk)to:
always @*But, then there is no need for the clk input to input_ram.
How to replace text between two XML tags using jQuery or JavaScript?
I have a XML mark-up/code like the following. I want to replace the text inside one of the tags (in this case
The source is inside a textarea. I have the following code, but it is obviously not doing what I want.
code=$("xml-code").val(); // content of XML sourcenewBegin = "The same old beginning"; // new text insideThis is just appending to the existing text inside the begin tags. I have a feeling this can be done only using Regex, but unfortunately I have no idea how to do it.
How to get a percentile for an empirical data distribution and get it's x-coordinate?
I have some discrete data values, that taken together form some sort of distribution. This is one of them, but they are different with the peak being in all possible locations, from 0 to end.
So, I want to use it's quantiles (percentiles) in Python. I think I could write some sort of function, that would some up all values starting from zero, until it reaches desired percent. But probably there is a better solution? For example, to create an empirical distribution of some sort in SciPy and then use SciPy's methods of calculating percentiles?
In the very end I need x-coordinates of a left percentile and a right percentile. One could use 20% and 80% percentiles as an example, I will have to find the best numbers for my case later.
Thank you in advance!
Listbox character limit per line
I have a listbox in my windows form application that shows quite long texts. Since texts are so long, user have to use the horizontal slider for check the rest of text.
So, I want to limit listbox character per line. For every 50 char it should go to next row, so user won't have to use glider.
I can't put "new line" since text source is Sql Database.
My code is basically this:
listbox1.items.add(dbRead["LongText"]); // dbRead = SqlDataReaderSo I have to edit listbox itself. I've checked it a bit, but didn't manage to find. I've also tried to find an event like when text is changed, for every 50 char listbox.items.add("") etc. I'm still alien to syntax.
Any suggestions ?
C++ Multiple Parameter Object creation
I am a virtual beginner in programming and am trying to understand a simple part of Object oriented programming. I apologize in advance if the answer to my question seems obvious, but I have tried to find similar examples online using google and youtube but sadly nothing fits the bill. With that said here is my question.
I am trying to make a simple video game inventory similar to the ones you would see in RPGs such as Final Fantasy VI or Chrono Trigger. What I am having trouble with is creating the items of the inventory. What I'd like help with is how to create one object that defines one item, for example a potion. I know it will take multiple parameters which are listed here:
itemText = "Potion";itemDesc = "Regain 50 HP";itemEffect = playerHP + 50;buyCost = 50;sellCost = 25;What I'd like help with is syntax of the connection of these parameters in one object. Later I will use the data so that I can create an array that shows only the itemText and a Quantity for the player to see. Any and all help or places would be appreciated.
Thank you in advance, Delita
MySQL Proxy Error: Cannot Load Module "mysql.password"
I am trying to test out a MySQL Proxy Script to handle authentication. And I keep getting errror
2013-12-25 00:25:31: (critical) (lua-error) [E:\Downloads\MySQL\proxy\script.txt][string "E:\Downloads\MySQL\proxy\script.txt"]:2: module 'mysql.password' not found: no field package.preload['mysql.password'] no file 'E:\Downloads\MySQL\proxy\lib\mysql-proxy\lua\mysql\password.lua' no file 'E:\Downloads\MySQL\proxy\bin\lua-mysql\password.dll' no module 'mysql.password' in file 'E:\Downloads\MySQL\proxy\bin\lua-mysql.dll'Following is my code. By the looks of the message I am missing some files. But I could not find any help by searching. Any help will be appreciated.
local proto = assert(require("mysql.proto"))local password = assert(require("mysql.password"))function read_auth() print(" username : " .. proxy.connection.client.username) print(" password : " .. string.format("%q", proxy.connection.client.scrambled_password)) local c = proxy.connection.client local s = proxy.connection.server if c.username == "test" and -- the username we want to map password.check( s.scramble_buffer, c.scrambled_password, password.hash(password.hash("test")) -- its valid password ) then proxy.queries:append(1, proto.to_response_packet({ username = "root", response = password.scramble(s.scramble_buffer, password.hash("admin")), charset = 8, -- default charset database = c.default_db, max_packet_size = 1 * 1024 * 1024 }) ) return proxy.PROXY_SEND_QUERY -- works if you use lp:mysql-proxy r694 or later endendNon-ASCII chars in python file deletes other chars
Turns out the locale had to be set to sv_SE.utf8 rather than sv_SE or sv_SE.UTF-8. If you're from another country than Sweden (which statistically seems reasonable to assume) you obviously have to find the right locale name for your language and location.
Then just do this to generate (optional) your locale, and set it:
locale-gen sv_SE.utf8locale-update LANG=sv_SE.utf8rebootReplace LANG for any other environment variables you need to set. This will create/modify the file /etc/default/locale.
is there any shorthand method to handle loops if you know exactly how much times a loop needs to be executed
When the number of loops is known, the best option is the for loop. As your example shows, it will loop until the desired number of times, in your case 5 (the original loop and goes up 5 times for a total of 6, unless you have 7 entries in which case the 6 is your required value).
Foreach comes in handy particularly for arrays.
A while loop is used when calling information from a database.
@DigitalChris recommends str_repeat, but I think the for loop is clearer in terms of code. The best solution isn't always to be quick to do right away, it's often to be able to make quick changes if the need comes. Personal opinion, anyways.
How do i safely encrypt user data?
I am learning java ...basically i only know the basics and i am self learning and was unable to find a video /post /site to help me with encrypting data i have tried something and posted it in an old post however i was told its stupid and it was..
the way i want it to work is that i am saving the data that needs to be encrypted in a class that i created and its then saved into a map that connects each object with key(id) and then the map is saved to a .dat file my question here is what is the best way to encrypt that data into the .dat file and how do i use it.
Please keep in mind that i am a beginner and i am relaying this site to help me learn the language so maybe in the future i might answer questions as well.
i would also appreciate any link or tutorial that would help me learn java a little more i have read some books however i dont have any experienced individual to guide me and help me learning the language.
nohup vs screen -- which is better for long running process?
Background: I have a long running script that makes database schema changes that has output I would want to check after the migration. I would want to write this to a file.
I have been reading stack overflow about nohup and screen. I have tried both and have concerns about both.
IN: How to run process as background and never die?
They said they used nohup and putty killed the process. How is this possible? I have been unable to replicate using Mac OS X terminal.
With screen I am terrified of typing exit instead of ctrl + a, d
Also If I just quit the terminal app when using screen, it seems to preserve the state.
Screen seems to be the better solution because it is really nifty how you can have a bunch of them open and switch back to the state.
What would you recommend in my situation? I don't have the run the script for another month or so (When I have a release). Should I become more comfortable with screen and just stick with that?
How can i make my current opencart theme responsive?
How can i make my current active opencart theme responsive? I am using the theme shopcart from themeforest.
Regards
how to parse html result of google search in java
in my program i search in google and getting back the results,but as a html code i want to extract the links,and print in the console but i don't know how to parse html result
String url="http://www.google.com/search?q="; String charset="UTF-8"; String key=s; String query = String.format("%s",URLEncoder.encode(key, charset)); URLConnection con = new URL(url+ query).openConnection(); BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())); String inputLine; while ((inputLine = in.readLine()) != null) System.out.println(inputLine); in.close();What is the best way to do long running task in android?
I am new to android application development. I understand that in android, long running operations should not happen in main thread and we can use Async Task for doing the same. To do the following operations,
Download a file (> 5 MM) from server.Make a http/s call from the application.Make any call other than http (example - voice call) from the application.is Async Task the best approach or do we have any other options in android for any of the above tasks?
Flask-login not redirecting to previous page
I have seen quite a few questions with this in mind, but haven't been able to address my issue. I have a Flask app with flask-login for session management. And, when I try to view a page without logging in, I get redirected to a link in form of /login/?next=%2Fsettings%2F
The issue is, as far as I could have it understand, that the "next" argument holds the part of the site I actually need, but when submitting a request to a login form, it is done via POST, so this argument is no longer available for me to redirect it to.
I tried using Request.path from Request (and url) but both just return the /login/ as the request url/path, not the actual /login/?next=xxx.
My login method is as follows:
@app.route('/login/', methods=['GET', 'POST'])def login(): if request.method == 'POST': #getting the user user = User.get(request.form['username']) if user.user is None: return redirect('/login/') #actual login proces if user and check_password_hash(user.user.password, request.form['password']): login_user(user, remember=remember) #the redirection portion of the login process return redirect(request.path or ("/")) # I tried various options there but without success, like request.args['next'] and such return redirect('/login/') else: return redirect('/')Thanks
C++ windows label form
I need help getting label1 to display the string that the user inputs.
I know that std::string and System::string are two different types, so I casted the inputted string to String^.
The textbox:
private: System::Void text_box_1(System::Object^ sender, System::EventArgs^ e) { cin >> name; String^ something = gcnew String(name.c_str()); label1->Text = "Name->" + something;Function that returns string:
string getName() { return name; }The problem is, label1 always outputs "Name-> blank". What am I doing wrong?
How to prevent reloading webpages when hit back?
All the pages of my dynamic website is reloading when hit back button.How to prevent this?
Sorry, I could not read the content fromt this page.Is there is conversion of tableRecord into Result<Record>?
Here there is a method
public void refreshPeopleDetail(@BindingParam("TableRecord") TableRecord tableRecord) { ResultHow I convert this??
Optimising MySQL Database Indexes InnoDB
I have been Googleling for hours now and I haven't quite figured out how indexes work, because there are so many mixed answers available.
Let's say I have an query 1:
SELECT subid, subid2 FROM clicks WHERE wid=100 AND uid=123 AND time >= 1387886885And a query 2:
SELECT subid, subid2 FROM clicks WHERE fid=100 AND time >= 1387886885 AND uid=1231) How should I place indexes here? Should I use multi column index or single column indexes?
2) I found an answer on stackoverflow that suggested adding indexes to subid and subid2 also, should I do that?
Detect if a string consists of a substring of a string
You can split the strings into two arrays
a = "sun is clear".splitb = "sun cloud rain".splitand compute the intersection
a & b# => ["sun"] (a & b).empty?# => falseIf the intersection is not empty, then they share pieces. Otherwise, you can also compute the difference of a - b
(a - b).size == a.size# => falseHTML Character - Invisible space
I have a website name, Dalton Empire, only written without space (but I can't do that on Stackoverflow, as it won't be bold any more). So DaltonEmpire with the 'Empire' bold.
However, weird this may be, I'd like the user to, when he/she copies "DaltonEmpire" actually have written "Dalton Empire" in their clipboard (separated).
I only came to one solution; use a space, but make the letter-spacing -18px. Isn't there a neater solution, such as a HTML character for this?
My example JSFiddle:
- DaltonEmpire
- DaltonEmpire
- DaltonEmpire
- DaltonEmpire
- Dalton Empire The only one that works
Android - Background extending instead of aligning while scrolling
I'm trying to create a chat view(sent text,received text). The background drawable(box) is properly aligned to one side. When i scroll, it extends the box to fit the whole width. Not sure why this is happening. Any ideas? The problem i'm talking aboutHow i actually want it(this is before scrolling)
My custom adapter class
public class DisplayMessageAdapter extends ArrayAdapterMy Layout file
My Drawables - rcvd/send
yii cdbcriteria->with child table record not displayed in view
In yii based application Im working on a search query. query is performed on two tables customers and customerContacts. Customer can have one-to-many contacts in different countries
Im using cdbcriteria as:
$criteria = new CDbCriteria;$criteria->alias = 't' ;$criteria->with= array("customerContacts"=> array("select"=>"customerContacts.fullname")); $criteria->condition = " customerContacts.country_id = 1";$customers = Customer::model()->findAll($criteria);Relations are
In Costumer model:
'customerContacts' => array(self::HAS_MANY, 'customerContacts', 'customer_id'),in customerContact model:
'customer' => array(self::BELONGS_TO, 'Customer', 'customer_id'),Issue is that there is a fullname column in customerContact table. This cdbCriteria is picking that fullname but it is not displayed that in view page, although data exists in table.
view code
customerContacts->fullname;endforeach; ?>I'am stuck in this. please help where im doing wrong?
PHP Time to Relative Time
I am trying to convert my already-implemented date format of:
$dateEntered = date('mdY');To a relative time using this function:
function RelativeTime($dateEntered)Now, the actual script that runs all of this looks like:
0) { // this was in the past $ending = "ago"; } else { // this was in the future $difference = -$difference; $ending = "to go"; } for($j = 0; array_key_exists($j,$lengths)&&$difference >= $lengths[$j]; $j++) { $difference /= $lengths[$j]; $difference = round($difference); if($difference != 1) $periods[$j].= "s"; $text = "$difference $periods[$j] $ending"; return $text; }}// Check Service Call Status & Mail if found Unpaid $query = "SELECT id, account, status, dateEntered FROM service WHERE status = 'Unpaid'";$result = mysql_query($query) or die(mysql_error());while($row = mysql_fetch_row($result)){ $account = $row[1]; $status = $row[2]; $dateEntered = $row[3]; $timeToSend = RelativeTime(strtotime($dateEntered)); // mailStatusUpdate($account, $status, $timeToSend);}?>If I run the script, I get a return of "4 decades ago".
I have my service table with one record in it. The $dateEntered variable returns:
01302012This is shown in the print_r output below. I basically want this to say "x days ago" or whatever the increment is.
Instead of returning the correct information (such as x days ago), it returns:
4 decades agoObviously this is wrong. Here is a print row so you see what I am working with:
Array ( [0] => 26 [1] => Example Client [2] => Unpaid [3] => 01302012 ) 1(I don't know what that "1" at the end is, though.)
merge Array using Function in PHP
I am new to PHP programming and i want to do this functionality using php coding style. I have a two integer array and i want to merge it in to a single array without using any built in php function.Simply i want one function and i will pass the both array as a parameter and then after processing it will show the third array as a combine of that both.
$array1=array('11','12','13','14','15');$array2=array('21','22','23','24','25');So how i will achieve this functionality?
Can android apk file read and write xml file and update sqllite via xml data from server?
My problem is : 1) I want apk file to read xml file from remote server 2) Once its completed, I want to enter that data into sqllite db and process it. 3) Export updated data into xml format to remote server 4) Is apk file not able to update/read data from server?
500 internal server error - php
I am running the 1 website on my server. That website has a search facility.
When I search for a category named "apple" at that time its showing 10 results and I am getting search result page fine and fast. [RECORDS ARE PAGINATED 10 records per page]
Now, When I search for "orange" named category at that time its giving me an internal server 500 error. It's just because it's trying to pull 300000 records from the database. [After 2 mins I am getting this error on page]
So How can I resolve this issue? I have checked queries too and its all fine. I need to record faster with no errors like internal server.
Is there any way to resolve this?
Please help! Thank you....
stored procedure remote call not working
i have stored procedure sp_1 in server_A .i am calling this SP from Server_B the code is:exec Server_A.MyDb.dbo.SP_1 in the body of sp i have complicted logic in the final step I insert result to Table_A. running sp take 10 minute and return 'command complete successfully' but tabe_A is Empty (must be filled). i try to execute the body of script it work properly .and tble Fill as expect. i do'nt know what is wrong...? i try to execute sp_1 from Another server 'server_c' server_d it work fine. problem is with server_B
Replacing fragments dynamically not on button click or orientation change
I am reading data from a microcontroller from usb serial port.
Based on the data i receive i want to replace the fragments.
When i try my below code on button click the fragment gets replaced perfectly. But when i try to replace the fragment under some other conditions like is strings matched then it is not working.
It is not giving any error also. It just restarts the application.
I am using two fragmets firstscreen and RinseFragment.
On activity start firstscreen fragment is added . on string matched RinseFragment should replace firstscreen fragment.
Please refer my code below.
public class ProcessActivity extends FragmentActivity {public Physicaloid phy;TextView status;Handler mHandler = new Handler();@Overrideprotected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_process); phy = new Physicaloid(this); openDevice(); IntentFilter filter = new IntentFilter(); filter.addAction(UsbManager.ACTION_USB_DEVICE_ATTACHED); filter.addAction(UsbManager.ACTION_USB_DEVICE_DETACHED); registerReceiver(mUsbReceiver, filter); status = (TextView)findViewById(R.id.status); FirstScreen fs = new FirstScreen(); getFragmentManager().beginTransaction().add(R.id.fragment_container, fs).commit();} private void openDevice() { if (!phy.isOpened()) { if (phy.open()) { // default 9600bps phy.addReadListener(new ReadLisener() { String readStr; @Override public void onRead(int size) { byte[] buf = new byte[size]; phy.read(buf, size); try { readStr = new String(buf, "UTF-8"); modeselector(readStr); finish(); } catch (UnsupportedEncodingException e) { } } }); } } } public void modeselector(String s){ if(s.equals("R_A")){ RinseFragment rFragment = new RinseFragment(); FragmentTransaction transaction = getFragmentManager().beginTransaction(); transaction.replace(R.id.fragment_container, rFragment); transaction.addToBackStack(null); transaction.commit(); } if(s.equals("R_S")){ tvAppend(status,"RINSING . . ."); } else { } } BroadcastReceiver mUsbReceiver = new BroadcastReceiver() { public void onReceive(Context context, Intent intent) { String action = intent.getAction(); if (UsbManager.ACTION_USB_DEVICE_DETACHED.equals(action)) { closeDevice(); } } }; private void closeDevice() { if(phy.close()) { phy.clearReadListener(); } }Now my main activity xml file
Now my fragment files both are same with no contents , empty xml files.
FirstScreen.java
public class FirstScreen extends Fragment {@Overridepublic View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // TODO Auto-generated method stub return inflater.inflate(R.layout.firstscreen, container,false);}}
python multiprocess fails to start
Here is my code for a simple multiprocessing task in python
from multiprocessing import Processdef myfunc(num): tmp = num * num print 'squared O/P will be ', tmp return(tmp)a = [ i**3 for i in range(5)] ## just defining a listtask = [Process(target = myfunc, args = (i,)) for i in a] ## creating processesfor each in task : each.start() # starting processes <------ problem linefor each in task : each.join() # waiting all to finish upWhen I run this code, it hangs at certain point, so to identify it I ran it line by line in python shell and found that when I call 'each.start()' The shell pops out a dialogue box as:
" The program is still running , do you want to kill it? 'and I select 'yes' the shell closes.
When I replace Process with 'threading.Thread' the same code runs but with this nonsense output:
Squared Squared Squared Squared Squared 0 149162536496481Is there any help in this regard ? thank in advance
How to extract image from JSON response in iOS
For extercating the Photo name from the JASON response you can use this code
JSONResponse : [ { "photo": "23_841676772.jpg", "date": "2013-06-06 08:11:15", "tags": "", "ID_article": "1", "commentcount": "5" },]Make a Array object in .h file
@interface ViewController : UIViewController{ NSMutableArray * photoNameData;}And in .m file
photoNameData =[[NSMutableArray alloc] init];NSMutableArray * tmpAry = JSONResponse;if (tmpAry.count !=0) { for (int i=0; i
You can use the code below to download the image in document directory.
And you can use this image using this code..
NSString* tmpStr = @"23_841676772.jpg"; //You can use code above to get image nameNSString * documentsDirectoryPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];UIImage * image = [UIImage imageWithContentsOfFile:[NSString stringWithFormat:@"%@/%@",documentsDirectoryPath, tmpStr]];javax.mail.AuthenticationFailedException
This is an edit. I will improve the question shortly.
stack trace:
run:-- listing properties --mail.smtp.gmail=smtp.gmail.commail.smtps.quitwait=truemail.smtp.starttls.enable=truemail.email=hawat.thufir@gmail.commail.smtp.connectiontimeout=2000mail.smtp.user=hawat.thufir@gmail.commail.smtp.socketFactory.class=SSL_FACTORYmail.smtp.password=passwordnntp.host=nntp://localhost/mail.smtp.socketFactory.port=465mail.smtp.timeout=2000mail.user=hawat.thufirmail.imap.port=993mail.imap.timeout=5000mail.smtp.socketFactory.fallback=falsemail.smtp.port=587mail.smtp.auth=truemail.imap.host=imap.gmail.commail.nntp.newsrc.file=/home/thufir/.newsrcmail.imap.connectiontimeout=5000mail.smtp.host=smtp.gmail.com========message follows==========smtp.gmail.comhawat.thufir@gmail.compassword587[Ljavax.mail.internet.InternetAddress;@ca128d[Ljavax.mail.internet.InternetAddress;@881278hello gmailtrying...Dec 24, 2013 4:20:21 AM net.bounceme.dur.nntp.Gmailcode:
package net.bounceme.dur.nntp;import gnu.mail.providers.smtp.SMTPTransport;import java.io.IOException;import java.net.PasswordAuthentication;import java.util.Properties;import java.util.logging.Level;import java.util.logging.Logger;import javax.mail.Message;import javax.mail.MessagingException;import javax.mail.NoSuchProviderException;import javax.mail.Session;import javax.mail.internet.InternetAddress;import javax.mail.internet.MimeMessage;public class Gmail { private Message message = null; private Session session = null; private Properties props = null; // private SMTPTransport transport = null; public Gmail() { try { sendMessage(); } catch (NoSuchProviderException ex) { Logger.getLogger(Gmail.class.getName()).log(Level.SEVERE, null, ex); } catch (MessagingException ex) { Logger.getLogger(Gmail.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(Gmail.class.getName()).log(Level.SEVERE, null, ex); } } public static void main(String[] args) { new Gmail(); } private void sendMessage() throws NoSuchProviderException, MessagingException, IOException { props = PropertiesReader.getProps(); props.list(System.out); System.out.println("\n========message follows==========\n"); session = Session.getInstance(props); session.setDebug(true); message = new MimeMessage(session); String host = props.getProperty("mail.smtp.host"); String user = props.getProperty("mail.smtp.user"); String password = props.getProperty("mail.smtp.password"); int port = Integer.parseInt(props.getProperty("mail.smtp.port")); System.out.println(host + user + password + port); message.setFrom(new InternetAddress(props.getProperty("mail.email"))); message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(props.getProperty("mail.email"), false)); message.setText("hello gmail"); System.out.println(message.getFrom().toString()); System.out.println(message.getRecipients(Message.RecipientType.TO).toString()); System.out.println(message.getContent().toString()); SMTPTransport transport = (SMTPTransport) session.getTransport("smtp"); System.out.println("trying..."); transport.connect(host, port, user, password); System.out.println("...connected"); transport.sendMessage(message, message.getAllRecipients()); transport.close(); }}Resume to SurfaceView shows black screen
The answer depends on how you change to the other activity.
Basically, you have to think about how to store the current state of the surface when the activity pauses, stops or destroys.
for example you can overload onSaveInstanceState in your activity to save degreUP and degreDOWN (by the way they are not defined in the current code snippet). and restore them in onRestoreInstanceState. see How do I save an Android application's state?
How to get dollar conversion rate in InApp purchase in iOS
I'm currently doing InApp purchase in an app, currently I'm following raywenderlich tutorial http://www.raywenderlich.com/21081/introduction-to-in-app-purchases-in-ios-6-tutorial and so far everythings working well. Now the problem is I'm required to do some points calculation based on the product.price from the below function based on dollars. Currently this will work for account based on US market but for other currencies the below log for My point will show a different value. In androids InApp purchase api they also return a microunits apart from price so we can convert into dollar using that microunits, I was wondering if there is any similar thing that is returned in iOS. Is there any workaround for this issue?
- (void)productPurchased:(NSNotification *)notification { SKPaymentTransaction *transaction=notification.object; NSString * productIdentifier = transaction.payment.productIdentifier; [products enumerateObjectsUsingBlock:^(SKProduct * product, NSUInteger idx, BOOL *stop) { if ([product.productIdentifier isEqualToString:productIdentifier]) { NSLog(@"Current Rate:%@",product.price); NSlog(@"My Points:%f" [product.price floatValue]*myPointsFactor); } }];}Eclipse: Unknown tags on new line
Here is the configuration screen for Eclipse under Java. I don't have the HTML plugin for Eclipse, but I'm guessing it's similar. (Under "Java"/"HTML" -> "Code Style" -> "Formatter" -> "Edit" -> "New Line".)
http://imgur.com/870A5yw
My apologies for the image link, apparently need more reputation to post actual images. :'(
Understanding Cmdlet positional parameter
All, Forgive me I am a newbie for the Power Shell, Currently I was reading book Windows PowerShell CookBook try to get start with it. So far, Everything make sense to me except one thing, I was totally confused with the Positional Parameter to Cmdlet.
For example: Select-String
The syntax is following :
Select-String [-Pattern]I can pass the parameter value to the Cmdlet directly by ignoring the parameter name . like below:
"Hello World"|Select-String .Based on the concept of Positional parameter,Because the parameter -Pattern is the first parameter. the value . can match the parameter -Pattern. It is ok for me to understand.
But When I try this command line "hello world" | Select-String -AllMatches . the value . is not in the first. Why the Select-String can know it and work out the result ? Could someone please tell me more to better understand it ? thanks.
HTML to PDF through url C# .net freeware library
Please suggest a freeware HTML to PDF converter library(dll) for .net c# which can convert HTML url to PDF.
I've used several but those were trial version (evolution purpose) only and put there titles on header or in centre of PDF page
Why JDBC cant connect to local Mysql Server
I have a machine with CentOS and mysql server on it (let's call it 'Server'). And another(my desktop) machine with Debian (let's call it 'Desktop'). I tried to launch java program on Desktop machine. Application connects to Server's mysql database without any troubles.
When I finished development of this application (it's still works and connects to DB well) I tried to deploy this app to Server machine. I'v built it the app on the server and tried to launch, using database, which still hosted on Server machine. So now it seems to be local database for my application. But it fails during connection to DB using Server IP address or "localhost" or 127.0.0.1. I have only:
java.sql.SQLException: null, message from server: "Host '82.192.90.179' is not allowed to connect to this MySQL server".In my.cnf file on Server I've set "bind-address=0.0.0.0".
PS:The most interesting thing, I do everything on server using ssh, and if I try to connect to database with "mysql" console tool, it connects OK either with -h82.192.90.179 and without -h option(seems to be localhost as a dafault)
call to a member function execute() on
Having trouble with line 27, Don't quite know why as I am very new to PHP/MySQL. Was wondering if anybody can advise me why I am getting the error;
"Fatal error: Call to a member function execute() on a non-object in C:\xampp\htdocs\testscripts\usercreate.php on line 27"
in the following code:
prepare($sql);$stmt->execute(array( ":name" => $name, ":psswrd" => $psswrd));PHP Code seems to not work [closed]
It is not working because you are using $interval->a for days and $interval->S for seconds. Correct is $interval->days (for if ($interval->days <= 7)), $interval->d (for if($interval->d !== 0)) and $interval->s (for if($interval->s !== 0)).
See DateInterval for correct parameters.
You can use this code:
echo time_elapsed_string('2013-09-01 00:22:35');echo time_elapsed_string('2013-09-01 00:22:35', true);17 days ago17 days, 1 hour, 40 minutes, 12 seconds agoLink to the function.
Spatial query w/o spatial data
I trying to execute a next query on Oracle Database 11g Enterprise Edition (11.1.0.6.0):
SELECT "__ItemId"FROM "Cities"WHERE "Longitude" IS NOT NULL AND "Latitude" IS NOT NULL AND SDO_ANYINTERACT(SDO_GEOMETRY('POINT(' || "Longitude" || ' ' || "Latitude" || ')'), SDO_UTIL.FROM_WKTGEOMETRY('POLYGON ((-100 80, 100 80, 100 -80, -100 -80, -100 80))')) = 'TRUE'Where "Longitude" and "Latitude" - numeric [NUMBER(28,5)] columns in the "Cities" table.
I get an error:
Error report -SQL Error: ORA-13226: interface not supported without a spatial indexORA-06512: at "MDSYS.MD", line 1723ORA-06512: at "MDSYS.MDERR", line 8ORA-06512: at "MDSYS.SDO_3GL", line 71ORA-06512: at "MDSYS.SDO_3GL", line 23913226. 00000 - "interface not supported without a spatial index" *Cause: The geometry table does not have a spatial index. *Action: Verify that the geometry table referenced in the spatial operator has a spatial index on it.Questions:
How can I check, that point with specified "Longitude" and "Latitude" in the specified polygon? Polygon in not always simple, it can be any.How can I create a spatial index on a table without any spatial column?It's really, I can not just call a spatial operator?Removing cross-domain Distribution Lists from an AD user
I'm writing a script to disable users for our security team but I'm a bit hung up on distribution lists(DL). I have it correctly cycle through every DL but when it gets to one on one of our association's domains, I get an error that the server is not willing to process the request. I've seen a workaround using ADSI and the LDAP filter but that didn't work for me at all. I also found that this issue used to be caused by a weak password/strong password policy but the password policy is the same across all domains so I don't think that's the case.
Data Access from Entity framework works during debugging but not on live
I got unique situation in my Entityframework web application, I'm trying to load the fields in page through list but its keep saying "The objectContext insteance has been disposed and can no longer be used for operations that require a connection." But when I set the debugging point and step into to see what is the error it works fine??
Here is my codes: This is Under my Page Load Event...
private void loadGPYouth(){ ListThis is under GPYouthLoader class :
public static ListAnd This is my GPYouth class :
public partial class GPYouth{ public long YouthID { get; set; } public NullableError when pushing to github? [on hold]
I am trying to push to a project onto github using git push -u origin master but am getting the following error:
error: src refspec master does not match any.error: failed to push some refs to 'https://github.com/mantismamita/kirstens-git.git'This is my first attempt at actually pushing anything and a day ago I misspelled my github password when prompted. I've tried closing and reopening terminal, waiting a day, and even password caching but haven't had any luck. Any help explaining this error would be greatly appreciated.
Second commit:
! [rejected] master -> master (non-fast-forward)error: failed to push some refs to 'https://github.com/mantismamita/kirstens-git.git'hint: Updates were rejected because the tip of your current branch is behindhint: its remote counterpart. Merge the remote changes (e.g. 'git pull')hint: before pushing again.hint: See the 'Note about fast-forwards' in 'git push --help' for details.UPDATE: SOLVED (see comments)
الجمعة، 20 ديسمبر 2013
How to make this SQL query faster
I have two tables like
table1:
word ida 1a 2a 10c 20d 21e 30table2:
id1 id21 202 21Now if word='a' then I need to find out 'c' and 'd' using table1 and table2: I wrote a query, its working but taking too much time, because tables include huge data.
Query:
SELECT word FROM table1 WHERE id IN (SELECT id2 FROM table2 WHERE id1 IN ( SELECT id FROM table1 WHERE word = 'a'))Another query:
SELECT DISTINCT word FROM table1 WHERE id IN (SELECT id FROM table1 WHERE word = 'a')Laoding JSON data into Ext.data.Tree store on click on a button
I have created a tree panel in ExtJs 4.1 and that panel is associated with store. I have some JSON data available in a variable. How can I load that into into tree store on click of a button.
Ext.define('User', { extend: 'Ext.data.Model', fields: [ {name: 'id', type: 'int'}, {name: 'name', type: 'string'}, {name: 'phone', type: 'string', mapping: 'phoneNumber'} ]});var data = { users: [ { id: 1, name: 'Ed Spencer', phoneNumber: '555 1234' }, { id: 2, name: 'Abe Elias', phoneNumber: '666 1234' } ]};//note how we set the 'root' in the reader to match the data structure above
var store = Ext.create('Ext.data.TreeStore', { autoLoad: false, model: 'User', proxy: { type: 'memory', }});How can I load data on click of a button?
If Web API can be used just for Authentication using OAuth 2 in ASP.NET MVC4
I'm working on segregating the authentication part of my ASP.net MVC4 application using DotNetOAuth 2.0, Which will means that one project will do only authentication and send out response,based on response it will have access to other application.
The Idea is to get any application or project added later on use one common authentication process.
First thing came to my mind was building a service, in the process a read a lot about Web API and think it can help to achieve what I'm looking for.
Please suggest if you guys have implemented something like this or whats's the best practice.
Should i go with API or service, any link or sample to direct is appreciated
Get the inner HTML of a element in lxml
I am trying to get the HTML content of child node with lxml and xpath in Python. As shown in code below, I want to find the html content of the each of product nodes. Does it have any methods like product.html?
productGrids = tree.xpath("//div[@class='name']/parent::*")for product in productGrids: print #html content of product