You cannot load images directly with @2x
or @3x
, system selects appropriate image automatically, just specify the name using UIImage
:
UIImage(named: "green-square-Retina")
it would be great if somebody told to put gif into any folder instead of assets folder
From your Obc-C code I think you want to set an Image for button so try this way:
let playButton = UIButton(type: .Custom)
if let image = UIImage(named: "play.png") {
playButton.setImage(image, forState: .Normal)
}
In Short:
playButton.setImage(UIImage(named: "play.png"), forState: UIControlState.Normal)
For Swift 3:
let playButton = UIButton(type: .custom)
playButton.setImage(UIImage(named: "play.png"), for: .normal)
I am using xcode with ios 8 just uncheck the connect harware keyboard option in your Simulator-> Hardware-> Keyboard-> Connect Hardware Keyboard.
This will solve the issue.
Swift 2.0 solution is here:
let urlStr = “http://url_to_manage_post_requests”
let url = NSURL(string: urlStr)
let request: NSMutableURLRequest =
NSMutableURLRequest(URL: url!) request.HTTPMethod = "POST"
request.setValue(“application/json” forHTTPHeaderField:”Content-Type”)
request.timeoutInterval = 60.0
//additional headers
request.setValue(“deviceIDValue”, forHTTPHeaderField:”DeviceId”)
let bodyStr = “string or data to add to body of request”
let bodyData = bodyStr.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true)
request.HTTPBody = bodyData
let session = NSURLSession.sharedSession()
let task = session.dataTaskWithRequest(request){
(data: NSData?, response: NSURLResponse?, error: NSError?) -> Void in
if let httpResponse = response as? NSHTTPURLResponse {
print("responseCode \(httpResponse.statusCode)")
}
if error != nil {
// You can handle error response here
print("\(error)")
}else {
//Converting response to collection formate (array or dictionary)
do{
let jsonResult: AnyObject = (try NSJSONSerialization.JSONObjectWithData(data!, options:
NSJSONReadingOptions.MutableContainers))
//success code
}catch{
//failure code
}
}
}
task.resume()
Only need to set blank title text in ParentViewController.
self.navigationItem.title=@"";
If you need title text then Put below two methods in ParentViewController.
-(void)viewWillAppear:(BOOL)animated
{
self.navigationItem.title = @"TitleText";
}
-(void)viewWillDisappear:(BOOL)animated
{
self.navigationItem.title=@"";
}
As the other answers mention, you can use setTintColor:
, but you want a solid color and that's not possible to do setting the tint color AFAIK.
The solution is to create an image programmatically and set that image as the background image for all navigation bars via UIAppearance
. About the size of the image, I'm not sure if a 1x1 pixel image would work or if you need the exact size of the navigation bar.Check the second answer of this question to see how to create the image.
As an advice, I don't like to "overload" the app delegate with these type of things. What I tend to do is to create a class named AppearanceConfiguration
with only one public method configureAppearance
where I set all the UIAppearance stuff I want, and then I call that method from the app delegate.
You might be do that its works 100% .
- (void)viewDidLoad
{
[super viewDidLoad];
// init table view
tableView = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStylePlain];
// must set delegate & dataSource, otherwise the the table will be empty and not responsive
tableView.delegate = self;
tableView.dataSource = self;
tableView.backgroundColor = [UIColor cyanColor];
// add to canvas
[self.view addSubview:tableView];
}
#pragma mark - UITableViewDataSource
// number of section(s), now I assume there is only 1 section
- (NSInteger)numberOfSectionsInTableView:(UITableView *)theTableView
{
return 1;
}
// number of row in the section, I assume there is only 1 row
- (NSInteger)tableView:(UITableView *)theTableView numberOfRowsInSection:(NSInteger)section
{
return 1;
}
// the cell will be returned to the tableView
- (UITableViewCell *)tableView:(UITableView *)theTableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *cellIdentifier = @"HistoryCell";
// Similar to UITableViewCell, but
JSCustomCell *cell = (JSCustomCell *)[theTableView dequeueReusableCellWithIdentifier:cellIdentifier];
if (cell == nil) {
cell = [[JSCustomCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
}
// Just want to test, so I hardcode the data
cell.descriptionLabel.text = @"Testing";
return cell;
}
#pragma mark - UITableViewDelegate
// when user tap the row, what action you want to perform
- (void)tableView:(UITableView *)theTableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
NSLog(@"selected %d row", indexPath.row);
}
@end
just change this line
[img setImage:[UIImage imageNamed:@"anyImageName"]];
with following line
img = [UIImage imageNamed:@"anyImageName"];
Swift 4
You would need to use these two lines of code, in this specific order. All you need is to change the top and bottom value of the edge insets.
addButton.imageView?.contentMode = .scaleAspectFit
addButton.imageEdgeInsets = UIEdgeInsetsMake(10.0, 0.0, 10.0, 0.0)
Correct way to do in Swift 4,
If your frame as screen size is correct then put anywhere otherwise,
important to write this in viewDidLayoutSubviews
because we can get actual frame in viewDidLayoutSubviews
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
UIGraphicsBeginImageContext(view.frame.size)
UIImage(named: "myImage")?.draw(in: self.view.bounds)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
view.backgroundColor = UIColor.init(patternImage: image!)
}
I had the same error message because I called an alert in
- (void)applicationDidBecomeActive:(UIApplication *)application
instead of
- (void)applicationWillEnterForeground:(UIApplication *)application
In my case, I have to change the UIButton.Type from .custom
to .system
And:
button.setImage(UIImage(named: "unchecked"), for: .normal)
button.setImage(UIImage(named: "checked"), for: [.selected, .highlighted])
When handling tapping:
button.isSelected = !button.isSelected
Inside my UIViewController
derived class, I am using the following inside viewDidLoad
:
UIBarButtonItem *flipButton = [[UIBarButtonItem alloc]
initWithTitle:@"Flip"
style:UIBarButtonItemStyleBordered
target:self
action:@selector(flipView:)];
self.navigationItem.rightBarButtonItem = flipButton;
[flipButton release];
This adds a button to the right hand side with the title Flip, which calls the method:
-(IBAction)flipView
This looks very much like you #3, but it is working within my code.
For me, it was a leftover connection created in interfacebuilder bij ctrl-dragging. The name of the broken connection was in the error-log
*** Terminating app due to uncaught exception 'NSInvalidArgumentException',
reason: '-[NameOfYourApp.NameOfYourClass nameOfCorruptConnection:]:
unrecognized selector sent to instance 0x7f97a48bb000'
I had an action linked to a button. Pressing the button crashed the app because the Outlet no longer existed in my code. Searching for the name in the log led me to it in the storyboard. Deleted it, and the crash was gone!
If anyone is interested in a no-brainer solution for drawing an image in a custom rect in a context:
func drawImage(image: UIImage, inRect rect: CGRect, context: CGContext!) {
//flip coords
let ty: CGFloat = (rect.origin.y + rect.size.height)
CGContextTranslateCTM(context, 0, ty)
CGContextScaleCTM(context, 1.0, -1.0)
//draw image
let rect__y_zero = CGRect(origin: CGPoint(x: rect.origin.x, y:0), size: rect.size)
CGContextDrawImage(context, rect__y_zero, image.CGImage)
//flip back
CGContextScaleCTM(context, 1.0, -1.0)
CGContextTranslateCTM(context, 0, -ty)
}
The image will be scaled to fill the rect.
in a custom UITableViewCell -controller add this
-(void)layoutSubviews {
CGRect newCellSubViewsFrame = CGRectMake(0, 0, self.frame.size.width, self.frame.size.height);
CGRect newCellViewFrame = CGRectMake(self.frame.origin.x, self.frame.origin.y, self.frame.size.width, self.frame.size.height);
self.contentView.frame = self.contentView.bounds = self.backgroundView.frame = self.accessoryView.frame = newCellSubViewsFrame;
self.frame = newCellViewFrame;
[super layoutSubviews];
}
In the UITableView -controller add this
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
return [indexPath row] * 1.5; // your dynamic height...
}
Another info: If you want use a Route Constraint, imagine that you want force that parameter has int datatype, then you need use this syntax:
[Route("v1/location/**{deviceOrAppid:int?}**", Name = "AddNewLocation")]
The ? character is put always before the last } character
For more information see: Optional URI Parameters and Default Values
cbindX from the package gdata combines multiple columns of differing column and row lengths. Check out the page here:
http://hosho.ees.hokudai.ac.jp/~kubo/Rdoc/library/gdata/html/cbindX.html
It takes multiple comma separated matrices and data.frames as input :) You just need to
install.packages("gdata", dependencies=TRUE)
and then
library(gdata)
concat_data <- cbindX(df1, df2, df3) # or cbindX(matrix1, matrix2, matrix3, matrix4)
CA5386 : Vulnerability analysis tools will alert you to these codes.
Correct code :
ServicePointManager.ServerCertificateValidationCallback += (sender, certificate, chain, sslPolicyErrors) =>
{
return (sslPolicyErrors & SslPolicyErrors.RemoteCertificateNotAvailable) != SslPolicyErrors.RemoteCertificateNotAvailable;
};
IMO looking at the /proc
filesystem is less nasty than hacking the text output of ps
.
import os
pids = [pid for pid in os.listdir('/proc') if pid.isdigit()]
for pid in pids:
try:
print open(os.path.join('/proc', pid, 'cmdline'), 'rb').read().split('\0')
except IOError: # proc has already terminated
continue
Best practice is to mark function async void
only if it is fire and forget method, if you want to await on, you should mark it as async Task
.
In case if you still want to await, then wrap it like so await Task.Run(() => blah())
In pyspark,SparkSql syntax:
where column_n like 'xyz%'
might not work.
Use:
where column_n RLIKE '^xyz'
This works perfectly fine.
$.getJSon expects a callback functions either you pass it to the callback function or in callback function assign it to global variale.
var globalJsonVar;
$.getJSON("http://127.0.0.1:8080/horizon-update", function(json){
//do some thing with json or assign global variable to incoming json.
globalJsonVar=json;
});
IMO best is to call the callback function. which is nicer to eyes, readability aspects.
$.getJSON("http://127.0.0.1:8080/horizon-update", callbackFuncWithData);
function callbackFuncWithData(data)
{
// do some thing with data
}
This should work, but there is a little trick. After you enter the formula, you need to hold down Ctrl+Shift while you press Enter. When you do, you'll see that the formula bar has curly-braces around your formula. This is called an array formula.
For example, if the Months are in cells A2:A100
and the amounts are in cells B2:B100
, your formula would look like {=SUM(If(A2:A100="January",B2:B100))}
. You don't actually type the curly-braces though.
You could also do something like =SUM((A2:A100="January")*B2:B100)
. You'd still need to use the trick to get it to work correctly.
try this:
$('html, body').animate({scrollTop:$('#xxx').position().top}, 'slow');
$('#xxx').focus();
array_values does the job :
$myArray = array_values($myArray);
Also some other php function do not preserve the keys, i.e. reset the index.
sudo gem install cocoapods --pre -n /usr/local/bin
This works for me.
This is what we called Composite Formatting of the .NET Framework to convert the value of an object to its text representation and embed that representation in a string. The resulting string is written to the output stream.
The overloaded Console.WriteLine Method (String, Object)Writes the text representation of the specified object, followed by the current line terminator, to the standard output stream using the specified format information.
Because there are two print statements. First is inside function and second is outside function. When function not return any thing that time it return None value.
Use return
statement at end of function to return value.
e.g.:
Return None value.
>>> def test1():
... print "In function."
...
>>> a = test1()
In function.
>>> print a
None
>>>
>>> print test1()
In function.
None
>>>
>>> test1()
In function.
>>>
Use return statement
>>> def test():
... return "ACV"
...
>>> print test()
ACV
>>>
>>> a = test()
>>> print a
ACV
>>>
It's really not an 'either/or' situation. AJAX stands for Asynchronous JavaScript and XML, and JQuery is a JavaScript library that takes the pain out of writing common JavaScript routines.
It's the difference between a thing (jQuery) and a process (AJAX). To compare them would be to compare apples and oranges.
Got help from this discussion. In my case the
git reset HEAD subby
git commit
worked for me :)
Actually an other way to solve this could be, overwriting the CSS with insertRule
.
It gives the ability to inject CSS rules to an existing/new stylesheet. In my concrete example it would look like this:
//creates a new `style` element in the document
var sheet = (function(){
var style = document.createElement("style");
// WebKit hack :(
style.appendChild(document.createTextNode(""));
// Add the <style> element to the page
document.head.appendChild(style);
return style.sheet;
})();
//add the actual rules to it
sheet.insertRule(
"ul#mainFilter a:hover { color: #0000EE }" , 0
);
Demo with my 4 years old original example: http://jsfiddle.net/raPeX/21/
From the jQuery API Document
While JavaScript provides the
load
event for executing code when a page is rendered, this event does not get triggered until all assets such as images have been completely received. In most cases, the script can be run as soon as the DOM hierarchy has been fully constructed. The handler passed to.ready()
is guaranteed to be executed after the DOM is ready, so this is usually the best place to attach all other event handlers and run other jQuery code. When using scripts that rely on the value of CSS style properties, it's important to reference external stylesheets or embed style elements before referencing the scripts.In cases where code relies on loaded assets (for example, if the dimensions of an image are required), the code should be placed in a handler for the
load
event instead.
Answer to the second question -
No, they are identical as long as you are not using jQuery in no conflict mode.
This solution works only if you create in Xcode 7 the directory "10.0" and you have a mistake in your sentence:
ln -s /Applications/Xcode_8.app/Contents/Developer/Platforms/iPhoneOS.platform/DeviceSupport/10.0 \(14A345\) /Applications/Xcode_7.app/Contents/Developer/Platforms/iPhoneOS.platform/DeviceSupport/10.0
If you change your inc() function to this
public static Integer inc(Integer i) {
Integer iParam = i;
i = i+1; // I think that this must be **sneakally** creating a new integer...
System.out.println(i == iParam);
return i;
}
then you will see that it always prints "false". That means that the addition creates a new instance of Integer and stores it in the local variable i ("local", because i is actually a copy of the reference that was passed), leaving the variable of the calling method untouched.
Integer is an immutable class, meaning that you cannot change it's value but must obtain a new instance. In this case you don't have to do it manually like this:
i = new Integer(i+1); //actually, you would use Integer.valueOf(i.intValue()+1);
instead, it is done by autoboxing.
I was following a doc on line and thought this error meant a problem with the dependencies in NPM. however after a third look. I realized that it was a typo. I did not add a comma after the first dependency in package.json that the tutorial asked me to edit.
You need to use the public properties from Main
, and not try to directly change the internal variables.
Instead of Tick
event, use Elapsed
event.
timer.Elapsed += new EventHandler(TimerEventProcessor);
and change the signiture of TimerEventProcessor method;
private void TimerEventProcessor(object sender, ElapsedEventArgs e)
{
label1.Text = _counter.ToString();
_counter += 1;
}
Standard Bubble Sort implementation in Java:
//Time complexity: O(n^2)
public static int[] bubbleSort(int[] arr) {
if (arr == null || arr.length <= 1) {
return arr;
}
for (int i = 0; i < arr.length; i++) {
for (int j = 1; j < arr.length - i; j++) {
if (arr[j - 1] > arr[j]) {
arr[j] = arr[j] + arr[j - 1];
arr[j - 1] = arr[j] - arr[j - 1];
arr[j] = arr[j] - arr[j - 1];
}
}
}
return arr;
}
You can use the shortcut -I
for tar's --use-compress-program
switch, and invoke pbzip2
for bzip2 compression on multiple cores:
tar -I pbzip2 -cf OUTPUT_FILE.tar.bz2 DIRECTORY_TO_COMPRESS/
Since Symfony 3.1 you can use JSON Helper http://symfony.com/doc/current/book/controller.html#json-helper
public function indexAction()
{
// returns '{"username":"jane.doe"}' and sets the proper Content-Type header
return $this->json(array('username' => 'jane.doe'));
// the shortcut defines three optional arguments
// return $this->json($data, $status = 200, $headers = array(), $context = array());
}
With c#9 (2020) you can now check a parameter is null with this code:
if (name is null) { }
if (name is not null) { }
You can have more information here
If you want to cater to 1-word cell, use this... based upon astander's
=IFERROR(LEFT(A1,SEARCH(" ",A1)-1),A1)
Acording to your first code snipet seems ok, but I've got similar behavior caused by bad programing. Have you checked the "options" variable is not null before the put call?
I'm using Struts2 (2.3.3) webapp and use a HashMap for displaying results. When is executed (in a class initialized by an Action class) :
if(value != null) pdfMap.put("date",value.toString());
else pdfMap.put("date","");
Got this error:
Struts Problem Report
Struts has detected an unhandled exception:
Messages:
File: aoc/psisclient/samples/PDFValidation.java
Line number: 155
Stacktraces
java.lang.NullPointerException
aoc.psisclient.samples.PDFValidation.getRevisionsDetail(PDFValidation.java:155)
aoc.action.signature.PDFUpload.execute(PDFUpload.java:66)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
...
Seems the NullPointerException points to the put method (Line number 155), but the problem was that de Map hasn't been initialized before. It compiled ok since the variable is out of the method that set the value.
Add the -v
option to your grep
command to invert the results.
Like this:
>>>mystr = "abcdefghijkl"
>>>mystr[-4:]
'ijkl'
This slices the string's last 4 characters. The -4 starts the range from the string's end. A modified expression with [:-4]
removes the same 4 characters from the end of the string:
>>>mystr[:-4]
'abcdefgh'
For more information on slicing see this Stack Overflow answer.
The basic problem here is that you are mistaking System.Environment.Exit
for return
.
For anyone getting to this thread late, you may want to take a look back at the .Net Base Class Library (BCL). Many people missed the changes between .Net 1.1 and .Net 2.0 when the TraceSource class was introduced (circa 2005).
Using the TraceSource is analagous to other logging frameworks, with granular control of logging, configuration in app.config/web.config, and programmatic access - without the overhead of the enterprise application block.
There are also a number of comparisons floating around: "log4net vs TraceSource"
1.
first of all Port 80(or what ever you are using) and 443 must be allow for both TCP and UDP packets. To do this, create 2 inbound rules for TPC and UDP on Windows Firewall for port 80 and 443. (or you can disable your whole firewall for testing but permanent solution if allow inbound rule)
2.
You need to change the security setting on Apache to allow access from anywhere else, so edit your httpd.conf
file.
Change this section from :
# onlineoffline tag - don't remove
Order Deny,Allow
Deny from all
Allow from 127.0.0.1
Allow from ::1
Allow from localhost
To :
# onlineoffline tag - don't remove
Order Allow,Deny
Allow from all
if "Allow from all" line not work for your then use "Require all granted" then it will work for you.
In version 3 and > of WAMPServer there is a Virtual Hosts pre defined for localhost
so dont amend the httpd.conf
file at all, leave it as you found it.
Using the menus, edit the httpd-vhosts.conf
file.
It should look like this :
<VirtualHost *:80>
ServerName localhost
DocumentRoot D:/wamp/www
<Directory "D:/wamp/www/">
Options +Indexes +FollowSymLinks +MultiViews
AllowOverride All
Require local
</Directory>
</VirtualHost>
Amend it to
<VirtualHost *:80>
ServerName localhost
DocumentRoot D:/wamp/www
<Directory "D:/wamp/www/">
Options +Indexes +FollowSymLinks +MultiViews
AllowOverride All
Require all granted
</Directory>
</VirtualHost>
Note:if you are running wamp for other than port 80 then VirtualHost will be like VirtualHost *:86.(86 or port whatever you are using) instead of VirtualHost *:80
3. Dont forget to restart All Services of Wamp or Apache after making this change
You can do this today in Java with the Red5 media server from Flash. If you want to also decode and encode video in Java, you can use the Xuggler project.
Simple Solution Solution Works Given: If your HEAD commit is in sync with remote commit.
The cherry-picked commit will only contain your latest changes, not the old changes. You can now just rename this commit.
Just right click on a table and select "backup". The popup will show various options, including "Format", select "plain" and you get plain SQL.
pgAdmin is just using pg_dump to create the dump, also when you want plain SQL.
It uses something like this:
pg_dump --user user --password --format=plain --table=tablename --inserts --attribute-inserts etc.
Initialize the MailMessage
with sender and reciever's email addresses. It should be something like
string from = "[email protected]"; //Senders email
string to = "[email protected]"; //Receiver's email
MailMessage msg = new MailMessage(from, to);
Read the full code snippet of how to send emails in c#
Working Solution 100% Swift 5.3
i have read all the answers and want to share the code and hierarchy of lines which i have used in all my applications to animate them correctly, Some solutions here are not working, you should check them on slower devices e.g iPhone 5 at this moment.
self.btnHeightConstraint.constant = 110
UIView.animate(withDuration: 0.27) { [weak self] in
self?.view.layoutIfNeeded()
}
That attribute is basically the persistence for the "Associated Activity" selection above the layout. At runtime, a layout is always associated with an activity. It can of course be associated with more than one, but at least one. In the tool, we need to know about this mapping (which at runtime happens in the other direction; an activity can call setContentView(layout) to display a layout) in order to drive certain features.
Right now, we're using it for one thing only: Picking the right theme to show for a layout (since the manifest file can register themes to use for an activity, and once we know the activity associated with the layout, we can pick the right theme to show for the layout). In the future, we'll use this to drive additional features - such as rendering the action bar (which is associated with the activity), a place to add onClick handlers, etc.
The reason this is a tools: namespace attribute is that this is only a designtime mapping for use by the tool. The layout itself can be used by multiple activities/fragments etc. We just want to give you a way to pick a designtime binding such that we can for example show the right theme; you can change it at any time, just like you can change our listview and fragment bindings, etc.
(Here's the full changeset which has more details on this)
And yeah, the link Nikolay listed above shows how the new configuration chooser looks and works
One more thing: The "tools" namespace is special. The android packaging tool knows to ignore it, so none of those attributes will be packaged into the APK. We're using it for extra metadata in the layout. It's also where for example the attributes to suppress lint warnings are stored -- as tools:ignore.
1)declare the structs before the main function. it worked for me. 2) And also fix the spelling mistake of that variable name if any e
ALTER TABLE dbo.table
DROP CONSTRAINT uq_testConstrain
constraint name uq_testConstrain
can be found under database->table->keys folder
Try this function, it's ok to round up a double
'---------------Start -------------
Function Round_Up(ByVal d As Double) As Integer
Dim result As Integer
result = Math.Round(d)
If result >= d Then
Round_Up = result
Else
Round_Up = result + 1
End If
End Function
'-----------------End----------------
Short answer: You can't.
Technically there is an accurate way, which would be checking the property:
history.previous
However, it won't work. The problem with this is that in most browsers this is considered a security violation and usually just returns undefined.
history.length
Is a property that others have suggested...
However, the length doesn't work completely because it doesn't indicate where in the history you are. Additionally, it doesn't always start at the same number. A browser not set to have a landing page, for example, starts at 0 while another browser that uses a landing page will start at 1.
Most of the time a link is added that calls:
history.back();
or
history.go(-1);
and it's just expected that if you can't go back then clicking the link does nothing.
Do not use floats to store fixed-point, accuracy-required data. This example shows how to convert a float to NVARCHAR(50) properly, while also showing why it is a bad idea to use floats for precision data.
create table #f ([Column_Name] float)
insert #f select 9072351234
insert #f select 907235123400000000000
select
cast([Column_Name] as nvarchar(50)),
--cast([Column_Name] as int), Arithmetic overflow
--cast([Column_Name] as bigint), Arithmetic overflow
CAST(LTRIM(STR([Column_Name],50)) AS NVARCHAR(50))
from #f
Output
9.07235e+009 9072351234
9.07235e+020 907235123400000010000
You may notice that the 2nd output ends with '10000' even though the data we tried to store in the table ends with '00000'. It is because float
datatype has a fixed number of significant figures supported, which doesn't extend that far.
For simple usage I made a function that encodes the input string (binary data):
/* Encodes string to hexadecimal string reprsentation
Allocates a new memory for supplied lpszOut that needs to be deleted after use
Fills the supplied lpszOut with hexadecimal representation of the input
*/
void StringToHex(unsigned char *szInput, size_t size_szInput, char **lpszOut)
{
unsigned char *pin = szInput;
const char *hex = "0123456789ABCDEF";
size_t outSize = size_szInput * 2 + 2;
*lpszOut = new char[outSize];
char *pout = *lpszOut;
for (; pin < szInput + size_szInput; pout += 2, pin++)
{
pout[0] = hex[(*pin >> 4) & 0xF];
pout[1] = hex[*pin & 0xF];
}
pout[0] = 0;
}
Usage:
unsigned char input[] = "This is a very long string that I want to encode";
char *szHexEncoded = NULL;
StringToHex(input, strlen((const char *)input), &szHexEncoded);
printf(szHexEncoded);
// The allocated memory needs to be deleted after usage
delete[] szHexEncoded;
For those from 2018 and beyond, using npm version 5 or later: edit your package-lock.json
: remove the library from "requires"
section and add it under "dependencies".
For example, you want deglob
package to use glob
package version 3.2.11
instead of its current one. You open package-lock.json
and see:
"deglob": {
"version": "2.1.0",
"resolved": "https://registry.npmjs.org/deglob/-/deglob-2.1.0.tgz",
"integrity": "sha1-TUSr4W7zLHebSXK9FBqAMlApoUo=",
"requires": {
"find-root": "1.1.0",
"glob": "7.1.2",
"ignore": "3.3.5",
"pkg-config": "1.1.1",
"run-parallel": "1.1.6",
"uniq": "1.0.1"
}
},
Remove "glob": "7.1.2",
from "requires"
, add "dependencies"
with proper version:
"deglob": {
"version": "2.1.0",
"resolved": "https://registry.npmjs.org/deglob/-/deglob-2.1.0.tgz",
"integrity": "sha1-TUSr4W7zLHebSXK9FBqAMlApoUo=",
"requires": {
"find-root": "1.1.0",
"ignore": "3.3.5",
"pkg-config": "1.1.1",
"run-parallel": "1.1.6",
"uniq": "1.0.1"
},
"dependencies": {
"glob": {
"version": "3.2.11"
}
}
},
Now remove your node_modules
folder, run npm install
and it will add missing parts to the "dependencies"
section.
insert into TABLENAMEA (A,B,C,D)
select A::integer,B,C,D from TABLENAMEB
In my case, I only updated the custom view.
// DO NOT LIKE THIS
customView.layoutIfNeeded() // Change to view.layoutIfNeeded()
UIView.animate(withDuration: 0.5) {
customViewConstraint.constant = 100.0
customView.layoutIfNeeded() // Change to view.layoutIfNeeded()
}
TLDR: This got my Python meetup group past this problem when I was running a clinic on installing docker and most of the users were on OS X:
boot2docker init
boot2docker up
run the export
commands the output gives you, then
docker info
should tell you it works.
The Context (what brought us to the problem)
I led a clinic on installing docker and most attendees had OS X, and we ran into this problem and I overcame it on several machines. Here's the steps we followed:
First, we installed homebrew (yes, some attendees didn't have it):
ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"
Then we got cask, which we used to install virtualbox, and then used brew to install docker and boot2docker (all required for OS X) Don't use sudo for brew.:
brew install caskroom/cask/brew-cask
brew cask install virtualbox
brew install docker
brew install boot2docker
The Solution
That was when we ran into the problem the asker here got. The following fixed it. I understand init
was a one-time deal, but you'll probably have to run up
every time you start docker:
boot2docker init
boot2docker up
Then when up
has been run, it gives several export
commands. Copy-paste and run those.
Finally docker info
should tell you it's properly installed.
To Demo
The rest of the commands should demo it. (on Ubuntu linux I required sudo.)
docker run hello-world
docker run -it ubuntu bash
Then you should be on a root shell in the container:
apt-get install nano
exit
Back to your native user bash:
docker ps -l
Look for the about 12 digit hexadecimal (0-9 or a-f) identifier under "Container ID", e.g. 456789abcdef
. You can then commit your change and name it some descriptive name, like descriptivename
:
docker commit 456789abcdef descriptivename`
Log in as root, then run the following MySQL commands:
GRANT ALL PRIVILEGES ON *.* TO 'root'@'localhost';
FLUSH PRIVILEGES;
You may try this sample, and always check your Connection String, you can use this example with or with out bindingsource you can load the data to datagridview.
private void Employee_Report_Load(object sender, EventArgs e)
{
var table = new DataTable();
var connection = "ConnectionString";
using (var con = new SqlConnection { ConnectionString = connection })
{
using (var command = new SqlCommand { Connection = con })
{
if (con.State == ConnectionState.Open)
{
con.Close();
}
con.Open();
try
{
command.CommandText = @"SELECT * FROM tblEmployee";
table.Load(command.ExecuteReader());
bindingSource1.DataSource = table;
dataGridView1.ReadOnly = true;
dataGridView1.DataSource = bindingSource1;
}
catch(SqlException ex)
{
MessageBox.Show(ex.Message + " sql query error.");
}
}
}
}
TL;DR; If you're still having trouble after restarting apache or nginx, also try restarting the php-fpm
service.
The answers here don't always satisfy the requirement to force a reload of the php.ini file. On numerous occasions I've taken these steps to be rewarded with no update, only to find the solution I need after also restarting the php-fpm service. So if restarting apache or nginx doesn't trigger a php.ini update although you know the files are updated, try restarting php-fpm as well.
To restart the service:
Note: prepend sudo if not root
Using SysV Init scripts directly:
/etc/init.d/php-fpm restart # typical
/etc/init.d/php5-fpm restart # debian-style
/etc/init.d/php7.0-fpm restart # debian-style PHP 7
Using service wrapper script
service php-fpm restart # typical
service php5-fpm restart # debian-style
service php7.0-fpm restart. # debian-style PHP 7
Using Upstart (e.g. ubuntu):
restart php7.0-fpm # typical (ubuntu is debian-based) PHP 7
restart php5-fpm # typical (ubuntu is debian-based)
restart php-fpm # uncommon
Using systemd (newer servers):
systemctl restart php-fpm.service # typical
systemctl restart php5-fpm.service # uncommon
systemctl restart php7.0-fpm.service # uncommon PHP 7
Or whatever the equivalent is on your system.
The above commands taken directly from this server fault answer
You can format currency writing your own code but it is just solution for the moment - when your app will grow you can need other currencies.
There is another issue with this:
I think the best option is use complex solution for internationalization e.g. library vue-i18n( http://kazupon.github.io/vue-i18n/).
I use this plugin and I don't have to worry about such a things. Please look at documentation - it is really simple:
http://kazupon.github.io/vue-i18n/guide/number.html
so you just use:
<div id="app">
<p>{{ $n(100, 'currency') }}</p>
</div>
and set EN-us to get $100.00:
<div id="app">
<p>$100.00</p>
</div>
or set PL to get 100,00 zl:
<div id="app">
<p>100,00 zl</p>
</div>
This plugin also provide different features like translations and date formatting.
If the original Service .InstallLog and .InstallState files are still in the folder, you can try reinstalling the executable to replace the files, then use InstallUtil /u, then uninstall the program. It's a bit convoluted, but worked in a particular instance for me.
Updated: 19/03/2017
this.form.controls['dept'].setValue(selected.id);
OLD:
For now we are forced to do a type cast:
(<Control>this.form.controls['dept']).updateValue(selected.id)
Not very elegant I agree. Hope this gets improved in future versions.
Try this regex, it works for me:
function isUrl(s) {
var regexp = /(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/
return regexp.test(s);
}
Answer based on @EdChum's comment on his answer. Comment is this -
groupby is notoriously slow and memory hungry, what you could do is sort by column A, then find the idxmin and idxmax (probably store this in a dict) and use this to slice your dataframe would be faster I think
Let's first create a dataframe with 500k categories in first column and total df shape 20 million as mentioned in question.
df = pd.DataFrame(columns=['a', 'b'])
df['a'] = (np.random.randint(low=0, high=500000, size=(20000000,))).astype(str)
df['b'] = list(range(20000000))
print(df.shape)
df.head()
# Sort data by first column
df.sort_values(by=['a'], ascending=True, inplace=True)
df.reset_index(drop=True, inplace=True)
# Create a temp column
df['temp_idx'] = list(range(df.shape[0]))
# Take all values of b in a separate list
all_values_b = list(df.b.values)
print(len(all_values_b))
# For each category in column a, find min and max indexes
gp_df = df.groupby(['a']).agg({'temp_idx': [np.min, np.max]})
gp_df.reset_index(inplace=True)
gp_df.columns = ['a', 'temp_idx_min', 'temp_idx_max']
# Now create final list_b column, using min and max indexes for each category of a and filtering list of b.
gp_df['list_b'] = gp_df[['temp_idx_min', 'temp_idx_max']].apply(lambda x: all_values_b[x[0]:x[1]+1], axis=1)
print(gp_df.shape)
gp_df.head()
This above code takes 2 minutes for 20 million rows and 500k categories in first column.
This image summarizes the Linear layout.
You can follow this link for more information on the topic. Just Maths - Views, View Groups and Layouts
Video Tutorial For Linear Layout : Width, Height & Weights
There is another example which I would like to share with you
:D
http://www.sommarskog.se/dynamic_sql.html#cursor0
This is my opinion for my database as recommended by my mentor
@allain, @GateKiller your query selects users not logins
To select logins you can use this query:
SELECT name FROM master..sysxlogins WHERE sid IS NOT NULL
In MSSQL2005/2008 syslogins table is used insted of sysxlogins
"A program doesn't run any faster when it is read from a ".pyc" or ".pyo" file than when it is read from a ".py" file; the only thing that's faster about ".pyc" or ".pyo" files is the speed with which they are loaded. "
To start an Activity
in java we wrote Intent(this, Page2.class)
, basically you have to define Context
in first parameter and destination class in second parameter. According to Intent
method in source code -
public Intent(Context packageContext, Class<?> cls)
As you can see we have to pass Class<?>
type in second parameter.
By writing Intent(this, Page2)
we never specify we are going to pass class, we are trying to pass class
type which is not acceptable.
Use ::class.java
which is alternative of .class
in kotlin. Use below code to start your Activity
Intent(this, Page2::class.java)
Example -
val intent = Intent(this, NextActivity::class.java)
// To pass any data to next activity
intent.putExtra("keyIdentifier", value)
// start your next activity
startActivity(intent)
a quick way to see your errors whilst testing:
$error= $st->errorInfo();
echo $error[2];
Step 1: Go to directory where the classes are kept using command prompt (or Linux shell prompt)
Like for Project.
C:/workspace/MyProj/bin/classess/com/test/*.class
Go directory bin using command:
cd C:/workspace/MyProj/bin
Step 2: Use below command to generate jar file.
jar cvf helloworld.jar com\test\hello\Hello.class com\test\orld\HelloWorld.class
Using the above command the classes will be placed in a jar in a directory structure.
I believe you can create a new Vector using your ArrayList and pass that to the JCombobox Constructor.
JComboBox<String> combobox = new JComboBox<String>(new Vector<String>(myArrayList));
my example is only strings though.
For t2/m3/c3/c4/r3/i2/d2 instances:
m1 small, medium, and large instances tend to perform higher than expected. c1.medium is another freak, at 800 MBit/s.
I gathered this by combing dozens of sources doing benchmarks (primarily using iPerf & TCP connections). Credit to CloudHarmony & flux7 in particular for many of the benchmarks (note that those two links go to google searches showing the numerous individual benchmarks).
The large instance size has the most variation reported:
Burstable (T2) instances appear to exhibit burstable networking performance too:
The CloudHarmony iperf benchmarks show initial transfers start at 1 GBit/s and then gradually drop to the sustained levels above after a few minutes. PDF links to reports below:
t2.small (PDF)
Note that these are within the same region - if you're transferring across regions, real performance may be much slower. Even for the larger instances, I'm seeing numbers of a few hundred MBit/s.
By Using like
use css and font same location
@font-face {
font-family: 'Material-Design-Icons';
src: url('Material-Design-Icons.eot');
src: url('Material-Design-Icons.eot?#iefix') format('embedded-opentype'),
url('Material-Design-Icons.woff2') format('woff2'),
url('Material-Design-Icons.woff') format('woff'),
url('Material-Design-Icons.ttf') format('truetype'),
url('Material-Design-Icons.svg#ge_dinar_oneregular') format('svg');
font-weight: normal;
font-style: normal;
}
The problem is in the line,
int([x[age1]])
What you want is
x = int(age1)
You also need to convert the int to a string for the output...
print "Hi, " + name1+ " you will be 21 in: " + str(twentyone) + " years."
The complete script looks like,
name1 = raw_input("What's your name? ")
age1 = raw_input ("how old are you? ")
x = 0
x = int(age1)
twentyone = 21 - x
print "Hi, " + name1+ " you will be 21 in: " + str(twentyone) + " years."
In addition to what John Skeet said, here's an overview of the Java 7 project. It includes a list and description of the features.
Note: JDK 7 was released on July 28, 2011, so you should now go to the official java SE site.
Make sure your PYTHONHOME environment variable is set correctly. You will receive this error if PYTHONHOME is pointing to invalid location or to another Python installation you are trying to run.
Try this:
C:\>set PYTHONHOME=C:\Python27
C:\>python
Use
setx PYTHONHOME C:\Python27
to set this permanently for subsequent command prompts
This can be done using driver.execute_script():-
driver.execute_script("document.getElementById('myelementid').scrollIntoView();")
I guess you already have the process object of the running process (e.g. by GetProcessesByName()). You can then get the executable file name by using
Process p;
string filename = p.MainModule.FileName;
For what it's worth, you can use the autofocus
attribute on HTML5 compatible browsers. Works even on IE as of version 10.
<input name="myinput" value="whatever" autofocus />
You can just copy & paste these methods (Swift 4+):
class func encryptMessage(message: String, encryptionKey: String, iv: String) -> String? {
if let aes = try? AES(key: encryptionKey, iv: iv),
let encrypted = try? aes.encrypt(Array<UInt8>(message.utf8)) {
return encrypted.toHexString()
}
return nil
}
class func decryptMessage(encryptedMessage: String, encryptionKey: String, iv: String) -> String? {
if let aes = try? AES(key: encryptionKey, iv: iv),
let decrypted = try? aes.decrypt(Array<UInt8>(hex: encryptedMessage)) {
return String(data: Data(bytes: decrypted), encoding: .utf8)
}
return nil
}
Example:
let encryptMessage = encryptMessage(message: "Hello World!", encryptionKey: "mykeymykeymykey1", iv: "myivmyivmyivmyiv")
// Output of encryptMessage is: 649849a5e700d540f72c4429498bf9f4
let decryptedMessage = decryptMessage(encryptedMessage: encryptMessage, encryptionKey: "mykeymykeymykey1", iv: "myivmyivmyivmyiv")
// Output of decryptedMessage is: Hello World!
Don't forget encryptionKey & iv should be 16 bytes.
No root is required:
This code will get 3rd party packages path with the name so you can easily identify your APK
adb shell pm list packages -f -3
the output will be
package:/data/app/XX.XX.XX.apk=YY.YY.YY
now pull that package using below code:
adb pull /data/app/XX.XX.XX.apk
if you executed above cmd in C:>\
, then you will find that package there.
No there is no byte data type in C++. However you could always include the bitset header from the standard library and create a typedef for byte:
typedef bitset<8> BYTE;
NB: Given that WinDef.h defines BYTE for windows code, you may want to use something other than BYTE if your intending to target Windows.
Edit: In response to the suggestion that the answer is wrong. The answer is not wrong. The question was "Is there a 'byte' data type in C++?". The answer was and is: "No there is no byte data type in C++" as answered.
With regards to the suggested possible alternative for which it was asked why is the suggested alternative better?
According to my copy of the C++ standard, at the time:
"Objects declared as characters (char) shall be large enough to store any member of the implementations basic character set": 3.9.1.1
I read that to suggest that if a compiler implementation requires 16 bits to store a member of the basic character set then the size of a char would be 16 bits. That today's compilers tend to use 8 bits for a char is one thing, but as far as I can tell there is certainly no guarantee that it will be 8 bits.
On the other hand, "the class template bitset<N> describes an object that can store a sequence consisting of a fixed number of bits, N." : 20.5.1. In otherwords by specifying 8 as the template parameter I end up with an object that can store a sequence consisting of 8 bits.
Whether or not the alternative is better to char, in the context of the program being written, therefore depends, as far as I understand, although I may be wrong, upon your compiler and your requirements at the time. It was therefore upto the individual writing the code, as far as I'm concerned, to do determine whether the suggested alternative was appropriate for their requirements/wants/needs.
Your first requirement, how to clear or redraw whole canvas - Answer - use canvas.drawColor(color.Black) method for clearing the screen with a color of black or whatever you specify .
Your second requirement, how to update part of the screen - Answer - for example if you want to keep all other things unchanged on the screen but in a small area of screen to show an integer(say counter) which increases after every five seconds. then use canvas.drawrect method to draw that small area by specifying left top right bottom and paint. then compute your counter value(using postdalayed for 5 seconds etc., llike Handler.postDelayed(Runnable_Object, 5000);) , convert it to text string, compute the x and y coordinate in this small rect and use text view to display the changing counter value.
Logically OLAP functions are calculated after GROUP BY/HAVING, so you can only access columns in GROUP BY or columns with an aggregate function. Following looks strange, but is Standard SQL:
SELECT employee_number,
MAX(MAX(course_completion_date))
OVER (PARTITION BY course_code) AS max_course_date,
MAX(course_completion_date) AS max_date
FROM employee_course_completion
WHERE course_code IN ('M910303', 'M91301R', 'M91301P')
GROUP BY employee_number, course_code
And as Teradata allows re-using an alias this also works:
SELECT employee_number,
MAX(max_date)
OVER (PARTITION BY course_code) AS max_course_date,
MAX(course_completion_date) AS max_date
FROM employee_course_completion
WHERE course_code IN ('M910303', 'M91301R', 'M91301P')
GROUP BY employee_number, course_code
A JavaScript accordion does the trick.
This fiddle by W3Schools makes a simple task even more simple using nothing but javascript, which i partially reproduce below.
<head>
<style>
button.accordion {
background-color: #eee;
color: #444;
font-size: 15px;
cursor: pointer;
}
button.accordion.active, button.accordion:hover {
background-color: #ddd;
}
div.panel {
padding: 0 18px;
display: none;
background-color: white;
}
div.panel.show {
display: block;
}
</style>
</head><body>
<script>
var acc = document.getElementsByClassName("accordion");
var i;
for (i = 0; i < acc.length; i++) {
acc[i].onclick = function(){
this.classList.toggle("active");
this.nextElementSibling.classList.toggle("show");
}
}
</script>
...
<button class="accordion">Section 1</button>
<div class="panel">
<p>Lorem ipsum dolor sit amet</p>
</div>
...
<button class="accordion">Table</button>
<div class="panel">
<p><table name="detail_table">...</table></p>
</div>
...
<button class="accordion"><table name="button_table">...</table></button>
<div class="panel">
<p>Lorem ipsum dolor sit amet</p>
<table name="detail_table">...</table>
<img src=...></img>
</div>
...
</body></html>
if using php, don't forget to convert "
to '
. You can also use tables of data inside the button and it will still work.
Be aware of that if you use nested transactions, a ROLLBACK operation rolls back all the nested transactions including the outer-most one.
This might, with usage in combination with TRY/CATCH, result in the error you described. See more here.
Just to add this because this is the top result in google for this question. In sqlite I used this to get the rowcount.
WITH temptable AS
(SELECT one,two
FROM
(SELECT one, two
FROM table3
WHERE dimension=0
UNION ALL SELECT one, two
FROM table2
WHERE dimension=0
UNION ALL SELECT one, two
FROM table1
WHERE dimension=0)
ORDER BY date DESC)
SELECT *
FROM temptable
LEFT JOIN
(SELECT count(*)/7 AS cnt,
0 AS bonus
FROM temptable) counter
WHERE 0 = counter.bonus
Do not concatenate. It's not needed, us commas as echo can take multiple parameters
echo "Welcome ", $name, "!";
Regarding using single or double quotes the difference is negligible, you can do tests with large numbers of strings to test for yourself.
with a specific dir:
cd your_dir && curl -L https://download.calibre-ebook.com/3.19.0/calibre-3.19.0-x86_64.txz | tar zx
The +
operator returns the numeric representation of the object. So in your particular case, it would appear to be predicating the if on whether or not d
is a non-zero number.
You can do a column transformation by using apply
Define a clean function to remove the dollar and commas and convert your data to float.
def clean(x):
x = x.replace("$", "").replace(",", "").replace(" ", "")
return float(x)
Next, call it on your column like this.
data['Revenue'] = data['Revenue'].apply(clean)
Currently there is no direct Instagram API to get user id from user name. You need to call the GET /users/search API and then iterate the results and check if the username
field value is equal to your username or not, then you grab the id
.
The problem you're having is that the event-handlers are being bound before the elements are present in the DOM, if you wrap the jQuery inside of a $(document).ready()
then it should work perfectly well:
$(document).ready(
function(){
$("#music").click(function () {
$("#musicinfo").show("slow");
});
});
An alternative is to place the <script></script>
at the foot of the page, so it's encountered after the DOM has been loaded and ready.
To make the div
hide again, once the #music
element is clicked, simply use toggle()
:
$(document).ready(
function(){
$("#music").click(function () {
$("#musicinfo").toggle();
});
});
And for fading:
$(document).ready(
function(){
$("#music").click(function () {
$("#musicinfo").fadeToggle();
});
});
If you code for iOS 13.0 or later and want a timestamp, then you can use:
let currentDate = NSDate.now
For those who are new to SOAP
and want a quick explanation and guide, I strongly recommend this awesome medium article.
You can also use node-soap
package, with this simple tutorial.
Return false from the anonymous function:
$(xml).find("strengths").each(function() {
// Code
// To escape from this block based on a condition:
if (something) return false;
});
From the documentation of the each method:
Returning 'false' from within the each function completely stops the loop through all of the elements (this is like using a 'break' with a normal loop). Returning 'true' from within the loop skips to the next iteration (this is like using a 'continue' with a normal loop).
This happens when classes belonging to the same package are loaded from different JAR files, and those JAR files have signatures signed with different certificates - or, perhaps more often, at least one is signed and one or more others are not (which includes classes loaded from directories since those AFAIK cannot be signed).
So either make sure all JARs (or at least those which contain classes from the same packages) are signed using the same certificate, or remove the signatures from the manifest of JAR files with overlapping packages.
You can also click on the Formulas tab in Excel and select Show Formulas, then use the regular "Find" and "Replace" function. This should not affect the rest of your formula.
Swift 5
UIApplication.shared.statusBarFrame.height
You have some syntax issues with your script. Here is a fixed version:
#!/bin/bash
if [ "$seconds" -eq 0 ]; then
timezone_string="Z"
elif [ "$seconds" -gt 0 ]; then
timezone_string=$(printf "%02d:%02d" $((seconds/3600)) $(((seconds / 60) % 60)))
else
echo "Unknown parameter"
fi
I'm not sure you can use a relationship as an Id/PrimaryKey in Hibernate.
One of the elements to consider as you design your interface is on what event (when A takes place, B happens...) does the new checkbox end up being added?
Let's say there is a button next to the text box. When the button is clicked the value of the textbox is turned into a new checkbox. Our markup could resemble the following...
<div id="checkboxes">
<input type="checkbox" /> Some label<br />
<input type="checkbox" /> Some other label<br />
</div>
<input type="text" id="newCheckText" /> <button id="addCheckbox">Add Checkbox</button>
Based on this markup your jquery could bind to the click
event of the button and manipulate the DOM.
$('#addCheckbox').click(function() {
var text = $('#newCheckText').val();
$('#checkboxes').append('<input type="checkbox" /> ' + text + '<br />');
});
This is because of using integer indices (ix
selects those by label over -3 rather than position, and this is by design: see integer indexing in pandas "gotchas"*).
*In newer versions of pandas prefer loc or iloc to remove the ambiguity of ix as position or label:
df.iloc[-3:]
see the docs.
As Wes points out, in this specific case you should just use tail!
Uh, WHERE mydate<='2008-11-25'
is the way to do it. That should work.
Do you get an error message? Are you using an ancient version of MySQL?
Edit: The following works fine for me on MySQL 5.x
create temporary table foo(d datetime);
insert into foo(d) VALUES ('2000-01-01');
insert into foo(d) VALUES ('2001-01-01');
select * from foo where d <= '2000-06-01';
Dates in the
m/d/y
ord-m-y
formats are disambiguated by looking at the separator between the various components: if the separator is a slash (/
), then the Americanm/d/y
is assumed; whereas if the separator is a dash (-
) or a dot (.
), then the Europeand-m-y
format is assumed. Check more here.
Use the default date function.
$var = "20/04/2012";
echo date("Y-m-d", strtotime($var) );
EDIT I just tested it, and somehow, PHP doesn't work well with dd/mm/yyyy format. Here's another solution.
$var = '20/04/2012';
$date = str_replace('/', '-', $var);
echo date('Y-m-d', strtotime($date));
I want to present performance of different approaches, on Python 3.4, Linux x64. Excerpt from line profiler:
Line # Hits Time Per Hit % Time Line Contents
==============================================================
(...)
823 1508 11334 7.5 41.6 yday = int(period_end.strftime('%j'))
824 1508 2492 1.7 9.1 yday = period_end.toordinal() - date(period_end.year, 1, 1).toordinal() + 1
825 1508 1852 1.2 6.8 yday = (period_end - date(period_end.year, 1, 1)).days + 1
826 1508 5078 3.4 18.6 yday = period_end.timetuple().tm_yday
(...)
So most efficient is
yday = (period_end - date(period_end.year, 1, 1)).days
To pull data for the last 3 days, not the current date :
date(timestamp) >= curdate() - 3
AND date(timestamp) < curdate()
Example:
SELECT *
FROM user_login
WHERE age > 18
AND date(timestamp) >= curdate() - 3
AND date(timestamp) < curdate()
LIMIT 10
It's a strict check test.
It's a good thing especially if you're checking between 0 and false and null.
For example, if you have:
$a = 0;
Then:
$a==0;
$a==NULL;
$a==false;
All returns true and you may not want this. Let's suppose you have a function that can return the 0th index of an array or false on failure. If you check with "==" false, you can get a confusing result.
So with the same thing as above, but a strict test:
$a = 0;
$a===0; // returns true
$a===NULL; // returns false
$a===false; // returns false
A bit late to the party but might be valuable to someone with this error..
I just straight copied a bunch of files into an Xcode project, if you forget to add them to your projects Build Phases you will get the error "Undefined symbols for architecture i386". So add your implementation files to Compile Sources, and Xib files to Copy Bundle Resources.
The error was telling me that there was no link to my classes simply because they weren't included in the Compile Sources, quite obvious really but may save someone a headache.
Even though you define android:onClick = "DoIt" in XML, you need to make sure your activity (or view context) has public method defined with exact same name and View as parameter. Android wires your definitions with this implementation in activity. At the end, implementation will have same code which you wrote in anonymous inner class. So, in simple words instead of having inner class and listener attachement in activity, you will simply have a public method with implementation code.
I was having the same issue. It's easy to make it work on FF and Chrome, but on IE (8+ that we need to support) things get complicated. The easiest solution I could find for custom select elements that works "everywhere I tried", including IE8, is using .customSelect()
CSS
body {
background: rgb(204,204,204);
}
page[size="A4"] {
background: white;
width: 21cm;
height: 29.7cm;
display: block;
margin: 0 auto;
margin-bottom: 0.5cm;
box-shadow: 0 0 0.5cm rgba(0,0,0,0.5);
}
@media print {
body, page[size="A4"] {
margin: 0;
box-shadow: 0;
}
}
HTML
<page size="A4"></page>
<page size="A4"></page>
<page size="A4"></page>
My answer to this quesiton.
Modify file C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\Tools\vcvarsqueryregistry.bat
The content of :GetWin10SdkDir
From
@REM ---------------------------------------------------------------------------
:GetWin10SdkDir
@call :GetWin10SdkDirHelper HKLM\SOFTWARE\Wow6432Node > nul 2>&1
@if errorlevel 1 call :GetWin10SdkDirHelper HKCU\SOFTWARE\Wow6432Node > nul 2>&1
@if errorlevel 1 call :GetWin10SdkDirHelper HKLM\SOFTWARE > nul 2>&1
@if errorlevel 1 call :GetWin10SdkDirHelper HKCU\SOFTWARE > nul 2>&1
@if errorlevel 1 exit /B 1
@exit /B 0
to
@REM ---------------------------------------------------------------------------
:GetWin10SdkDir
@call :GetWin10SdkDirHelper HKLM\SOFTWARE\Wow6432Node > nul 2>&1
@if errorlevel 1 call :GetWin10SdkDirHelper HKCU\SOFTWARE\Wow6432Node > nul 2>&1
@if errorlevel 1 call :GetWin10SdkDirHelper HKLM\SOFTWARE > nul 2>&1
@if errorlevel 1 call :GetWin10SdkDirHelper HKCU\SOFTWARE > nul 2>&1
@if errorlevel 1 exit /B 1
@setlocal enableDelayedExpansion
set HostArch=x86
if "%PROCESSOR_ARCHITECTURE%"=="AMD64" ( set "HostArch=x64" )
if "%PROCESSOR_ARCHITECTURE%"=="EM64T" ( set "HostArch=x64" )
if "%PROCESSOR_ARCHITECTURE%"=="ARM64" ( set "HostArch=arm64" )
if "%PROCESSOR_ARCHITECTURE%"=="arm" ( set "HostArch=arm" )
@endlocal & set PATH=%WindowsSdkDir%bin\%WindowsSDKVersion%%HostArch%;%PATH%
@exit /B 0
Modify this single place will enable the support for all Windows 10 sdk along with all build target of visual studio, including
They are all working.
Try using IgnoreDataMember
property
public class Foo
{
[IgnoreDataMember]
public int Id { get; set; }
public string Name { get; set; }
}
I had this problem, but only in Visual Studio Code, not in ISE. Turns out I was using an x86 session in VSCode. I displayed the PowerShell Session Menu and switched to the x64 session, and all the modules began working without full paths. I am using Version 1.17.2, architecture x64 of VSCode. My modules were stored in the C:\Windows\System32\WindowsPowerShell\v1.0\Modules directory.
here is a trick
a = double.Parse(a.ToString().Split(',')[0])
Xcode 5.1 no longer provides command line tools in the Preferences section. You now go to https://developer.apple.com/downloads/index.action, and select the command line tools version for your OS X release. The installer puts them in /usr/bin.
I've done a lot of work on this kind of parsing. Because there are errors you won't get 100% accuracy, but there are a few things you can do to get most of the way there, and then do a visual BS test. Here's the general way to go about it. It's not code, because it's pretty academic to write it, there's no weirdness, just lots of string handling.
(Now that you've posted some sample data, I've made some minor changes)
I hope this helps somewhat.
In my somewhat checkered experience, applying -O3
to an entire program almost always makes it slower (relative to -O2
), because it turns on aggressive loop unrolling and inlining that make the program no longer fit in the instruction cache. For larger programs, this can also be true for -O2
relative to -Os
!
The intended use pattern for -O3
is, after profiling your program, you manually apply it to a small handful of files containing critical inner loops that actually benefit from these aggressive space-for-speed tradeoffs. Newer versions of GCC have a profile-guided optimization mode that can (IIUC) selectively apply the -O3
optimizations to hot functions -- effectively automating this process.
Better to use independent code.....
var xhrQueue = [];
$(document).ajaxSend(function(event,jqxhr,settings){
xhrQueue.push(jqxhr); //alert(settings.url);
});
$(document).ajaxComplete(function(event,jqxhr,settings){
var i;
if((i=$.inArray(jqxhr,xhrQueue)) > -1){
xhrQueue.splice(i,1); //alert("C:"+settings.url);
}
});
ajaxAbort = function (){ //alert("abortStart");
var i=0;
while(xhrQueue.length){
xhrQueue[i++] .abort(); //alert(i+":"+xhrQueue[i++]);
}
};
Works for ALL columns and Case Insensitive :
function search_table(){
// Declare variables
var input, filter, table, tr, td, i;
input = document.getElementById("search_field_input");
filter = input.value.toUpperCase();
table = document.getElementById("table_id");
tr = table.getElementsByTagName("tr");
// Loop through all table rows, and hide those who don't match the search query
for (i = 0; i < tr.length; i++) {
td = tr[i].getElementsByTagName("td") ;
for(j=0 ; j<td.length ; j++)
{
let tdata = td[j] ;
if (tdata) {
if (tdata.innerHTML.toUpperCase().indexOf(filter) > -1) {
tr[i].style.display = "";
break ;
} else {
tr[i].style.display = "none";
}
}
}
}
}
Django 1.7 solution for me:
There variables are exact to the question, but you should definitely be able to dissect this example
The key here is to pretty much use the .__dict__
of the model
views.py:
def display_specific(request, key):
context = {
'question_id':question_id,
'client':Client.objects.get(pk=key).__dict__,
}
return render(request, "general_household/view_specific.html", context)
template:
{% for field in gen_house %}
{% if field != '_state' %}
{{ gen_house|getattribute:field }}
{% endif %}
{% endfor %}
in the template I used a filter to access the field in the dict
filters.py:
@register.filter(name='getattribute')
def getattribute(value, arg):
if value is None or arg is None:
return ""
try:
return value[arg]
except KeyError:
return ""
except TypeError:
return ""
In a generic sense, a "hook" is something that will let you, a programmer, view and/or interact with and/or change something that's already going on in a system/program.
For example, the Drupal CMS provides developers with hooks that let them take additional action after a "content node" is created. If a developer doesn't implement a hook, the node is created per normal. If a developer implements a hook, they can have some additional code run whenever a node is created. This code could do anything, including rolling back and/or altering the original action. It could also do something unrelated to the node creation entirely.
A callback could be thought of as a specific kind of hook. By implementing callback functionality into a system, that system is letting you call some additional code after an action has completed. However, hooking (as a generic term) is not limited to callbacks.
Another example. Sometimes Web Developers will refer to class names and/or IDs on elements as hooks. That's because by placing the ID/class name on an element, they can then use Javascript to modify that element, or "hook in" to the page document. (this is stretching the meaning, but it is commonly used and worth mentioning)
Use http://jsfiddle.net//show/light/
then just use inspect element function of browser. you will get code in iframe tab. . in chrome just right click and cick on edit as html tab. and copy the html content. that is your actual code.
The !==
opererator tests whether values are not equal or not the same type.
i.e.
var x = 5;
var y = '5';
var 1 = y !== x; // true
var 2 = y != x; // false
Try this function
public void Wait(int time)
{
Thread thread = new Thread(delegate()
{
System.Threading.Thread.Sleep(time);
});
thread.Start();
while (thread.IsAlive)
Application.DoEvents();
}
Call function
Wait(1000); // Wait for 1000ms = 1s
You can create a function template like this:
template<int R, int C>
void myFunction(double (&myArray)[R][C])
{
myArray[x][y] = 5;
etc...
}
Then you have both dimension sizes via R and C. A different function will be created for each array size, so if your function is large and you call it with a variety of different array sizes, this may be costly. You could use it as a wrapper over a function like this though:
void myFunction(double * arr, int R, int C)
{
arr[x * C + y] = 5;
etc...
}
It treats the array as one dimensional, and uses arithmetic to figure out the offsets of the indexes. In this case, you would define the template like this:
template<int C, int R>
void myFunction(double (&myArray)[R][C])
{
myFunction(*myArray, R, C);
}
I don't know if this question is still relevant, but there is such possibility in Postman now. They added it a few months ago.
All you need is create simple .js file and run it via node.js. It looks like this:
var path = require('path'),
async = require('async'), //https://www.npmjs.com/package/async
newman = require('newman'),
parametersForTestRun = {
collection: path.join(__dirname, 'postman_collection.json'), // your collection
environment: path.join(__dirname, 'postman_environment.json'), //your env
};
parallelCollectionRun = function(done) {
newman.run(parametersForTestRun, done);
};
// Runs the Postman sample collection thrice, in parallel.
async.parallel([
parallelCollectionRun,
parallelCollectionRun,
parallelCollectionRun
],
function(err, results) {
err && console.error(err);
results.forEach(function(result) {
var failures = result.run.failures;
console.info(failures.length ? JSON.stringify(failures.failures, null, 2) :
`${result.collection.name} ran successfully.`);
});
});
Then just run this .js file ('node fileName.js' in cmd).
More details here
You can create a boolean field and check it inside run:
public class Task implements Runnable {
private volatile boolean isRunning = true;
public void run() {
while (isRunning) {
//do work
}
}
public void kill() {
isRunning = false;
}
}
To stop it just call
task.kill();
This should work.
You can also do:
git filter-branch --commit-filter '
if [ "$GIT_COMMITTER_NAME" = "<Old Name>" ];
then
GIT_COMMITTER_NAME="<New Name>";
GIT_AUTHOR_NAME="<New Name>";
GIT_COMMITTER_EMAIL="<New Email>";
GIT_AUTHOR_EMAIL="<New Email>";
git commit-tree "$@";
else
git commit-tree "$@";
fi' HEAD
Note, if you are using this command in the Windows command prompt, then you need to use "
instead of '
:
git filter-branch --commit-filter "
if [ "$GIT_COMMITTER_NAME" = "<Old Name>" ];
then
GIT_COMMITTER_NAME="<New Name>";
GIT_AUTHOR_NAME="<New Name>";
GIT_COMMITTER_EMAIL="<New Email>";
GIT_AUTHOR_EMAIL="<New Email>";
git commit-tree "$@";
else
git commit-tree "$@";
fi" HEAD
Try this:
import shutil
import os
source_dir = '/path/to/source_folder'
target_dir = '/path/to/dest_folder'
file_names = os.listdir(source_dir)
for file_name in file_names:
shutil.move(os.path.join(source_dir, file_name), target_dir)
You have to use the contents()
method:
$("#myiframe").contents().find("#myContent")
Source: http://simple.procoding.net/2008/03/21/how-to-access-iframe-in-jquery/
API Doc: https://api.jquery.com/contents/
All links to the Azure Active Directory Connection page now seem to be invalid.
I had an older version of Azure AD installed too, this is what worked for me. Install this.
Run these in an elevated PS session:
uninstall-module AzureAD # this may or may not be needed
install-module AzureAD
install-module AzureADPreview
install-module MSOnline
I was then able to log in and run what I needed.
I am sure we have a lot of good answers here. But, I just thought of adding the way I have used enumerated types
package main
import "fmt"
type Enum interface {
name() string
ordinal() int
values() *[]string
}
type GenderType uint
const (
MALE = iota
FEMALE
)
var genderTypeStrings = []string{
"MALE",
"FEMALE",
}
func (gt GenderType) name() string {
return genderTypeStrings[gt]
}
func (gt GenderType) ordinal() int {
return int(gt)
}
func (gt GenderType) values() *[]string {
return &genderTypeStrings
}
func main() {
var ds GenderType = MALE
fmt.Printf("The Gender is %s\n", ds.name())
}
This is by far one of the idiomatic ways we could create Enumerated types and use in Go.
Edit:
Adding another way of using constants to enumerate
package main
import (
"fmt"
)
const (
// UNSPECIFIED logs nothing
UNSPECIFIED Level = iota // 0 :
// TRACE logs everything
TRACE // 1
// INFO logs Info, Warnings and Errors
INFO // 2
// WARNING logs Warning and Errors
WARNING // 3
// ERROR just logs Errors
ERROR // 4
)
// Level holds the log level.
type Level int
func SetLogLevel(level Level) {
switch level {
case TRACE:
fmt.Println("trace")
return
case INFO:
fmt.Println("info")
return
case WARNING:
fmt.Println("warning")
return
case ERROR:
fmt.Println("error")
return
default:
fmt.Println("default")
return
}
}
func main() {
SetLogLevel(INFO)
}
The MD5 Hash algorithm is not reversible, so MD5 decode in not possible, but some website have bulk set of password match, so you can try online for decode MD5 hash.
Try online :
I think it may be a bug in chrome. There was a similar issue long back: See this.
Try in a different browser. I think it should work fine.
I would like to propose different solution which wasn't mentioned here which is using .URL
files:
set SHRT_LOCA=%userprofile%\Desktop\new_shortcut2.url
set SHRT_DEST=C:\Windows\write.exe
echo [InternetShortcut]> %SHRT_LOCA%
echo URL=file:///%SHRT_DEST%>> %SHRT_LOCA%
echo IconFile=%SHRT_DEST%>> %SHRT_LOCA%
echo IconIndex=^0>> %SHRT_LOCA%
Notes:
.url
files are intended to open web pages but they are working fine for any properly constructed URI.url
file extension even if "Hide extensions for known file types" option in Windows Explorer is disabledIconFile
and IconIndex
are optionalI was having the same issue
My Issue
Caused by: java.security.PrivilegedActionException: com.sun.xml.internal.bind.v2.runtime.IllegalAnnotationsException: 2 counts of IllegalAnnotationExceptions
Two classes have the same XML type name "{urn:cpq_tns_Kat_getgroupsearch}Kat_getgroupsearch". Use @XmlType.name and @XmlType.namespace to assign different names to them.
this problem is related to the following location:
at katrequest.cpq_tns_kat_getgroupsearch.KatGetgroupsearch
at public javax.xml.bind.JAXBElement katrequest.cpq_tns_kat_getgroupsearch.ObjectFactory.createKatGetgroupsearch(katrequest.cpq_tns_kat_getgroupsearch.KatGetgroupsearch)
at katrequest.cpq_tns_kat_getgroupsearch.ObjectFactory
this problem is related to the following location:
at cpq_tns_kat_getgroupsearch.KatGetgroupsearch
Two classes have the same XML type name "{urn:cpq_tns_Kat_getgroupsearch}Kat_getgroupsearchResponse0". Use @XmlType.name and @XmlType.namespace to assign different names to them.
this problem is related to the following location:
at katrequest.cpq_tns_kat_getgroupsearch.KatGetgroupsearchResponse0
at public javax.xml.bind.JAXBElement katrequest.cpq_tns_kat_getgroupsearch.ObjectFactory.createKatGetgroupsearchResponse0(katrequest.cpq_tns_kat_getgroupsearch.KatGetgroupsearchResponse0)
at katrequest.cpq_tns_kat_getgroupsearch.ObjectFactory
this problem is related to the following location:
at cpq_tns_kat_getgroupsearch.KatGetgroupsearchResponse0
Changed made to solve it are below
I change the respective name to namespace
@XmlAccessorType(XmlAccessType.FIELD) @XmlType(**name** =
"Kat_getgroupsearch", propOrder = {
@XmlAccessorType(XmlAccessType.FIELD) @XmlType(namespace =
"Kat_getgroupsearch", propOrder = {
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(**name** = "Kat_getgroupsearchResponse0", propOrder = {
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(namespace = "Kat_getgroupsearchResponse0", propOrder = {
why?
As written in error log two classes have same name so we should use namespace because XML namespaces are used for providing uniquely named elements and attributes in an XML document.
On my Mac OS X El Capitan, I use homebrew to install gdb:
brew install gdb
Then I follow the instruction here: https://sourceware.org/gdb/wiki/BuildingOnDarwin, in the section 2.1. Method for Mac OS X 10.5 (Leopard) and later.
Why not create an extension method? That's more readable.
public static IEnumerable<FileInfo> GetFilesByExtensions(this DirectoryInfo dir, params string[] extensions)
{
if (extensions == null)
throw new ArgumentNullException("extensions");
IEnumerable<FileInfo> files = Enumerable.Empty<FileInfo>();
foreach(string ext in extensions)
{
files = files.Concat(dir.GetFiles(ext));
}
return files;
}
EDIT: a more efficient version:
public static IEnumerable<FileInfo> GetFilesByExtensions(this DirectoryInfo dir, params string[] extensions)
{
if (extensions == null)
throw new ArgumentNullException("extensions");
IEnumerable<FileInfo> files = dir.EnumerateFiles();
return files.Where(f => extensions.Contains(f.Extension));
}
Usage:
DirectoryInfo dInfo = new DirectoryInfo(@"c:\MyDir");
dInfo.GetFilesByExtensions(".jpg",".exe",".gif");
list multiplication works.
>>> [0] * 10
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
$(function() {
$('#sortable').sortable({
start: function(event, ui) {
var start_pos = ui.item.index();
ui.item.data('start_pos', start_pos);
},
change: function(event, ui) {
var start_pos = ui.item.data('start_pos');
var index = ui.placeholder.index();
if (start_pos < index) {
$('#sortable li:nth-child(' + index + ')').addClass('highlights');
} else {
$('#sortable li:eq(' + (index + 1) + ')').addClass('highlights');
}
},
update: function(event, ui) {
$('#sortable li').removeClass('highlights');
}
});
});
Since we are doing this one to death - you don't have to specify a year:
select * from demo
where somedate between to_date('01/01 00:00:00', 'DD/MM HH24:MI:SS')
and to_date('31/12 23:59:59', 'DD/MM HH24:MI:SS');
However the accepted answer by FerranB makes more sense if you want to specify all date values that fall within the current year.
As far as I've been able to find out, there is no simple way to do it. The easiest way is to not actually convert the class file into an executable, but to wrap an executable launcher around the class file. That is, create an executable file (perhaps an OS-based, executable scripting file) which simply invokes the Java class through the command line.
If you want to actually have a program that does it, you should look into some of the automated installers out there.
Here is a way I've found:
[code]
import java.io.*;
import java.util.jar.*;
class OnlyExt implements FilenameFilter{
String ext;
public OnlyExt(String ext){
this.ext="." + ext;
}
@Override
public boolean accept(File dir,String name){
return name.endsWith(ext);
}
}
public class ExeCreator {
public static int buffer = 10240;
protected void create(File exefile, File[] listFiles) {
try {
byte b[] = new byte[buffer];
FileOutputStream fout = new FileOutputStream(exefile);
JarOutputStream out = new JarOutputStream(fout, new Manifest());
for (int i = 0; i < listFiles.length; i++) {
if (listFiles[i] == null || !listFiles[i].exists()|| listFiles[i].isDirectory())
System.out.println("Adding " + listFiles[i].getName());
JarEntry addFiles = new JarEntry(listFiles[i].getName());
addFiles.setTime(listFiles[i].lastModified());
out.putNextEntry(addFiles);
FileInputStream fin = new FileInputStream(listFiles[i]);
while (true) {
int len = fin.read(b, 0, b.length);
if (len <= 0)
break;
out.write(b, 0, len);
}
fin.close();
}
out.close();
fout.close();
System.out.println("Jar File is created successfully.");
} catch (Exception ex) {}
}
public static void main(String[]args){
ExeCreator exe=new ExeCreator();
FilenameFilter ff = new OnlyExt("class");
File folder = new File("./examples");
File[] files = folder.listFiles(ff);
File file=new File("examples.exe");
exe.create(file, files);
}
}
[/code]`
Use org.apache.commons.lang.StringUtils' split method which can split strings based on the character or string you want to split.
Method signature:
public static String[] split(String str, char separatorChar);
In your case, you want to split a string when there is a "-".
You can simply do as follows:
String str = "004-034556";
String split[] = StringUtils.split(str,"-");
Output:
004
034556
Assume that if -
does not exists in your string, it returns the given string, and you will not get any exception.
Use time.mktime() to convert the time tuple (in localtime) into seconds since the Epoch, then use datetime.fromtimestamp() to get the datetime object.
from datetime import datetime
from time import mktime
dt = datetime.fromtimestamp(mktime(struct))
I had a similar problem with a request to a non-SSL service.
This blog suggested vaguely to try URI encoding the URL that is passed to 'get': http://www.loudthinking.org/2010/02/ruby-eoferror-end-of-file-reached.html
I took a shot at it, based on desperation, and in my limiting testing this seems to have fixed it for me. My new code is:
@http = Net::HTTP.new('domain.com')
@http = @http.start
url = 'http://domain.com/requested_url?blah=blah&etc=1'
req = Net::HTTP::Get.new(URI.encode(url))
req.basic_auth USERNAME, API_KEY
res = @http.request(req)
Note that I use @http.start as I want to maintain the HTTP session over multiple requests. Other than that, you might like to try the most relevant part which is: URI.encode(url) inside the get call
Change this:
<div class=fetch_results>
To this:
<div id="fetch_results">
Then the following should work:
$("#fetch_results input").each(function() {
this.value = "";
})?
Use subprocess.Popen:
import subprocess
process = subprocess.Popen(['ls', '-a'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
out, err = process.communicate()
print(out)
Note that communicate blocks until the process terminates. You could use process.stdout.readline() if you need the output before it terminates. For more information see the documentation.
Syntax errors is not checked easily in external servers, just runtime errors.
What I do? Just like you, I use
ini_set('display_errors', 'On');
error_reporting(E_ALL);
However, before run I check syntax errors in a PHP file using an online PHP syntax checker.
The best, IMHO is PHP Code Checker
I copy all the source code, paste inside the main box and click the Analyze
button.
It is not the most practical method, but the 2 procedures are complementary and it solves the problem completely
I know the question is old, but how the topic is not closed I'll give my help.
The attribute "size" will resolve your problem.
Example:
<select name="courses" multiple="multiple" size="30">
img{display: flex; max-width: 80%; margin: auto;}
This is working for me. You can also use display: table in this case. Moreover, if you don't want to stick to this approach you can use the following:
img{position: relative; left: 50%;}
Here is an end to end solution I implemented for streaming Android microphone audio to a server for playback: Android AudioRecord to Server over UDP Playback Issues
Probably the string would be like this data:image/jpeg;base64,/9j/4QN8RXh...
First split for /
and get the second token.
var StrAfterSlash = Face.Split('/')[1];
Then Split for ;
and get the first token which will be the format. In my case it's jpeg.
var ImageFormat =StrAfterSlash.Split(';')[0];
Then remove the line data:image/jpeg;base64,
for the collected format
CleanFaceData=Face.Replace($"data:image/{ImageFormat };base64,",string.Empty);
You may need to config the CORS at Spring Boot side. Please add below class in your Project.
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
@EnableWebMvc
public class WebConfig implements Filter,WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**");
}
@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) {
HttpServletResponse response = (HttpServletResponse) res;
HttpServletRequest request = (HttpServletRequest) req;
System.out.println("WebConfig; "+request.getRequestURI());
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Methods", "POST, PUT, GET, OPTIONS, DELETE");
response.setHeader("Access-Control-Allow-Headers", "Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With,observe");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Credentials", "true");
response.setHeader("Access-Control-Expose-Headers", "Authorization");
response.addHeader("Access-Control-Expose-Headers", "responseType");
response.addHeader("Access-Control-Expose-Headers", "observe");
System.out.println("Request Method: "+request.getMethod());
if (!(request.getMethod().equalsIgnoreCase("OPTIONS"))) {
try {
chain.doFilter(req, res);
} catch(Exception e) {
e.printStackTrace();
}
} else {
System.out.println("Pre-flight");
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Methods", "POST,GET,DELETE,PUT");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Headers", "Access-Control-Expose-Headers"+"Authorization, content-type," +
"USERID"+"ROLE"+
"access-control-request-headers,access-control-request-method,accept,origin,authorization,x-requested-with,responseType,observe");
response.setStatus(HttpServletResponse.SC_OK);
}
}
}
UPDATE:
To append Token to each request you can create one Interceptor as below.
import { Injectable } from '@angular/core';
import { HttpEvent, HttpHandler, HttpInterceptor, HttpRequest } from '@angular/common/http';
import { Observable } from 'rxjs';
@Injectable()
export class AuthInterceptor implements HttpInterceptor {
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
const token = window.localStorage.getItem('tokenKey'); // you probably want to store it in localStorage or something
if (!token) {
return next.handle(req);
}
const req1 = req.clone({
headers: req.headers.set('Authorization', `${token}`),
});
return next.handle(req1);
}
}
'dir' is an alias for Get-ChildItem which will return back a System.IO.FileInfo class when you're calling it from the filesystem which has VersionInfo as a property. So ...
To get the version info of a single file do this:
PS C:\Windows> (dir .\write.exe).VersionInfo | fl
OriginalFilename : write
FileDescription : Windows Write
ProductName : Microsoft® Windows® Operating System
Comments :
CompanyName : Microsoft Corporation
FileName : C:\Windows\write.exe
FileVersion : 6.1.7600.16385 (win7_rtm.090713-1255)
ProductVersion : 6.1.7600.16385
IsDebug : False
IsPatched : False
IsPreRelease : False
IsPrivateBuild : False
IsSpecialBuild : False
Language : English (United States)
LegalCopyright : © Microsoft Corporation. All rights reserved.
LegalTrademarks :
PrivateBuild :
SpecialBuild :
For multiple files this:
PS C:\Windows> dir *.exe | %{ $_.VersionInfo }
ProductVersion FileVersion FileName
-------------- ----------- --------
6.1.7600.16385 6.1.7600.1638... C:\Windows\bfsvc.exe
6.1.7600.16385 6.1.7600.1638... C:\Windows\explorer.exe
6.1.7600.16385 6.1.7600.1638... C:\Windows\fveupdate.exe
6.1.7600.16385 6.1.7600.1638... C:\Windows\HelpPane.exe
6.1.7600.16385 6.1.7600.1638... C:\Windows\hh.exe
6.1.7600.16385 6.1.7600.1638... C:\Windows\notepad.exe
6.1.7600.16385 6.1.7600.1638... C:\Windows\regedit.exe
6.1.7600.16385 6.1.7600.1638... C:\Windows\splwow64.exe
1,7,0,0 1,7,0,0 C:\Windows\twunk_16.exe
1,7,1,0 1,7,1,0 C:\Windows\twunk_32.exe
6.1.7600.16385 6.1.7600.1638... C:\Windows\winhlp32.exe
6.1.7600.16385 6.1.7600.1638... C:\Windows\write.exe
putting NOW() in quotes won't work as Active Records will put escape the NOW() into a string and tries to push it into the db as a string of "NOW()"... you will need to use
$this->db->set('time', 'NOW()', FALSE);
to set it correctly.
you can always check your sql afterward with
$this->db->last_query();
The reason csv
doesn't support that is because variable-length lines are not really supported on most filesystems. What you should do instead is collect all the data in lists, then call zip()
on them to transpose them after.
>>> l = [('Result_1', 'Result_2', 'Result_3', 'Result_4'), (1, 2, 3, 4), (5, 6, 7, 8)]
>>> zip(*l)
[('Result_1', 1, 5), ('Result_2', 2, 6), ('Result_3', 3, 7), ('Result_4', 4, 8)]
FWIW, it smells like an error (or at least a potential source of future pain) to be using files from /usr/include when cross-compiling.
I was struggling for a while with this as my work computer (with Windows 10) created the default user library on a network drive, which would slow down R and RStudio to an unusable state.
In case this helps someone, this is the easiest way I found, without requiring admin rights:
C:\Users\username\R\win-library\rversion
(for example, something like: C:\Users\janebloggs\R\win-library\3.6
).Renviron
file in your home directory (which might be on the network drive?), and in it, write one single line that defines the R_LIBS_USER
variable to be your custom path:R_LIBS_USER=C:\Users\janebloggs\R\win-library\3.6
(feel free to add comments too, with lines starting with #
)
If a .Renviron
file exists, R will read it at startup and use the variables as they are defined in there, before running the code in the .Rprofile
. You can read about it in help(Startup)
.
Now it should be persistent between sessions!
Hey you can just do one simple thing instead of using model to send parameter use HttpServletRequest object and do this
HttpServletRequest request;
request.setAttribute("param", "value")
now your parametrs will not be shown in your url header hope it works :)
I think the problem is with the spaces. I had my variable at the System variables but it didn't work. When I changed variable Progra~1 = 'Program Files'
everything works fine.
M2_HOME C:\Progra~1\Maven\apache-maven-3.1.1
I also moved my M2_HOME
at the end of the PATH(%M2_HOME%\bin)
I'm not sure if this has any difference.
You could try using MultiMap instead of HashMap
Initialising it will require fewer lines of codes. Adding and retrieving the values will also make it shorter.
Map<String, List<Integer>> map = new HashMap<String, List<Integer>>();
would become:
Multimap<String, Integer> multiMap = ArrayListMultimap.create();
You can check this link: http://java.dzone.com/articles/hashmap-%E2%80%93-single-key-and
Another solution, using jQuery:
$(document).ready(function() {
$("input").keypress(function(e) {
if (e.which == 13) {
$('#submit').click();
return false;
}
return true;
});
});
This should work on the following forms, making "Update" the default action:
<form name="f" method="post" action="/action">
<input type="text" name="text1" />
<input type="submit" name="button2" value="Delete" />
<input type="submit" name="button1" id="submit" value="Update" />
</form>
As well as:
<form name="f" method="post" action="/action">
<input type="text" name="text1" />
<button type="submit" name="button2">Delete</button>
<button type="submit" name="button1" id="submit">Update</button>
</form>
This traps the Enter key only when an input field on the form has focus.
I wrote a module for this: win-node-env.
It creates a NODE_ENV.cmd
that sets the NODE_ENV
environment variable and spawns a child process with the rest of the command and its args.
Just install it (globally), and run your npm script commands, it should automatically make them work.
npm install -g win-node-env
I was able to write a general contains
function for std::list
and std::vector
,
template<typename T>
bool contains( const list<T>& container, const T& elt )
{
return find( container.begin(), container.end(), elt ) != container.end() ;
}
template<typename T>
bool contains( const vector<T>& container, const T& elt )
{
return find( container.begin(), container.end(), elt ) != container.end() ;
}
// use:
if( contains( yourList, itemInList ) ) // then do something
This cleans up the syntax a bit.
But I could not use template template parameter magic to make this work arbitrary stl containers.
// NOT WORKING:
template<template<class> class STLContainer, class T>
bool contains( STLContainer<T> container, T elt )
{
return find( container.begin(), container.end(), elt ) != container.end() ;
}
Any comments about improving the last answer would be nice.
No, unless you want to break compatibility and your compiler supports it.
You need to detect the click from js side, your HTML remaining same. Note: this method is deprecated since v3.5.5 and removed in v4.
$("button").click(function() {
var $btn = $(this);
$btn.button('loading');
// simulating a timeout
setTimeout(function () {
$btn.button('reset');
}, 1000);
});
Also, don't forget to load jQuery and Bootstrap js (based on jQuery) file in your page.
Single liner to create a sudo user with home directory and password.
useradd -m -p $(openssl passwd -1 ${PASSWORD}) -s /bin/bash -G sudo ${USERNAME}
The thing on the right of <-
is a formula
object. It is often used to denote a statistical model, where the thing on the left of the ~
is the response and the things on the right of the ~
are the explanatory variables. So in English you'd say something like "Species depends on Sepal Length, Sepal Width, Petal Length and Petal Width".
The myFormula <-
part of that line stores the formula in an object called myFormula
so you can use it in other parts of your R code.
Other common uses of formula objects in R
The lattice
package uses them to specify the variables to plot.
The ggplot2
package uses them to specify panels for plotting.
The dplyr
package uses them for non-standard evaulation.
//Here is some simple sample code for update
//First declare this
private DatabaseAppHelper dbhelper;
private SQLiteDatabase db;
//initialize the following
dbhelper=new DatabaseAppHelper(this);
db=dbhelper.getWritableDatabase();
//updation code
ContentValues values= new ContentValues();
values.put(DatabaseAppHelper.KEY_PEDNAME, ped_name);
values.put(DatabaseAppHelper.KEY_PEDPHONE, ped_phone);
values.put(DatabaseAppHelper.KEY_PEDLOCATION, ped_location);
values.put(DatabaseAppHelper.KEY_PEDEMAIL, ped_emailid);
db.update(DatabaseAppHelper.TABLE_NAME, values, DatabaseAppHelper.KEY_ID + "=" + ?, null);
//put ur id instead of the 'question mark' is a function in my shared preference.
Add a style with the attribute text-decoration:none;
:
There are a number of different ways of doing this.
Inline style:
<a href="xxx.html" style="text-decoration:none;">goto this link</a>
Inline stylesheet:
<html>
<head>
<style type="text/css">
a {
text-decoration:none;
}
</style>
</head>
<body>
<a href="xxx.html">goto this link</a>
</body>
</html>
External stylesheet:
<html>
<head>
<link rel="Stylesheet" href="stylesheet.css" />
</head>
<body>
<a href="xxx.html">goto this link</a>
</body>
</html>
stylesheet.css:
a {
text-decoration:none;
}
Again with the inverting, you could simply use the following code:
for k,v in pairs(t) do
if not isstring(k) then
-- do something to t[k] when k is not a string
end
I'd suggest looking into fetch
. It is the ES5 equivalent and uses Promises. It is much more readable and easily customizable.
const url = "http://example.com";
fetch(url, {
method : "POST",
body: new FormData(document.getElementById("inputform")),
// -- or --
// body : JSON.stringify({
// user : document.getElementById('user').value,
// ...
// })
}).then(
response => response.text() // .json(), etc.
// same as function(response) {return response.text();}
).then(
html => console.log(html)
);
_x000D_
In Node.js, you'll need to import fetch
using:
const fetch = require("node-fetch");
If you want to use it synchronously (doesn't work in top scope):
const json = await fetch(url, optionalOptions)
.then(response => response.json()) // .text(), etc.
.catch((e) => {});
More Info:
If it is something to do with the data in your database, why not utilize database isolation locking to achieve?
The declaration of x
is inside foo
but the x=5
initialization takes place outside of foo
!
What we need to understand here is that
static int x = 5;
is not the same as
static int x;
x = 5;
Other answers have used the important words here, scope and lifetime, and pointed out that the scope of x
is from the point of its declaration in the function foo
to the end of the function foo
. For example I checked by moving the declaration to the end of the function, and that makes x
undeclared at the x++;
statement.
So the static int x
(scope) part of the statement actually applies where you read it, somewhere INSIDE the function and only from there onwards, not above it inside the function.
However the x = 5
(lifetime) part of the statement is initialization of the variable and happening OUTSIDE of the function as part of the program loading. Variable x
is born with a value of 5
when the program loads.
I read this in one of the comments: "Also, this doesn't address the really confusing part, which is the fact that the initializer is skipped on subsequent calls." It is skipped on all calls. Initialization of the variable is outside of the function code proper.
The value of 5 is theoretically set regardless of whether or not foo is called at all, although a compiler might optimize the function away if you don't call it anywhere. The value of 5 should be in the variable before foo is ever called.
Inside of foo
, the statement static int x = 5;
is unlikely to be generating any code at all.
I found the address x
uses when I put a function foo
into a program of mine, and then (correctly) guessed that the same location would be used if I ran the program again. The partial screen capture below shows that x
has the value 5
even before the first call to foo
.
Another way to rename the database or taking an image of the database is by using the reverse engineering option in the database tab. It will create an ER diagram for the database. Rename the schema there.
After that, go to the File menu and go to export and forward engineer the database.
Then you can import the database.
Intents are useful for passing data around the android framework. You can communicate with your own Activities
and even other processes. Check the developer guide and if you have specific questions (it's a lot to digest up front) come back.
Not sure if it'll work in all circumstances, but in our case, we were trying to override the describe
function in Jest so that we can parse the name and skip the whole describe
block if it met some criteria.
Here's what worked for us:
function describe( name, callback ) {
if ( name.includes( "skip" ) )
return this.describe.skip( name, callback );
else
return this.describe( name, callback );
}
Two things that are critical here:
We don't use an arrow function () =>
.
Arrow functions change the reference to this
and we need that to be the file's this
.
The use of this.describe
and this.describe.skip
instead of just describe
and describe.skip
.
Again, not sure it's of value to anybody but we originally tried to get away with Matthew Crumley's excellent answer but needed to make our method a function and accept params in order to parse them in the conditional.
I have had another issue giving me a 504. It's pretty far out but I'll write it up here for googlers and posterity...
I have a client calling an IIS hosted webservice hosted in another domain (Active Directory). There is not full trust between the client domain and the domain where the web services is hosted. One of the many challenges with the selective trust between these two domains is that Kerberos does not work when calling from one to the other.
In my case I was trying to call a service in another domain where I found out that a SPN was registered. Like this : http/myurl.test.local (just an example)
This forces the call to use Kerberos instead of letting it fall back to NTLM and this gave me a 405 back from the calling server.
After removing the spn and allowing the call to fall back to NTLM, it works fine.
As I said ... this is not something you are likely to run into, as most organizations do not venture into having such a selective trusts between two domains ... But it gives a 504 and caused me a few (more) gray hairs.
If you are using version 0.14.0 or higher of the gradle plugin, you should replace "runProguard" with "minifyEnabled" in your build.gradle files.
runProguard was renamed to minifyEnabled in version 0.14.0. For more info, See Android Build System
<div class="col-md-12">
<p style="color: #28a745; font-weight: bold; font-size:25px; text-align: right " >Total Productos a pagar= {{ getTotal() }} {{ getResult() | currency }}
<button class="btn btn-success" type="submit" [disabled]="!getResult()" (click)="onSubmit()">
Ver Pedido
</button>
</p>
</div>
Implement #to_hash
?
class Gift
def to_hash
hash = {}
instance_variables.each { |var| hash[var.to_s.delete('@')] = instance_variable_get(var) }
hash
end
end
h = Gift.new("Book", 19).to_hash
jQuery Validation Unobtrusive Native is a collection of ASP.Net MVC HTML helper extensions. These make use of jQuery Validation's native support for validation driven by HTML 5 data attributes. Microsoft shipped jquery.validate.unobtrusive.js back with MVC 3. It provided a way to apply data model validations to the client side using a combination of jQuery Validation and HTML 5 data attributes (that's the "unobtrusive" part).
Here's a function to convert js array or object into a php-compatible array to be sent as http get request parameter:
function obj2url(prefix, obj) {
var args=new Array();
if(typeof(obj) == 'object'){
for(var i in obj)
args[args.length]=any2url(prefix+'['+encodeURIComponent(i)+']', obj[i]);
}
else
args[args.length]=prefix+'='+encodeURIComponent(obj);
return args.join('&');
}
prefix is a parameter name.
EDIT:
var a = {
one: two,
three: four
};
alert('/script.php?'+obj2url('a', a));
Will produce
/script.php?a[one]=two&a[three]=four
which will allow you to use $_GET['a'] as an array in script.php. You will need to figure your way into your favorite ajax engine on supplying the url to call script.php from js.
Django provides it. You can use either:
{{ forloop.counter }}
index starts at 1.{{ forloop.counter0 }}
index starts at 0.In template, you can do:
{% for item in item_list %}
{{ forloop.counter }} # starting index 1
{{ forloop.counter0 }} # starting index 0
# do your stuff
{% endfor %}
More info at: for | Built-in template tags and filters | Django documentation
Action Sheet in iOS10 with Swift3.0. Follow this link.
@IBAction func ShowActionSheet(_ sender: UIButton) {
// Create An UIAlertController with Action Sheet
let optionMenuController = UIAlertController(title: nil, message: "Choose Option from Action Sheet", preferredStyle: .actionSheet)
// Create UIAlertAction for UIAlertController
let addAction = UIAlertAction(title: "Add", style: .default, handler: {
(alert: UIAlertAction!) -> Void in
print("File has been Add")
})
let saveAction = UIAlertAction(title: "Edit", style: .default, handler: {
(alert: UIAlertAction!) -> Void in
print("File has been Edit")
})
let deleteAction = UIAlertAction(title: "Delete", style: .default, handler: {
(alert: UIAlertAction!) -> Void in
print("File has been Delete")
})
let cancelAction = UIAlertAction(title: "Cancel", style: .cancel, handler: {
(alert: UIAlertAction!) -> Void in
print("Cancel")
})
// Add UIAlertAction in UIAlertController
optionMenuController.addAction(addAction)
optionMenuController.addAction(saveAction)
optionMenuController.addAction(deleteAction)
optionMenuController.addAction(cancelAction)
// Present UIAlertController with Action Sheet
self.present(optionMenuController, animated: true, completion: nil)
}
This code may help you:
Master frm = new Master();
this.Hide();
frm.ShowDialog();
this.Close();
Wikipedia has this to say about the differences.
In general JScript is an ActiveX scripting language that is probably interpreted as JavaScript by non-IE browsers.
One more option is WinRun4J. This is a configurable java launcher that doubles as a windows service host (both 32 and 64 bit versions). It is open source and there are no restrictions on its use.
(full disclosure: I work on this project).
<style type="text/css">
div.inline { display:inline; }
</style>
<div class="inline">a</div>
<div class="inline">b</div>
<div class="inline">c</div>
I don't think it is very important to find the location of Svcutil.exe. You can use Visual Studio Command prompt to execute directly without its absolute path,
Syntax:
svcutil.exe /language:[vb|cs] /out:[YourClassName].[cs|vb] /config:[YourAppConfigFile.config] [YourServiceAddress]
example:
svcutil.exe /language:cs /out:MyClientClass.cs /config:app.config http://localhost:8370/MyService/
which(df==my.val, arr.ind=TRUE)
You should try slicing the image if possible into a smaller piece which could be repeated. I have sliced that image to a 101x101px image.
CSS:
body{
background-image: url(SO_texture_bg.jpg);
background-repeat:repeat;
}
But in some cases, we wouldn't be able to slice the image to a smaller one. In that case, I would use the whole image. But you could also use the CSS3 methods like what Mustafa Kamal had mentioned.
Wish you good luck.
You'll need the cookie plugin, which provides several additional signatures to the cookie function.
$.cookie('cookie_name', 'cookie_value')
stores a transient cookie (only exists within this session's scope, while $.cookie('cookie_name', 'cookie_value', 'cookie_expiration")
creates a cookie that will last across sessions - see http://www.stilbuero.de/2006/09/17/cookie-plugin-for-jquery/ for more information on the JQuery cookie plugin.
If you want to set cookies that are used for the entire site, you'll need to use JavaScript like this:
document.cookie = "name=value; expires=date; domain=domain; path=path; secure"
Using AddDays(-1)
worked for me until I tried to cross months. When I tried to subtract 2 days from 2017-01-01 the result was 2016-00-30. It could not handle the month change correctly (though the year seemed to be fine).
I used date = Convert.ToDateTime(date).Subtract(TimeSpan.FromDays(2)).ToString("yyyy-mm-dd");
and have no issues.
Invalid login/password could be also related to issues in your DNS server - that's what happened to me and cost me good 5 hours of my life. See if you can specify ip address instead on domain name.
Some long answers here. The principle is very simple though. I submit the opening statement from wikipedia:
"Loose coupling describes a resilient relationship between two or more systems or organizations with some kind of exchange relationship.
Each end of the transaction makes its requirements explicit and makes few assumptions about the other end."
For people with a similar question and find this post (like I did); you can do this even without lastrow if your dataset is formatted as a table.
Range("tablename[columnname]").Formula = "=G3&"",""&L3"
Making it a true one liner. Hope it helps someone!