Install PIL(Python Image Library) :
then:
from PIL import Image
myImage = Image.open("your_image_here");
myImage.show();
DateTime dt1=DateTime.ParseExact(date1,"dd-MM-yyyy",null);
DateTime dt2=DateTime.ParseExact(date2,"dd-MM-yyyy",null);
int cmp=dt1.CompareTo(dt2);
if(cmp>0) {
// date1 is greater means date1 is comes after date2
} else if(cmp<0) {
// date2 is greater means date1 is comes after date1
} else {
// date1 is same as date2
}
Consider:
class Bike(object):
def __init__(self, name, weight, cost):
self.name = name
self.weight = weight
self.cost = cost
bikes = {
# Bike designed for children"
"Trike": Bike("Trike", 20, 100), # <--
# Bike designed for everyone"
"Kruzer": Bike("Kruzer", 50, 165), # <--
}
# Markup of 20% on all sales
margin = .2
# Revenue minus cost after sale
for bike in bikes.values():
profit = bike.cost * margin
print(profit)
Output:
33.0 20.0
The difference is that in your bikes
dictionary, you're initializing the values as lists [...]
. Instead, it looks like the rest of your code wants Bike
instances. So create Bike
instances: Bike(...)
.
As for your error
AttributeError: 'list' object has no attribute 'cost'
this will occur when you try to call .cost
on a list
object. Pretty straightforward, but we can figure out what happened by looking at where you call .cost
-- in this line:
profit = bike.cost * margin
This indicates that at least one bike
(that is, a member of bikes.values()
is a list). If you look at where you defined bikes
you can see that the values were, in fact, lists. So this error makes sense.
But since your class has a cost attribute, it looked like you were trying to use Bike
instances as values, so I made that little change:
[...] -> Bike(...)
and you're all set.
My solution to this problem was to use the $() sub-expression block.
Add-Type -Language CSharp @"
public class Thing{
public string Name;
}
"@;
$x = New-Object Thing
$x.Name = "Bill"
Write-Output "My name is $($x.Name)"
Write-Output "This won't work right: $x.Name"
Gives:
My name is Bill
This won't work right: Thing.Name
As someone mentioned in a comment, you can use which python
if it is supported by CentOS. Another command that could work is whereis python
. In the event neither of these work, you can start the Python interpreter, and it will show you the version, or you could look in /usr/bin
for the Python files (python, python3 etc).
Forget datalist element that good solution for autocomplete function, but not for combobox feature.
css:
.combobox {
display: inline-block;
position: relative;
}
.combobox select {
display: none;
position: absolute;
overflow-y: auto;
}
html:
<div class="combobox">
<input type="number" name="" value="" min="" max="" step=""/><br/>
<select size="3">
<option value="0"> 0</option>
<option value="25"> 25</option>
<option value="40"> 40</option>
</select>
</div>
js (jQuery):
$('.combobox').each(function() {
var
$input = $(this).find('input'),
$select = $(this).find('select');
function hideSelect() {
setTimeout(function() {
if (!$select.is(':focus') && !$input.is(':focus')) {
$select
.hide()
.css('z-index', 1);
}
}, 20);
}
$input
.focusin(function() {
if (!$select.is(':visible')) {
$select
.outerWidth($input.outerWidth())
.show()
.css('z-index', 100);
}
})
.focusout(hideSelect)
.on('input', function() {
$select.val('');
});
$select
.change(function() {
$input.val($select.val());
})
.focusout(hideSelect);
});
This works properly even when you use text input instead of number.
If you put Datetime nullable like DateTime?
in your model it doesn't throw exception.
I solved the problem like this in my case.
You may see this error when you have added a new file to your code and you're now trying to commit the code without staging(adding) it.
To overcome this, you may first add the file by using git add (git add your_file_name.py
) and then committing the changes (git commit -m "Rename Files" -m "Sample script to rename files as you like"
)
Here's a couple of recommendations I can make:
node-amqp: A RabbitMQ client that I have successfully used in combination with Socket.IO to make a real-time multi-player game and chat application amongst other things. Seems reliable enough.
zeromq.node: If you want to go down the non-brokered route this might be worth a look. More work to implement functionality but your more likely to get lower latency and higher throughput.
Adding to @David Roussel answer, classes may be loaded by multiple class loaders.
Lets understand how class loader works.
From javin paul blog in javarevisited :
ClassLoader
follows three principles.
A class is loaded in Java, when its needed. Suppose you have an application specific class called Abc.class, first request of loading this class will come to Application ClassLoader which will delegate to its parent Extension ClassLoader which further delegates to Primordial or Bootstrap class loader
Bootstrap ClassLoader is responsible for loading standard JDK class files from rt.jar and it is parent of all class loaders in Java. Bootstrap class loader don't have any parents.
Extension ClassLoader delegates class loading request to its parent, Bootstrap and if unsuccessful, loads class form jre/lib/ext directory or any other directory pointed by java.ext.dirs system property
System or Application class loader and it is responsible for loading application specific classes from CLASSPATH environment variable, -classpath or -cp command line option, Class-Path attribute of Manifest file inside JAR.
Application class loader is a child of Extension ClassLoader and its implemented by sun.misc.Launcher$AppClassLoader
class.
NOTE: Except Bootstrap class loader, which is implemented in native language mostly in C, all Java class loaders are implemented using java.lang.ClassLoader
.
According to visibility principle, Child ClassLoader can see class loaded by Parent ClassLoader but vice-versa is not true.
According to this principle a class loaded by Parent should not be loaded by Child ClassLoader again
You can also do it in your query, for instance in sql server, google ISNULL
and CASE
built-in functions.
I think you can use loc
if you need update two columns to same value:
df1.loc[df1['stream'] == 2, ['feat','another_feat']] = 'aaaa'
print df1
stream feat another_feat
a 1 some_value some_value
b 2 aaaa aaaa
c 2 aaaa aaaa
d 3 some_value some_value
If you need update separate, one option is use:
df1.loc[df1['stream'] == 2, 'feat'] = 10
print df1
stream feat another_feat
a 1 some_value some_value
b 2 10 some_value
c 2 10 some_value
d 3 some_value some_value
Another common option is use numpy.where
:
df1['feat'] = np.where(df1['stream'] == 2, 10,20)
print df1
stream feat another_feat
a 1 20 some_value
b 2 10 some_value
c 2 10 some_value
d 3 20 some_value
EDIT: If you need divide all columns without stream
where condition is True
, use:
print df1
stream feat another_feat
a 1 4 5
b 2 4 5
c 2 2 9
d 3 1 7
#filter columns all without stream
cols = [col for col in df1.columns if col != 'stream']
print cols
['feat', 'another_feat']
df1.loc[df1['stream'] == 2, cols ] = df1 / 2
print df1
stream feat another_feat
a 1 4.0 5.0
b 2 2.0 2.5
c 2 1.0 4.5
d 3 1.0 7.0
If working with multiple conditions is possible use multiple numpy.where
or numpy.select
:
df0 = pd.DataFrame({'Col':[5,0,-6]})
df0['New Col1'] = np.where((df0['Col'] > 0), 'Increasing',
np.where((df0['Col'] < 0), 'Decreasing', 'No Change'))
df0['New Col2'] = np.select([df0['Col'] > 0, df0['Col'] < 0],
['Increasing', 'Decreasing'],
default='No Change')
print (df0)
Col New Col1 New Col2
0 5 Increasing Increasing
1 0 No Change No Change
2 -6 Decreasing Decreasing
I just experienced a similar message [ mine was "Permission denied (publickey)"] after connecting to a compute engine VM which I just created. After reading this post, I decided to try it again.
That time it worked. So i see 3 possible reasons for it working the second time,
I suspect the last is unlikely :)
1). You can use getter methods from WC_Order
and WC_Abstract_Order
classes on the WC_Order
object instance like:
// Get an instance of the WC_Order Object from the Order ID (if required)
$order = wc_get_order( $order_id );
// Get the Customer ID (User ID)
$customer_id = $order->get_customer_id(); // Or $order->get_user_id();
// Get the WP_User Object instance
$user = $order->get_user();
// Get the WP_User roles and capabilities
$user_roles = $user->roles;
// Get the Customer billing email
$billing_email = $order->get_billing_email();
// Get the Customer billing phone
$billing_phone = $order->get_billing_phone();
// Customer billing information details
$billing_first_name = $order->get_billing_first_name();
$billing_last_name = $order->get_billing_last_name();
$billing_company = $order->get_billing_company();
$billing_address_1 = $order->get_billing_address_1();
$billing_address_2 = $order->get_billing_address_2();
$billing_city = $order->get_billing_city();
$billing_state = $order->get_billing_state();
$billing_postcode = $order->get_billing_postcode();
$billing_country = $order->get_billing_country();
// Customer shipping information details
$shipping_first_name = $order->get_shipping_first_name();
$shipping_last_name = $order->get_shipping_last_name();
$shipping_company = $order->get_shipping_company();
$shipping_address_1 = $order->get_shipping_address_1();
$shipping_address_2 = $order->get_shipping_address_2();
$shipping_city = $order->get_shipping_city();
$shipping_state = $order->get_shipping_state();
$shipping_postcode = $order->get_shipping_postcode();
$shipping_country = $order->get_shipping_country();
2). You can also use the WC_Order
get_data()
method, to get an unprotected data array from Order meta data like:
// Get an instance of the WC_Order Object from the Order ID (if required)
$order = wc_get_order( $order_id );
// Get the Order meta data in an unprotected array
$data = $order->get_data(); // The Order data
$order_id = $data['id'];
$order_parent_id = $data['parent_id'];
// Get the Customer ID (User ID)
$customer_id = $data['customer_id'];
## BILLING INFORMATION:
$billing_email = $data['billing']['email'];
$billing_phone = $order_data['billing']['phone'];
$billing_first_name = $data['billing']['first_name'];
$billing_last_name = $data['billing']['last_name'];
$billing_company = $data['billing']['company'];
$billing_address_1 = $data['billing']['address_1'];
$billing_address_2 = $data['billing']['address_2'];
$billing_city = $data['billing']['city'];
$billing_state = $data['billing']['state'];
$billing_postcode = $data['billing']['postcode'];
$billing_country = $data['billing']['country'];
## SHIPPING INFORMATION:
$shipping_first_name = $data['shipping']['first_name'];
$shipping_last_name = $data['shipping']['last_name'];
$shipping_company = $data['shipping']['company'];
$shipping_address_1 = $data['shipping']['address_1'];
$shipping_address_2 = $data['shipping']['address_2'];
$shipping_city = $data['shipping']['city'];
$shipping_state = $data['shipping']['state'];
$shipping_postcode = $data['shipping']['postcode'];
$shipping_country = $data['shipping']['country'];
Now to get the user account data (from an Order ID):
1). You can use the methods from WC_Customer
Class:
// Get the user ID from an Order ID
$user_id = get_post_meta( $order_id, '_customer_user', true );
// Get an instance of the WC_Customer Object from the user ID
$customer = new WC_Customer( $user_id );
$username = $customer->get_username(); // Get username
$user_email = $customer->get_email(); // Get account email
$first_name = $customer->get_first_name();
$last_name = $customer->get_last_name();
$display_name = $customer->get_display_name();
// Customer billing information details (from account)
$billing_first_name = $customer->get_billing_first_name();
$billing_last_name = $customer->get_billing_last_name();
$billing_company = $customer->get_billing_company();
$billing_address_1 = $customer->get_billing_address_1();
$billing_address_2 = $customer->get_billing_address_2();
$billing_city = $customer->get_billing_city();
$billing_state = $customer->get_billing_state();
$billing_postcode = $customer->get_billing_postcode();
$billing_country = $customer->get_billing_country();
// Customer shipping information details (from account)
$shipping_first_name = $customer->get_shipping_first_name();
$shipping_last_name = $customer->get_shipping_last_name();
$shipping_company = $customer->get_shipping_company();
$shipping_address_1 = $customer->get_shipping_address_1();
$shipping_address_2 = $customer->get_shipping_address_2();
$shipping_city = $customer->get_shipping_city();
$shipping_state = $customer->get_shipping_state();
$shipping_postcode = $customer->get_shipping_postcode();
$shipping_country = $customer->get_shipping_country();
2). The WP_User
object (WordPress):
// Get the user ID from an Order ID
$user_id = get_post_meta( $order_id, '_customer_user', true );
// Get the WP_User instance Object
$user = new WP_User( $user_id );
$username = $user->username; // Get username
$user_email = $user->email; // Get account email
$first_name = $user->first_name;
$last_name = $user->last_name;
$display_name = $user->display_name;
// Customer billing information details (from account)
$billing_first_name = $user->billing_first_name;
$billing_last_name = $user->billing_last_name;
$billing_company = $user->billing_company;
$billing_address_1 = $user->billing_address_1;
$billing_address_2 = $user->billing_address_2;
$billing_city = $user->billing_city;
$billing_state = $user->billing_state;
$billing_postcode = $user->billing_postcode;
$billing_country = $user->billing_country;
// Customer shipping information details (from account)
$shipping_first_name = $user->shipping_first_name;
$shipping_last_name = $user->shipping_last_name;
$shipping_company = $user->shipping_company;
$shipping_address_1 = $user->shipping_address_1;
$shipping_address_2 = $user->shipping_address_2;
$shipping_city = $user->shipping_city;
$shipping_state = $user->shipping_state;
$shipping_postcode = $user->shipping_postcode;
$shipping_country = $user->shipping_country;
Related: How to get WooCommerce order details
if you use more thread ExecutionServices SEQUENTIALLY and want to wait EACH EXECUTIONSERVICE to be finished. The best way is like below;
ExecutorService executer1 = Executors.newFixedThreadPool(THREAD_SIZE1);
for (<loop>) {
executer1.execute(new Runnable() {
@Override
public void run() {
...
}
});
}
executer1.shutdown();
try{
executer1.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS);
ExecutorService executer2 = Executors.newFixedThreadPool(THREAD_SIZE2);
for (true) {
executer2.execute(new Runnable() {
@Override
public void run() {
...
}
});
}
executer2.shutdown();
} catch (Exception e){
...
}
I did this:
<!DOCTYPE HTML>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>AutoDealer</title>
<style>
.container{
width: 860px;
height: 1074px;
margin-right: auto;
margin-left: auto;
border: 1px solid red;
}
.nav{
}
.wrapper{
display: block;
overflow: hidden;
border: 1px solid green;
}
.otherWrapper{
display: block;
overflow: hidden;
border: 1px solid green;
float:left;
}
.left{
width: 399px;
float: left;
background-color: pink;
}
.bottom{
clear: both;
width: 399px;
background-color: yellow;
}
.right{
height:350px;
width: 449px;
overflow: hidden;
background-color: blue;
overflow: hidden;
float:right;
}
</style>
</head>
<body>
<div class="container">
<div class="nav"></div>
<div class="wrapper">
<div class="otherWrapper">
<div class="left">
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum ultricies aliquet tellus sit amet ultrices. Sed faucibus, nunc vitae accumsan laoreet, enim metus varius nulla, ac ultricies felis ante venenatis justo. In hac habitasse platea dictumst. In cursus enim nec urna molestie, id mattis elit mollis. In sed eros eget nibh congue vehicula. Nunc vestibulum enim risus, sit amet suscipit dui auctor et. Morbi orci magna, accumsan at turpis a, scelerisque congue eros. Morbi non mi vel nibh varius blandit sed et urna.</p>
</div>
<div class="bottom">
<p>ucibus eros, sed viverra ex. Vestibulum aliquet accumsan massa, at feugiat ipsum interdum blandit. Morbi et orci hendrerit orci consequat ornare ac et sapien. Nulla vestibulum lectus bibendum, efficitur purus in, venenatis nunc. Nunc tincidunt velit sit amet orci pellentesq</p></div>
</div>
<div class="right">
<p>Quisque vulputate mi id turpis luctus, quis laoreet nisi vestibulum. Morbi facilisis erat vitae augue ornare convallis. Fusce sit amet magna rutrum, hendrerit purus vitae, congue justo. Nam non mi eget purus ultricies lacinia. Fusce ante nisl, efficitur venenatis urna ut, pellentesque egestas nisl. In ut faucibus eros, sed viverra ex. Vestibulum aliquet accumsan massa, at feugiat ipsum interdum blandit. Morbi et orci hendrerit orci consequat ornare ac et sapien. Nulla vestibulum lectus bibendum, efficitur purus in, venenatis nunc. Nunc tincidunt velit sit amet orci pellentesque maximus. Quisque a tempus lectus.</p>
</div>
</div>
</div>
</body>
So basically I just made another div to wrap the pink and yellow, and I make that div have a float:left on it. The blue div has a float:right on it.
I stuck on this issue tried different commands but these will help to solve the problem
php artisan route:clear
php artisan config:clear
php artisan cache:clear
Hope it's helped others too.
I have had a similar problem before where it turned out to be the web brower (chrome in my case) that was the issue.
If you are using chrome, try launching it so:
For Windows:
1) Create a shortcut to Chrome on your desktop. Right-click on the shortcut and choose Properties, then switch to “Shortcut” tab.
2) In the “Target” field, append the following: –args –disable-web-security
For Mac, Open a terminal window and run this from command-line: open ~/Applications/Google\ Chrome.app/ –args –disable-web-security
Above info from:
This is what worked for me perfectly:-
// slide the view from its current position to below itself
public void slideUp(final View view, final View llDomestic){
ObjectAnimator animation = ObjectAnimator.ofFloat(view, "translationY",0f);
animation.setDuration(100);
llDomestic.setVisibility(View.GONE);
animation.start();
}
// slide the view from below itself to the current position
public void slideDown(View view,View llDomestic){
llDomestic.setVisibility(View.VISIBLE);
ObjectAnimator animation = ObjectAnimator.ofFloat(view, "translationY", 0f);
animation.setDuration(100);
animation.start();
}
llDomestic : The view which you want to hide. view: The view which you want to move down or up.
you need to use os.system
module to execute shell command
import os
os.system('command')
if you want to save the output for later use, you need to use subprocess
module
import subprocess
child = subprocess.Popen('command',stdout=subprocess.PIPE,shell=True)
output = child.communicate()[0]
You shouldn't design your application based on specific lifetimes of access tokens. Just assume they are (very) short lived.
However, after a successful completion of the OAuth2 installed application flow, you will get back a refresh token. This refresh token never expires, and you can use it to exchange it for an access token as needed. Save the refresh tokens, and use them to get access tokens on-demand (which should then immediately be used to get access to user data).
EDIT: My comments above notwithstanding, there are two easy ways to get the access token expiration time:
expires_in
)when you exchange your refresh token (using /o/oauth2/token endpoint). More details.There is also an API that returns the remaining lifetime of the access_token:
https://www.googleapis.com/oauth2/v1/tokeninfo?access_token={accessToken}
This will return a json array that will contain an expires_in
parameter, which is the number of seconds left in the lifetime of the token.
To configure Sublime to always use tabs try the adding the following to preferences->settings-user:
{
"tab_size": 4,
"translate_tabs_to_spaces": false
}
More information here: http://www.sublimetext.com/docs/2/indentation.html
I noticed this post was old but it appears top on google and this kind of solution was never offered so I decided to post it anyway.
You can just disable cursor-events and enable them again later via css. It is supported on all major browsers and may prove useful in some situations.
$("#button_id").click(function() {
$("#button_id").css("pointer-events", "none");
//do something
$("#button_id").css("pointer-events", "auto");
}
Based on my experience I would recommend the solution suggested by Adhip Gupta:
$("#my_txtbox").attr( 'readOnly' , 'true' );
The following code won't let the user type new characters, but will allow them to delete characters:
$("#my_txtbox").keypress(function(event) {event.preventDefault();});
Additionally, this will render the form useless to those who have JavaScript disabled:
<input type="text" readonly="true" />
Just use ArrayList.contains(desiredElement). For example, if you're looking for the conta1 account from your example, you could use something like:
if (lista.contains(conta1)) {
System.out.println("Account found");
} else {
System.out.println("Account not found");
}
Edit:
Note that in order for this to work, you will need to properly override the equals() and hashCode() methods. If you are using Eclipse IDE, then you can have these methods generated by first opening the source file for your CurrentAccount
object and the selecting Source > Generate hashCode() and equals()...
This is a highly inefficient way of doing it. You can use the merge
statement and then there's no need for cursors, looping or (if you can do without) PL/SQL.
MERGE INTO studLoad l
USING ( SELECT studId, studName FROM student ) s
ON (l.studId = s.studId)
WHEN MATCHED THEN
UPDATE SET l.studName = s.studName
WHERE l.studName != s.studName
WHEN NOT MATCHED THEN
INSERT (l.studID, l.studName)
VALUES (s.studId, s.studName)
Make sure you commit
, once completed, in order to be able to see this in the database.
To actually answer your question I would do it something like as follows. This has the benefit of doing most of the work in SQL and only updating based on the rowid, a unique address in the table.
It declares a type, which you place the data within in bulk, 10,000 rows at a time. Then processes these rows individually.
However, as I say this will not be as efficient as merge
.
declare
cursor c_data is
select b.rowid as rid, a.studId, a.studName
from student a
left outer join studLoad b
on a.studId = b.studId
and a.studName <> b.studName
;
type t__data is table of c_data%rowtype index by binary_integer;
t_data t__data;
begin
open c_data;
loop
fetch c_data bulk collect into t_data limit 10000;
exit when t_data.count = 0;
for idx in t_data.first .. t_data.last loop
if t_data(idx).rid is null then
insert into studLoad (studId, studName)
values (t_data(idx).studId, t_data(idx).studName);
else
update studLoad
set studName = t_data(idx).studName
where rowid = t_data(idx).rid
;
end if;
end loop;
end loop;
close c_data;
end;
/
A good alternative is this:
find . -type f | xargs chmod -v 644
and for directories:
find . -type d | xargs chmod -v 755
and to be more explicit:
find . -type f | xargs -I{} chmod -v 644 {}
Simple example...
Let's say the child view controller has a UISlider
and we want to pass the value of the slider back to the parent via a delegate.
In the child view controller's header file, declare the delegate type and its methods:
ChildViewController.h
#import <UIKit/UIKit.h>
// 1. Forward declaration of ChildViewControllerDelegate - this just declares
// that a ChildViewControllerDelegate type exists so that we can use it
// later.
@protocol ChildViewControllerDelegate;
// 2. Declaration of the view controller class, as usual
@interface ChildViewController : UIViewController
// Delegate properties should always be weak references
// See http://stackoverflow.com/a/4796131/263871 for the rationale
// (Tip: If you're not using ARC, use `assign` instead of `weak`)
@property (nonatomic, weak) id<ChildViewControllerDelegate> delegate;
// A simple IBAction method that I'll associate with a close button in
// the UI. We'll call the delegate's childViewController:didChooseValue:
// method inside this handler.
- (IBAction)handleCloseButton:(id)sender;
@end
// 3. Definition of the delegate's interface
@protocol ChildViewControllerDelegate <NSObject>
- (void)childViewController:(ChildViewController*)viewController
didChooseValue:(CGFloat)value;
@end
In the child view controller's implementation, call the delegate methods as required.
ChildViewController.m
#import "ChildViewController.h"
@implementation ChildViewController
- (void)handleCloseButton:(id)sender {
// Xcode will complain if we access a weak property more than
// once here, since it could in theory be nilled between accesses
// leading to unpredictable results. So we'll start by taking
// a local, strong reference to the delegate.
id<ChildViewControllerDelegate> strongDelegate = self.delegate;
// Our delegate method is optional, so we should
// check that the delegate implements it
if ([strongDelegate respondsToSelector:@selector(childViewController:didChooseValue:)]) {
[strongDelegate childViewController:self didChooseValue:self.slider.value];
}
}
@end
In the parent view controller's header file, declare that it implements the ChildViewControllerDelegate
protocol.
RootViewController.h
#import <UIKit/UIKit.h>
#import "ChildViewController.h"
@interface RootViewController : UITableViewController <ChildViewControllerDelegate>
@end
In the parent view controller's implementation, implement the delegate methods appropriately.
RootViewController.m
#import "RootViewController.h"
@implementation RootViewController
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
ChildViewController *detailViewController = [[ChildViewController alloc] init];
// Assign self as the delegate for the child view controller
detailViewController.delegate = self;
[self.navigationController pushViewController:detailViewController animated:YES];
}
// Implement the delegate methods for ChildViewControllerDelegate
- (void)childViewController:(ChildViewController *)viewController didChooseValue:(CGFloat)value {
// Do something with value...
// ...then dismiss the child view controller
[self.navigationController popViewControllerAnimated:YES];
}
@end
Hope this helps!
While the status bar is usually 20pt tall, it can be twice that amount in some situations:
Just try it, and you'll see for yourself. Hardcoding the height to 20pt will usually work, until it doesn't.
So I second H2CO3's answer:
statusBarHeight = [[UIApplication sharedApplication] statusBarFrame].size.height;
Another possibility (esp. with multiple Oracle homes)
set ORACLE_SID=$SID
sqlplus /nolog
conn / as sysdba;
Using docker-compose, I accomplished this by creating a service that mounts the volumes that I need and committing the image of the container. Then, in the subsequent service, I rely on the previously committed image, which has all of the data stored at mounted locations. You will then have have to copy these files to their ultimate destination, as host mounted directories do not get committed when running a docker commit
command
You don't have to use docker-compose to accomplish this, but it makes life a bit easier
# docker-compose.yml
version: '3'
services:
stage:
image: alpine
volumes:
- /host/machine/path:/tmp/container/path
command: bash -c "cp -r /tmp/container/path /final/container/path"
setup:
image: stage
# setup.sh
# Start "stage" service
docker-compose up stage
# Commit changes to an image named "stage"
docker commit $(docker-compose ps -q stage) stage
# Start setup service off of stage image
docker-compose up setup
You are trying to load a XIB named DetailViewController
, but no such XIB exists or it's not member of your current target.
Python os module
Specifically for Python 3.6/3.7:
os.name
: The name of the operating system dependent module imported. The following names have currently been registered: 'posix', 'nt', 'java'.
In your case, you want to check for 'nt' as os.name
output:
import os
if os.name == 'nt':
...
There is also a note on os.name
:
See also
sys.platform
has a finer granularity.os.uname()
gives system-dependent version information.The platform module provides detailed checks for the system’s identity.
I was looking for the size in GB, so I just improved the code from Superman above with the following changes:
public double GetTotalHDDSize(string driveName)
{
foreach (DriveInfo drive in DriveInfo.GetDrives())
{
if (drive.IsReady && drive.Name == driveName)
{
return drive.TotalSize / (1024 * 1024 * 1024);
}
}
return -1;
}
Quickie test code for WinForms in VB:
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim Newline As String
Newline = System.Environment.NewLine
TextBox1.Text = "This is a test"
TextBox1.Text = TextBox1.Text & Newline & "This is line 2"
End Sub
I use this short format for github repositories:
yarn add github_user/repository_name#commit_hash
A. If using "target": "es5"
and TypeScript version below 2.0:
typings install es6-promise --save --global --source dt
B. If using "target": "es5"
and TypeScript version 2.0 or higer:
"compilerOptions": {
"lib": ["es5", "es2015.promise"]
}
C. If using "target": "es6"
, there's no need to do anything.
I have been using readlink -f works on linux
so
FULL_PATH=$(readlink -f filename)
DIR=$(dirname $FULL_PATH)
PWD=$(pwd)
cd $DIR
#<do more work>
cd $PWD
You can use this:
Range("MyTable[#Data]").Rows.Count
You have to distinguish between a table which has either one row of data or no data, as the previous code will return "1" for both cases. Use this to test for an empty table:
If WorksheetFunction.CountA(Range("MyTable[#Data]"))
Check out the MSDN Documentation for the Application.DoEvents
method.
I think this may help you...programme is very simple and works fine
import java.util.*;
public class NumberToWord
{
public void pw(int n, String ch)
{
String one[] = {
" ", " one", " two", " three", " four", " five", " six", " seven",
" eight", " Nine", " ten", " eleven", " twelve", " thirteen",
" fourteen", "fifteen", " sixteen", " seventeen", " eighteen",
" nineteen" };
String ten[] = { " ", " ", " twenty", " thirty", " forty", " fifty",
" sixty", "seventy", " eighty", " ninety" };
if (n > 19) {
System.out.print(ten[n / 10] + " " + one[n % 10]);
} else {
System.out.print(one[n]);
}
if (n > 0)
System.out.print(ch);
}
public static void main(String[] args)
{
int n = 0;
Scanner s = new Scanner(System.in);
System.out.print("Enter an integer number: ");
n = s.nextInt();
if (n <= 0)
System.out.print("Enter numbers greater than 0");
else
{
NumberToWord a = new NumberToWord();
System.out.print("After conversion number in words is :");
a.pw((n / 1000000000), " Hundred");
a.pw((n / 10000000) % 100, " crore");
a.pw(((n / 100000) % 100), " lakh");
a.pw(((n / 1000) % 100), " thousand");
a.pw(((n / 100) % 10), " hundred");
a.pw((n % 100), " ");
}
}
}
You were almost there:
You just need to append the li
to ul
and voila!
So just add
ul.appendChild(li);
to the end of your function so the end function will be like this:
function function1() {
var ul = document.getElementById("list");
var li = document.createElement("li");
li.appendChild(document.createTextNode("Element 4"));
ul.appendChild(li);
}
The problem is that static imports from Hamcrest and Mockito have similar names, but return Matchers and real values, respectively.
One work-around is to simply copy the Hamcrest and/or Mockito classes and delete/rename the static functions so they are easier to remember and less show up in the auto complete. That's what I did.
Also, when using mocks, I try to avoid assertThat
in favor other other assertions
and verify
, e.g.
assertEquals(1, 1);
verify(someMock).someMethod(eq(1));
instead of
assertThat(1, equalTo(1));
verify(someMock).someMethod(eq(1));
If you remove the classes from your Favorites in Eclipse, and type out the long name e.g. org.hamcrest.Matchers.equalTo
and do CTRL+SHIFT+M to 'Add Import' then autocomplete will only show you Hamcrest matchers, not any Mockito matchers. And you can do this the other way so long as you don't mix matchers.
If the finality of you code is to get the filtered user, I would invert the for
to evaluate the user
instead of reducing the result array during each iteration.
Here an (untested) example:
function filterUsers (users, filter) {
var result = [];
for (i=0;i<users.length;i++){
for (var prop in filter) {
if (users.hasOwnProperty(prop) && users[i][prop] === filter[prop]) {
result.push(users[i]);
}
}
}
return result;
}
In my opinion, varchar(n)
has it's own advantages. Yes, they all use the same underlying type and all that. But, it should be pointed out that indexes in PostgreSQL has its size limit of 2712 bytes per row.
TL;DR:
If you use text
type without a constraint and have indexes on these columns, it is very possible that you hit this limit for some of your columns and get error when you try to insert data but with using varchar(n)
, you can prevent it.
Some more details: The problem here is that PostgreSQL doesn't give any exceptions when creating indexes for text
type or varchar(n)
where n
is greater than 2712. However, it will give error when a record with compressed size of greater than 2712 is tried to be inserted. It means that you can insert 100.000 character of string which is composed by repetitive characters easily because it will be compressed far below 2712 but you may not be able to insert some string with 4000 characters because the compressed size is greater than 2712 bytes. Using varchar(n)
where n
is not too much greater than 2712, you're safe from these errors.
In python there is no difference between modules and scripts; You can execute both scripts and modules. The file must be on the pythonpath AFAIK because python must be able to find the file in question. If python is executed from a directory, then the directory is automatically added to the pythonpath.
Refer to What is the best way to call a Python script from another Python script? for more information about modules vs scripts
There is also a builtin function execfile(filename) that will do what you want
I stumbled across this for the same reason as anyone else. But the quoted scripts didn't quite work for me. I've made one that is more a hybrid of those I've seen and it now lives here - https://gitlab.com/inorton/git-size-calc
Imao put UIImageView on background is not the best idea . In my case i added on controller view other 2 views . First view has [UIColor clearColor]
on background, second - color which u want to be transparent (grey in my case).Note that order is important.Then for second view set alpha 0.5(alpha >=0 <=1).Added this to lines in prepareForSegue
infoVC.providesPresentationContextTransitionStyle = YES;
infoVC.definesPresentationContext = YES;
And thats all.
There's a solution:
import pyautogui
for i in range(1000):
pyautogui.typewrite("a")
First add the following line to AndroidManifest.xml :
<uses-permission android:name="android.permission.INSTALL_PACKAGES"
tools:ignore="ProtectedPermissions" />
Then use the following code to install apk:
File sdCard = Environment.getExternalStorageDirectory();
String fileStr = sdCard.getAbsolutePath() + "/MyApp";// + "app-release.apk";
File file = new File(fileStr, "TaghvimShamsi.apk");
Intent promptInstall = new Intent(Intent.ACTION_VIEW).setDataAndType(Uri.fromFile(file),
"application/vnd.android.package-archive");
startActivity(promptInstall);
Have you tried os.mkdir?
You might also try this little code snippet:
mypath = ...
if not os.path.isdir(mypath):
os.makedirs(mypath)
makedirs creates multiple levels of directories, if needed.
Color is not data.
The Get.cell technique has flaws.
That does not surprise, since the Get.cell uses an old XML command, i.e. a command from the macro language Excel used before VBA was introduced. At that time, Excel colors were limited to less than 60.
Again: Color is not data.
If you want to color-code your cells, use conditional formatting based on the cell values or based on rules that can be expressed with logical formulas. The logic that leads to conditional formatting can also be used in other places to report on the data, regardless of the color value of the cell.
One of the most interesting features in HTML5
is the ability to store data locally and to allow the application to run offline. There are three different APIs that deal with these features and choosing one depends on what exactly you want to do with the data you're planning to store locally:
For more reference see Introducing the HTML5 storage APIs
And how to use
http://cookbooks.adobe.com/post_Store_data_in_the_HTML5_SQLite_database-19115.html
Here are some methods that have worked for me. You can use them in either the global script namespace (if in the global namespace, you can't reference the function builtin variables)
quick and dirty one liner
: ${1?' You forgot to supply a directory name'}
output:
./my_script: line 279: 1: You forgot to supply a directory name
Fancier - supply function name and usage
${1? ERROR Function: ${FUNCNAME[0]}() Usage: " ${FUNCNAME[0]} directory_name"}
output:
./my_script: line 288: 1: ERROR Function: deleteFolders() Usage: deleteFolders directory_name
Add complex validation logic without cluttering your current function
Add the following line within the function or script that receives the argument.
: ${1?'forgot to supply a directory name'} && validate $1 || die 'Please supply a valid directory'
You can then create a validation function that does something like
validate() {
#validate input and & return 1 if failed, 0 if succeed
if [[ ! -d "$1" ]]; then
return 1
fi
}
and a die function that aborts the script on failure
die() { echo "$*" 1>&2 ; exit 1; }
For additional arguments, just add an additional line, replicating the format.
: ${1?' You forgot to supply the first argument'}
: ${2?' You forgot to supply the second argument'}
I'm using Object.keys(chars).map(...)
to loop in render
// chars = {a:true, b:false, ..., z:false}
render() {
return (
<div>
{chars && Object.keys(chars).map(function(char, idx) {
return <span key={idx}>{char}</span>;
}.bind(this))}
"Some text value"
</div>
);
}
When you create an object of a class using new
keyword in some other class, you are actually doing tight coupling (bad practice) instead you should use loose coupling which is a good practice
---A.java---
package interface_package.loose_coupling;
public class A {
void display(InterfaceClass obji)
{
obji.display();
System.out.println(obji.getVar());
}
}
---B.java---
package interface_package.loose_coupling;
public class B implements InterfaceClass{
private String var="variable Interface";
public String getVar() {
return var;
}
public void setVar(String var) {
this.var = var;
}
@Override
public void display() {
// TODO Auto-generated method stub
System.out.println("Display Method Called");
}
}
---InterfaceClass---
package interface_package.loose_coupling;
public interface InterfaceClass {
void display();
String getVar();
}
---MainClass---
package interface_package.loose_coupling;
public class MainClass {
public static void main(String[] args) {
// TODO Auto-generated method stub
A obja=new A();
B objb=new B();
obja.display(objb); //Calling display of A class with object of B class
}
}
Explanation:
In above example, we have two classes A and B
Class B implements Interface i.e. InterfaceClass.
InterfaceClass defines a Contract for B class as InterfaceClass have abstract methods of B class that can be access by any other class for example A.
In Class A we have display method which can except object of class which implements InterfaceClass (in our case it is B class). And on that object method of class A is calling display() and getVar() of class B
In MainClass we have created object of Class A and B. And calling display method of A by passing object of B class i.e. objb. Display method of A will be called with object of B class.
Now talking about loose coupling. Suppose in future you have to change the name of Class B to ABC then you do not have to change its name in display method of class B, just make the object of new (ABC class) and pass it to the display method in MailClass. You do not have to change anything in Class A
ref: http://p3lang.com/2013/06/loose-coupling-example-using-interface/
Your query looks fine, and your data and query work for me using this JsonPath parser. Also see the example queries on that page for more predicate examples.
The testing tool that you're using seems faulty. Even the examples from the JsonPath site are returning incorrect results:
e.g., given:
{
"store":
{
"book":
[
{ "category": "reference",
"author": "Nigel Rees",
"title": "Sayings of the Century",
"price": 8.95
},
{ "category": "fiction",
"author": "Evelyn Waugh",
"title": "Sword of Honour",
"price": 12.99
},
{ "category": "fiction",
"author": "Herman Melville",
"title": "Moby Dick",
"isbn": "0-553-21311-3",
"price": 8.99
},
{ "category": "fiction",
"author": "J. R. R. Tolkien",
"title": "The Lord of the Rings",
"isbn": "0-395-19395-8",
"price": 22.99
}
],
"bicycle":
{
"color": "red",
"price": 19.95
}
}
}
And the expression: $.store.book[?(@.length-1)].title
, the tool returns a list of all titles.
If you are using Maven, you can run it from the cmd line really easy, cd into the directory with the testng.xml (or whatever yours is called, the xml that has all the classes that will run) and run this cmd:
mvn clean test -DsuiteXmlFile=testng.xml
This page explains it in much more detail: How to run testng.xml from Maven command line
I didn't know it mattered if you were using Maven or not so I didn't include it in my search terms, I thought I would mention it here in case others are in the same situation as I was.
A pure bash solution:
shopt -s nullglob
dirs=( /path/to/directory/*/ )
echo "There are ${#dirs[@]} (non-hidden) directories"
If you also want to count the hidden directories:
shopt -s nullglob dotglob
dirs=( /path/to/directory/*/ )
echo "There are ${#dirs[@]} directories (including hidden ones)"
Note that this will also count links to directories. If you don't want that, it's a bit more difficult with this method.
Using find
:
find /path/to/directory -type d \! -name . -prune -exec printf x \; | wc -c
The trick is to output an x
to stdout each time a directory is found, and then use wc
to count the number of characters. This will count the number of all directories (including hidden ones), excluding links.
The methods presented here are all safe wrt to funny characters that can appear in file names (spaces, newlines, glob characters, etc.).
For the Swift way of doing things, you can try and make use of the tools available in the Swift Standard Library. These should work on any platform that is able to run Swift.
Instead of floor()
, round()
and the rest of the rounding routines you can use rounded(_:)
:
let x = 6.5
// Equivalent to the C 'round' function:
print(x.rounded(.toNearestOrAwayFromZero))
// Prints "7.0"
// Equivalent to the C 'trunc' function:
print(x.rounded(.towardZero))
// Prints "6.0"
// Equivalent to the C 'ceil' function:
print(x.rounded(.up))
// Prints "7.0"
// Equivalent to the C 'floor' function:
print(x.rounded(.down))
// Prints "6.0"
These are currently available on Float
and Double
and it should be easy enough to convert to a CGFloat
for example.
Instead of sqrt()
there's the squareRoot()
method on the FloatingPoint protocol. Again, both Float
and Double
conform to the FloatingPoint
protocol:
let x = 4.0
let y = x.squareRoot()
For the trigonometric functions, the standard library can't help, so you're best off importing Darwin on the Apple platforms or Glibc on Linux. Fingers-crossed they'll be a neater way in the future.
#if os(OSX) || os(iOS)
import Darwin
#elseif os(Linux)
import Glibc
#endif
let x = 1.571
print(sin(x))
// Prints "~1.0"
I see that if you paste csv delimited text in Excel and do a "Text to Columns", it asks you for a "text qualifier". It's defaulted to a double quote so that it treats text within double quotes as literal. I imagine that Excel implements this by going one character at a time, if it encounters a "text qualifier", it keeps going to the next "qualifier". You can probably implement this yourself with a for loop and a boolean to denote if you're inside literal text.
public string[] CsvParser(string csvText)
{
List<string> tokens = new List<string>();
int last = -1;
int current = 0;
bool inText = false;
while(current < csvText.Length)
{
switch(csvText[current])
{
case '"':
inText = !inText; break;
case ',':
if (!inText)
{
tokens.Add(csvText.Substring(last + 1, (current - last)).Trim(' ', ','));
last = current;
}
break;
default:
break;
}
current++;
}
if (last != csvText.Length - 1)
{
tokens.Add(csvText.Substring(last+1).Trim());
}
return tokens.ToArray();
}
the easiest way to delete all files in a folder/remove all files
import os
files = os.listdir(yourFilePath)
for f in files:
os.remove(yourFilePath + f)
To manually generate a Certificate, you need a Certificate Signing Request (CSR) file from your Mac. To create a CSR file, follow the instructions below to create one using Keychain Access.
Create a CSR file. In the Applications folder on your Mac, open the Utilities folder and launch Keychain Access.
Within the Keychain Access drop down menu, select Keychain Access > Certificate Assistant > Request a Certificate from a Certificate Authority.
In the Certificate Information window, enter the following information: In the User Email Address field, enter your email address. In the Common Name field, create a name for your private key (e.g., John Doe Dev Key). The CA Email Address field should be left empty. In the "Request is" group, select the "Saved to disk" option. Click Continue within Keychain Access to complete the CSR generating process.
One interesting thing to point here; the usual way of using OR and AND too will work in this case, but with a small change. Instead of "and" and instead of "or", rather use Ampersand(&) and Pipe Operator(|) and it will work.
When we use 'and':
ar = np.array([3,4,5,14,2,4,3,7])
np.where((ar>3) and (ar<6), 'yo', ar)
Output:
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
When we use Ampersand(&):
ar = np.array([3,4,5,14,2,4,3,7])
np.where((ar>3) & (ar<6), 'yo', ar)
Output:
array(['3', 'yo', 'yo', '14', '2', 'yo', '3', '7'], dtype='<U11')
And this is same in the case when we are trying to apply multiple filters in case of pandas Dataframe. Now the reasoning behind this has to do something with Logical Operators and Bitwise Operators and for more understanding about same, I'd suggest to go through this answer or similar Q/A in stackoverflow.
A user asked, why is there a need for giving (ar>3) and (ar<6) inside the parenthesis. Well here's the thing. Before I start talking about what's happening here, one needs to know about Operator precedence in Python.
Similar to what BODMAS is about, python also gives precedence to what should be performed first. Items inside the parenthesis are performed first and then the bitwise operator comes to work. I'll show below what happens in both the cases when you do use and not use "(", ")".
Case1:
np.where( ar>3 & ar<6, 'yo', ar)
np.where( np.array([3,4,5,14,2,4,3,7])>3 & np.array([3,4,5,14,2,4,3,7])<6, 'yo', ar)
Since there are no brackets here, the bitwise operator(&
) is getting confused here that what are you even asking it to get logical AND of, because in the operator precedence table if you see, &
is given precedence over <
or >
operators. Here's the table from from lowest precedence to highest precedence.
It's not even performing the <
and >
operation and being asked to perform a logical AND operation. So that's why it gives that error.
One can check out the following link to learn more about: operator precedence
Now to Case 2:
If you do use the bracket, you clearly see what happens.
np.where( (ar>3) & (ar<6), 'yo', ar)
np.where( (array([False, True, True, True, False, True, False, True])) & (array([ True, True, True, False, True, True, True, False])), 'yo', ar)
Two arrays of True and False. And you can easily perform logical AND operation on them. Which gives you:
np.where( array([False, True, True, False, False, True, False, False]), 'yo', ar)
And rest you know, np.where, for given cases, wherever True, assigns first value(i.e. here 'yo') and if False, the other(i.e. here, keeping the original).
That's all. I hope I explained the query well.
One reason is that it is easy to create a set from map:
s := map[int]bool{5: true, 2: true}
_, ok := s[6] // check for existence
s[8] = true // add element
delete(s, 2) // remove element
Union
s_union := map[int]bool{}
for k, _ := range s1{
s_union[k] = true
}
for k, _ := range s2{
s_union[k] = true
}
Intersection
s_intersection := map[int]bool{}
for k,_ := range s1 {
if s2[k] {
s_intersection[k] = true
}
}
It is not really that hard to implement all other set operations.
Here's a jquery plugin to do the same: http://s.technabled.com/jquery-foggle
I've answered that here: (WAMP/XAMP) send Mail using SMTP localhost (works not only GMAIL, but for others too).
I found the solution here Whatsapp preview link posted on 2 March 16
And you should see working
There is two kind of code. First meta og:image inside <head>
<meta property="og:image" content="url_image">
Thumbnail schema from schema.org inside <body>
<link itemprop="thumbnailUrl" href="url_image">
<span itemprop="thumbnail" itemscope itemtype="http://schema.org/ImageObject">
<link itemprop="url" href="url_image">
</span>
Hope this help. Thanks.
the easiest way would be
which means you could just do:
new File(filename).text
In Java, according to the JSSE Reference Guide, there is no default for the keystore
, the default for the truststore
is "jssecacerts, if it exists. Otherwise, cacerts".
A few applications use ~/.keystore
as a default keystore, but this is not without problems (mainly because you might not want all the application run by the user to use that trust store).
I'd suggest using application-specific values that you bundle with your application instead, it would tend to be more applicable in general.
Simple:
byte[] data = Convert.FromBase64String(encodedString);
string decodedString = Encoding.UTF8.GetString(data);
For Excel 2016 64-bit on a Windows 10 machine, I have used a hex editor to be able to change the password of a protected xla (have not tested this for any other extensions). Tip: create a backup before you do this.
The steps I took:
I hope this helped some of you!
While the question is just a bit old, this might still help. I'm running into similar issues and using the option below has helped me. Not sure if this is a permanent solution, but it's fixing it for now.
OPTION (OPTIMIZE FOR UNKNOWN)
Then your query will be like this
select * from Table where Col = 'someval' OPTION (OPTIMIZE FOR UNKNOWN)
Just call mkdir C:\VTS
no matter what. It will simply report that the subdirectory already exists.
Edit: As others have noted, this does set the %ERRORLEVEL% if the folder already exists. If your batch (or any processes calling it) doesn't care about the error level, this method works nicely. Since the question made no mention of avoiding the error level, this answer is perfectly valid. It fulfills the needs of creating the folder if it doesn't exist, and it doesn't overwrite the contents of an existing folder. Otherwise follow Martin Schapendonk's answer.
You can use window.close()
to close browser tab.
You can return an array, an object literal, or an object of a type you created that encapsulates the returned values.
Then you can pass in the array, object literal, or custom object into a method to disseminate the values.
Object example:
function myFunction(value1,value2,value3)
{
var returnedObject = {};
returnedObject["value1"] = value1;
returnedObject["value2"] = value2;
return returnedObject;
}
var returnValue = myFunction("1",value2,value3);
if(returnValue.value1 && returnValue.value2)
{
//Do some stuff
}
Array example:
function myFunction(value1,value2,value3)
{
var returnedArray = [];
returnedArray.push(value1);
returnedArray.push(value2);
return returnedArray;
}
var returnValue = myFunction("1",value2,value3);
if(returnValue[0] && returnValue[1])
{
//Do some stuff
}
Custom Object:
function myFunction(value1,value2,value3)
{
var valueHolder = new ValueHolder(value1, value2);
return valueHolder;
}
var returnValue = myFunction("1",value2,value3);
// hypothetical method that you could build to create an easier to read conditional
// (might not apply to your situation)
if(returnValue.valid())
{
//Do some stuff
}
I would avoid the array method because you would have to access the values via indices rather than named object properties.
There is a way to turn the validation back to 2.0 for one page. Just add the below code to your web.config:
<configuration>
<location path="XX/YY">
<system.web>
<httpRuntime requestValidationMode="2.0" />
</system.web>
</location>
...
the rest of your configuration
...
</configuration>
Use http://ipinfo.io , You need to pay them if you make more than 1000 requests per day.
The code below requires the Json.NET package.
public static string GetUserCountryByIp(string ip)
{
IpInfo ipInfo = new IpInfo();
try
{
string info = new WebClient().DownloadString("http://ipinfo.io/" + ip);
ipInfo = JsonConvert.DeserializeObject<IpInfo>(info);
RegionInfo myRI1 = new RegionInfo(ipInfo.Country);
ipInfo.Country = myRI1.EnglishName;
}
catch (Exception)
{
ipInfo.Country = null;
}
return ipInfo.Country;
}
And the IpInfo
Class I used:
public class IpInfo
{
[JsonProperty("ip")]
public string Ip { get; set; }
[JsonProperty("hostname")]
public string Hostname { get; set; }
[JsonProperty("city")]
public string City { get; set; }
[JsonProperty("region")]
public string Region { get; set; }
[JsonProperty("country")]
public string Country { get; set; }
[JsonProperty("loc")]
public string Loc { get; set; }
[JsonProperty("org")]
public string Org { get; set; }
[JsonProperty("postal")]
public string Postal { get; set; }
}
Force a method to get the struct (the constructor way).
From this post:
A good design is to make your type unexported, but provide an exported constructor function like
NewMyType()
in which you can properly initialize your struct / type. Also return an interface type and not a concrete type, and the interface should contain everything others want to do with your value. And your concrete type must implement that interface of course.
This can be done by simply making the type itself unexported. You can export the function NewSomething and even the fields Text and DefaultText, but just don't export the struct type something.
Another way to customize it for you own module is by using a Config struct to set default values (Option 5 in the link). Not a good way though.
Here are some more exotic Python 3 ways to get "hello" TAB "alex" (tested with Python 3.6.10):
"hello\N{TAB}alex"
"hello\N{tab}alex"
"hello\N{TaB}alex"
"hello\N{HT}alex"
"hello\N{CHARACTER TABULATION}alex"
"hello\N{HORIZONTAL TABULATION}alex"
"hello\x09alex"
"hello\u0009alex"
"hello\U00000009alex"
Actually, instead of using an escape sequence, it is possible to insert tab symbol directly into the string literal. Here is the code with a tabulation character to copy and try:
"hello alex"
If the tab in the string above won't be lost anywhere during copying the string then "print(repr(< string from above >)" should print 'hello\talex'.
See respective Python documentation for reference.
There is a command line program to convert any Java project into a SBT/Maven project.
It resolves all jars and tries to figure out the correct version based on SHA checksum, classpath or filename. Then it tries to compile the sources until it finds a working configuration. Custom tasks to execute per dependency configuration can be given too.
UniversalResolver 1.0
Usage: UniversalResolver [options]
-s <srcpath1>,<srcpath2>... | --srcPaths <srcpath1>,<srcpath2>...
required src paths to include
-j <jar1>,<jar2>... | --jars <jar1>,<jar2>...
required jars/jar paths to include
-t /path/To/Dir | --testDirectory /path/To/Dir
required directory where test configurations will be stored
-a <task1>,<task2>... | --sbt-tasks <task1>,<task2>...
SBT Tasks to be executed. i.e. compile
-d /path/To/dependencyFile.json | --dependencyFile /path/To/dependencyFile.json
optional file where the dependency buffer will be stored
-l | --search
load and search dependencies from remote repositories
-g | --generateConfigurations
generate dependency configurations
-c <value> | --findByNameCount <value>
number of dependencies to resolve by class name per jar
You shall pass a this
pointer to tell the function which object to work on because it relies on that as opposed to a static
member function.
This code should do the trick:
var array = ["ab", "abcdefgh", "abcd"];
array.sort(function(a, b){return b.length - a.length});
console.log(JSON.stringify(array, null, '\t'));
Its blank because you are writing to file
. you should write to output
using php://output
instead and also send header information to indicate that it's csv.
Example
header('Content-Type: text/csv');
header('Content-Disposition: attachment; filename="sample.csv"');
$data = array(
'aaa,bbb,ccc,dddd',
'123,456,789',
'"aaa","bbb"'
);
$fp = fopen('php://output', 'wb');
foreach ( $data as $line ) {
$val = explode(",", $line);
fputcsv($fp, $val);
}
fclose($fp);
The naming convention is part of the well-established JavaBeans specification and is supported by the classes in the java.beans package.
Using Scanner
s, you will end up spawning a lot of objects for every line. You will generate a decent amount of garbage for the GC with large files. Also, it is nearly three times slower than using split().
On the other hand, If you split by space (line.split(" ")
), the code will fail if you try to read a file with a different whitespace delimiter. If split()
expects you to write a regular expression, and it does matching anyway, use split("\\s")
instead, that matches a "bit" more whitespace than just a space character.
P.S.: Sorry, I don't have right to comment on already given answers.
Use document.title
.
See this page for a rudimentary tutorial as well.
I was going to bitch and moan about Java, but obviously it isn't THAT bad and that would have amounted to trolling, and besides, I just remembered something far worse:
Magic II.
It just barely qualified as a language. Really, it could be more accurately described as a pre-SQL database system with a data driven programming model. It was based on the astute observation that almost everything you ever do with database tables involves doing something before you start iterating on the data, then iterating on the data, and then maybe doing something after you're done.
"Programming" Magic involves filling in fields in tables that describe those three phases of a program's life. It also had a text mode screen designer that tied in with this whole mess. A trained Magic user could knock out reports and data entry screens at a reasonably fast pace, which made management happy.
The problem for me was that the language had very minimal abstraction facilities. You could define routines that you could call from other routines. That's it. No data structures other than database tables, no in-memory arrays (you could define new tables, though!)
No hash tables, no way to organize variables (which the language did support) in any meaningful way. No lists. Nothing. Of course, no classes or anything resembling an object model, but honestly - I could live without that. And I did.
Worse yet, the "program" had bits and pieces that were hidden away in fields that you had to zoom into to be able to see - certain expressions, etc. So you could never just read a screen of code and know what it did.
This thing took data driven programming to its ultimate, sad apex. It's an obsession, manifested in a programming tool. I was glad to put that miserable piece of junk behind me.
Recently, I met a former co-worker who worked with me while I was using Magic. It's been almost 20 years since I've done that, but she was all too happy to tell me how she was tasked with maintaining one of my projects, and that she declared defeat when she found a recursive procedure in there somewhere. She had never seen anyone implement recursion in Magic. No one ever has. It was uncharted territory. I don't think anyone realized the tool was capable of recursion.
The project had to be rewritten in a hurry, before it caused someone's brain to explode.
Here's a couple of suggestions:
Use date_range
for the index:
import datetime
import pandas as pd
import numpy as np
todays_date = datetime.datetime.now().date()
index = pd.date_range(todays_date-datetime.timedelta(10), periods=10, freq='D')
columns = ['A','B', 'C']
Note: we could create an empty DataFrame (with NaN
s) simply by writing:
df_ = pd.DataFrame(index=index, columns=columns)
df_ = df_.fillna(0) # with 0s rather than NaNs
To do these type of calculations for the data, use a numpy array:
data = np.array([np.arange(10)]*3).T
Hence we can create the DataFrame:
In [10]: df = pd.DataFrame(data, index=index, columns=columns)
In [11]: df
Out[11]:
A B C
2012-11-29 0 0 0
2012-11-30 1 1 1
2012-12-01 2 2 2
2012-12-02 3 3 3
2012-12-03 4 4 4
2012-12-04 5 5 5
2012-12-05 6 6 6
2012-12-06 7 7 7
2012-12-07 8 8 8
2012-12-08 9 9 9
Here nice is used in the meaning of an editor you like or find more user friendly.
The underlying problem is that Git by default uses an editor that is too unintuitive to use for most people: Vim. Now, don't get me wrong, I love Vim, and while you could set some time aside (like a month) to learn Vim and try to understand why some people think Vim is the greatest editor in existence, there is a quicker way of fixing this problem :-)
The fix is not to memorize cryptic commands, like in the accepted answer, but configuring Git to use an editor that you like and understand! It's really as simple as configuring either of these options
core.editor
(per project, or globally)VISUAL
or EDITOR
environment variable (this works for other programs as well)I'll cover the first option for a couple of popular editors, but GitHub has an excellent guide on this for many editors as well.
Straight from its docs, enter this in a terminal:
git config --global core.editor "atom --wait"
Git normally wait for the editor command to finish, but since Atom forks to a background process immediately, this won't work, unless you give it the --wait
option.
For the same reasons as in the Atom case, you need a special flag to signal to the process that it shouldn't fork to the background:
git config --global core.editor "subl -n -w"
Copy Specified Rows from Table to another
// here dttablenew is a new Table and dttableOld is table Which having the data
dttableNew = dttableOld.Clone();
foreach (DataRow drtableOld in dttableOld.Rows)
{
if (/*put some Condition */)
{
dtTableNew.ImportRow(drtableOld);
}
}
You can use the getters of java.time.LocalDateTime
for that.
LocalDateTime now = LocalDateTime.now();
int year = now.getYear();
int month = now.getMonthValue();
int day = now.getDayOfMonth();
int hour = now.getHour();
int minute = now.getMinute();
int second = now.getSecond();
int millis = now.get(ChronoField.MILLI_OF_SECOND); // Note: no direct getter available.
System.out.printf("%d-%02d-%02d %02d:%02d:%02d.%03d", year, month, day, hour, minute, second, millis);
Or, when you're not on Java 8 yet, make use of java.util.Calendar
.
Calendar now = Calendar.getInstance();
int year = now.get(Calendar.YEAR);
int month = now.get(Calendar.MONTH) + 1; // Note: zero based!
int day = now.get(Calendar.DAY_OF_MONTH);
int hour = now.get(Calendar.HOUR_OF_DAY);
int minute = now.get(Calendar.MINUTE);
int second = now.get(Calendar.SECOND);
int millis = now.get(Calendar.MILLISECOND);
System.out.printf("%d-%02d-%02d %02d:%02d:%02d.%03d", year, month, day, hour, minute, second, millis);
Either way, this prints as of now:
2010-04-16 15:15:17.816
To convert an int
to String
, make use of String#valueOf()
.
If your intent is after all to arrange and display them in a human friendly string format, then better use either Java8's java.time.format.DateTimeFormatter
(tutorial here),
LocalDateTime now = LocalDateTime.now();
String format1 = now.format(DateTimeFormatter.ISO_DATE_TIME);
String format2 = now.atZone(ZoneId.of("GMT")).format(DateTimeFormatter.RFC_1123_DATE_TIME);
String format3 = now.format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss", Locale.ENGLISH));
System.out.println(format1);
System.out.println(format2);
System.out.println(format3);
or when you're not on Java 8 yet, use java.text.SimpleDateFormat
:
Date now = new Date(); // java.util.Date, NOT java.sql.Date or java.sql.Timestamp!
String format1 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS", Locale.ENGLISH).format(now);
String format2 = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss Z", Locale.ENGLISH).format(now);
String format3 = new SimpleDateFormat("yyyyMMddHHmmss", Locale.ENGLISH).format(now);
System.out.println(format1);
System.out.println(format2);
System.out.println(format3);
Either way, this yields:
2010-04-16T15:15:17.816 Fri, 16 Apr 2010 15:15:17 GMT 20100416151517
Try:
import simplejson
data = {'apple': 'cat', 'banana':'dog', 'pear':'fish'}
data_json = "{'apple': 'cat', 'banana':'dog', 'pear':'fish'}"
simplejson.loads(data_json) # outputs data
simplejson.dumps(data) # outputs data_joon
NB: Based on Paolo's answer.
Try this code. It will work
Uri smsUri = Uri.parse("tel:123456");
Intent intent = new Intent(Intent.ACTION_VIEW, smsUri);
intent.putExtra("sms_body", "sms text");
intent.setType("vnd.android-dir/mms-sms");
startActivity(intent);
Hope this will help you.
o = open('outfile','w')
print('hello world', file=o)
o.close()
I was looking for something like I did in Perl
my $printname = "outfile"
open($ph, '>', $printname)
or die "Could not open file '$printname' $!";
print $ph "hello world\n";
In .plist file set property:
<key>UIViewControllerBasedStatusBarAppearance</key>
<false/>
It hides the statusBar.
you can measure how long your program works. The following functions help measure the CPU time since the start of the program:
my reference: Algorithms toolbox week 1 course part of data structures and algorithms specialization by University of California San Diego & National Research University Higher School of Economics
so you can add this line of code after your algorithm
cout << (double)clock() / CLOCKS_PER_SEC ;
Expected Output: the output representing the number of clock ticks per second
As other users have pointed out, we use expression()
. I'd like to answer the original question which involves a comma in the subscript:
How can I write v 1,2 with 1,2 as subscripts?
plot(1:10, 11:20 , main=expression(v["1,2"]))
Also, I'd like to add the reference for those looking to find the full expression
syntax in R
plotting: For more information see the ?plotmath
help page. Running demo(plotmath)
will showcase many expressions and relevant syntax.
Remember to use *
to join different types of text within an expression.
Here is some of the sample output from demo(plotmath)
:
posible you already solved your problem, any way i hope this help you.
all files downloaded starts with empty line, in my case where four empty
lines, and it make a problem. No matter if you work with readfile();
or
save('php://output');
, This can be fixed with adding ob_start();
at the
beginning of the script and ob_end_clean();
just before the readfile()
; or
save('php://output');
.
Please use this. You will get table names along with schema names:
SELECT SYSSCHEMA.NAME, SYSTABLE.NAME
FROM SYS.tables SYSTABLE
INNER JOIN SYS.SCHEMAS SYSSCHEMA
ON SYSTABLE.SCHEMA_ID = SYSSCHEMA.SCHEMA_ID
Simply put:
SELECT *
FROM TABLE_NAME
WHERE
dob > '1/21/2012'
Where 1/21/2012 is the date and you want all data, including that date.
SELECT *
FROM TABLE_NAME
WHERE
dob BETWEEN '1/21/2012' AND '2/22/2012'
Use a between if you're selecting time between two dates
move
and del
ARE certainly the equivalents, but from a functionality standpoint they are woefully NOT equivalent. For example, you can't move both files AND folders (in a wildcard scenario) with the move
command. And the same thing applies with del
.
The preferred solution in my view is to use Win32 ports of the Linux tools, the best collection of which I have found being here.
mv
and rm
are in the CoreUtils package and they work wonderfully!
You use:
yourcommand > /dev/null 2>&1
If it should run in the Background add an &
yourcommand > /dev/null 2>&1 &
>/dev/null 2>&1
means redirect stdout
to /dev/null
AND stderr
to the place where stdout
points at that time
If you want stderr
to occur on console and only stdout
going to /dev/null
you can use:
yourcommand 2>&1 > /dev/null
In this case stderr
is redirected to stdout
(e.g. your console) and afterwards the original stdout
is redirected to /dev/null
If the program should not terminate you can use:
nohup yourcommand &
Without any parameter all output lands in nohup.out
I know that this is super-duper old, but on the off chance that someone comes looking for this, as of Visual Basic 14, Vb supports interpolation. Sooooo cool!
Example:
SQLQueryString = $"
Insert into Employee values(
{txtEmployeeNo},
{txtContractsStartDate},
{txtSeatNo},
{txtFloor},
{txtLeaves}
)"
It works. Documentation Here
Edit: After writing this, I realized that the OP was talking about VBA. This will not work in VBA!!! However, I will leave this up here, because as someone new to VB, I stumbled upon this question looking for a solution to just this problem in VB.net. If this helps someone else, great.
The problem is that you have a date formatted like this:
Thu Jun 18 20:56:02 EDT 2009
But are using a SimpleDateFormat
that is:
yyyy-MM-dd
The two formats don't agree. You need to construct a SimpleDateFormat
that matches the layout of the string you're trying to parse into a Date. Lining things up to make it easy to see, you want a SimpleDateFormat
like this:
EEE MMM dd HH:mm:ss zzz yyyy
Thu Jun 18 20:56:02 EDT 2009
Check the JavaDoc page I linked to and see how the characters are used.
The -Wl,xxx
option for gcc passes a comma-separated list of tokens as a space-separated list of arguments to the linker. So
gcc -Wl,aaa,bbb,ccc
eventually becomes a linker call
ld aaa bbb ccc
In your case, you want to say "ld -rpath .
", so you pass this to gcc as -Wl,-rpath,.
Alternatively, you can specify repeat instances of -Wl
:
gcc -Wl,aaa -Wl,bbb -Wl,ccc
Note that there is no comma between aaa
and the second -Wl
.
Or, in your case, -Wl,-rpath -Wl,.
.
I used some of the answers given here but just a heads up that
Get-Content -Path Yourfile.log -Tail 30 -Wait
will chew up memory after awhile. A colleague left such a "tail" up over the last day and it went up to 800 MB. I don't know if Unix tail behaves the same way (but I doubt it). So it's fine to use for short term applications, but be careful with it.
There are two approaches: shmget
and mmap
. I'll talk about mmap
, since it's more modern and flexible, but you can take a look at man shmget
(or this tutorial) if you'd rather use the old-style tools.
The mmap()
function can be used to allocate memory buffers with highly customizable parameters to control access and permissions, and to back them with file-system storage if necessary.
The following function creates an in-memory buffer that a process can share with its children:
#include <stdio.h>
#include <stdlib.h>
#include <sys/mman.h>
void* create_shared_memory(size_t size) {
// Our memory buffer will be readable and writable:
int protection = PROT_READ | PROT_WRITE;
// The buffer will be shared (meaning other processes can access it), but
// anonymous (meaning third-party processes cannot obtain an address for it),
// so only this process and its children will be able to use it:
int visibility = MAP_SHARED | MAP_ANONYMOUS;
// The remaining parameters to `mmap()` are not important for this use case,
// but the manpage for `mmap` explains their purpose.
return mmap(NULL, size, protection, visibility, -1, 0);
}
The following is an example program that uses the function defined above to allocate a buffer. The parent process will write a message, fork, and then wait for its child to modify the buffer. Both processes can read and write the shared memory.
#include <string.h>
#include <unistd.h>
int main() {
char parent_message[] = "hello"; // parent process will write this message
char child_message[] = "goodbye"; // child process will then write this one
void* shmem = create_shared_memory(128);
memcpy(shmem, parent_message, sizeof(parent_message));
int pid = fork();
if (pid == 0) {
printf("Child read: %s\n", shmem);
memcpy(shmem, child_message, sizeof(child_message));
printf("Child wrote: %s\n", shmem);
} else {
printf("Parent read: %s\n", shmem);
sleep(1);
printf("After 1s, parent read: %s\n", shmem);
}
}
You can add .a file in the linking command:
gcc yourfiles /path/to/library/libLIBRARY.a
But this is not talking with gcc driver, but with ld
linker as options like -Wl,anything
are.
When you tell gcc or ld -Ldir -lLIBRARY
, linker will check both static and dynamic versions of library (you can see a process with -Wl,--verbose
). To change order of library types checked you can use -Wl,-Bstatic
and -Wl,-Bdynamic
. Here is a man page of gnu LD: http://linux.die.net/man/1/ld
To link your program with lib1, lib3 dynamically and lib2 statically, use such gcc call:
gcc program.o -llib1 -Wl,-Bstatic -llib2 -Wl,-Bdynamic -llib3
Assuming that default setting of ld is to use dynamic libraries (it is on Linux).
On heroku server (readonly filesystem), If you want runtime compilation of css (its not recommended but you can do it), make sure you have done settings like below -
# inside config/application.rb
config.assets.enabled = true
config.assets.prefix = Rails.root.join('tmp/assets').to_s
# If you are using sass then keep gem outside of asset group
gem 'sass-rails', '3.1.4'
# inside config/environments/production.rb
config.assets.compile = true
An NSMutableArray
is a subclass of NSArray
so you won't always need to convert but if you want to make sure that the array can't be modified you can create a NSArray
either of these ways depending on whether you want it autoreleased or not:
/* Not autoreleased */
NSArray *array = [[NSArray alloc] initWithArray:mutableArray];
/* Autoreleased array */
NSArray *array = [NSArray arrayWithArray:mutableArray];
EDIT: The solution provided by Georg Schölly is a better way of doing it and a lot cleaner, especially now that we have ARC and don't even have to call autorelease.
Here is My Code
protected void btnExcel_Click(object sender, ImageClickEventArgs e)
{
if (gvDetail.Rows.Count > 0)
{
System.IO.StringWriter stringWrite1 = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter htmlWrite1 = new HtmlTextWriter(stringWrite1);
gvDetail.RenderControl(htmlWrite1);
gvDetail.AllowPaging = false;
Search();
sh.ExportToExcel(gvDetail, "Report");
}
}
public override void VerifyRenderingInServerForm(Control control)
{
/* Confirms that an HtmlForm control is rendered for the specified ASP.NET
server control at run time. */
}
In the following example you have an PHP array, then firstly create a JavaScript array by a PHP array:
<script type="javascript">
day = new Array(<?php echo implode(',', $day); ?>);
week = new Array(<?php echo implode(',',$week); ?>);
month = new Array(<?php echo implode(',',$month); ?>);
<!-- Then pass it to the JavaScript function: -->
drawChart(<?php echo count($day); ?>, day, week, month);
</script>
By using this query you get the answer:
select Column_name
from Information_schema.columns
where Table_name like 'table name'
For Android SDK, setEndpoint solves the problem, although it's been deprecated.
CognitoCachingCredentialsProvider credentialsProvider = new CognitoCachingCredentialsProvider(
context, "identityPoolId", Regions.US_EAST_1);
AmazonS3 s3 = new AmazonS3Client(credentialsProvider);
s3.setEndpoint("s3.us-east-2.amazonaws.com");
List is an interface so you can't instanciate it. Use any of its implementatons instead e.g.
List<Object> object = new List<Object>();
About List : you can use any object as a generic param for it instance:
List<?> list = new ArrayList<String>();
or
List<?> list = new ArrayList<Integer>();
While using List<Object>
this declaration is invalid because it will be type missmatch.
Change
dateTime.setText(app.getTotalDl());
To
dateTime.setText(String.valueOf(app.getTotalDl()));
There are different versions of setText
- one takes a String and one takes an int resource id. If you pass it an integer it will try to look for the corresponding string resource id - which it can't find, which is your error.
I guess app.getTotalDl()
returns an int. You need to specifically tell setText
to set it to the String value of this int.
If you want to remove an item, the following will be a bit more efficient.
std::vector<int> v;
auto it = std::find(v.begin(), v.end(), 5);
if(it != v.end())
v.erase(it);
or you may avoid overhead of moving the items if the order does not matter to you:
std::vector<int> v;
auto it = std::find(v.begin(), v.end(), 5);
if (it != v.end()) {
using std::swap;
// swap the one to be removed with the last element
// and remove the item at the end of the container
// to prevent moving all items after '5' by one
swap(*it, v.back());
v.pop_back();
}
After changing the target to matching version (as explained by Ben), if it still shows errors then just run "Clean" on the project to clear resource errors.
You may try creating a new project in netbeans and then copy and and paste the files into it. I usually experience this problem when the project wasn't created in netbeans.
I have found that a button works, but that you'll want to add style="height: 100%;"
to the button so that it will show more than the first line on Safari for iPhone iOS 5.1.1
std::less<>
when using custom classes with operator<
If you are dealing with a set of your custom class that has operator<
defined, then you can just use std::less<>
.
As mentioned at http://en.cppreference.com/w/cpp/container/set/find C++14 has added two new find
APIs:
template< class K > iterator find( const K& x );
template< class K > const_iterator find( const K& x ) const;
which allow you to do:
main.cpp
#include <cassert>
#include <set>
class Point {
public:
// Note that there is _no_ conversion constructor,
// everything is done at the template level without
// intermediate object creation.
//Point(int x) : x(x) {}
Point(int x, int y) : x(x), y(y) {}
int x;
int y;
};
bool operator<(const Point& c, int x) { return c.x < x; }
bool operator<(int x, const Point& c) { return x < c.x; }
bool operator<(const Point& c, const Point& d) {
return c.x < d;
}
int main() {
std::set<Point, std::less<>> s;
s.insert(Point(1, -1));
s.insert(Point(2, -2));
s.insert(Point(0, 0));
s.insert(Point(3, -3));
assert(s.find(0)->y == 0);
assert(s.find(1)->y == -1);
assert(s.find(2)->y == -2);
assert(s.find(3)->y == -3);
// Ignore 1234, find 1.
assert(s.find(Point(1, 1234))->y == -1);
}
Compile and run:
g++ -std=c++14 -Wall -Wextra -pedantic -o main.out main.cpp
./main.out
More info about std::less<>
can be found at: What are transparent comparators?
Tested on Ubuntu 16.10, g++
6.2.0.
Step 1.
vi ~/.bashrc
Step 2. Append this line on the last:
export CLASSPATH=$CLASSPATH:/home/abc/lib/*; (Assuming the jars are stored in /home/abc/lib)
Step 3.
source ~/.bashrc
After these steps direct complile and run your programs(e.g. javac xyz.java)
You will have to add it through code. Try this:
// 1.create UIView programmetically
var myView = UIView(frame: CGRectMake(100, 100, 100, 100))
// 2.add myView to UIView hierarchy
self.view.addSubview(myView)
// 3. add action to myView
let gesture = UITapGestureRecognizer(target: self, action: "someAction:")
// or for swift 2 +
let gestureSwift2AndHigher = UITapGestureRecognizer(target: self, action: #selector (self.someAction (_:)))
self.myView.addGestureRecognizer(gesture)
func someAction(sender:UITapGestureRecognizer){
// do other task
}
// or for Swift 3
func someAction(_ sender:UITapGestureRecognizer){
// do other task
}
// or for Swift 4
@objc func someAction(_ sender:UITapGestureRecognizer){
// do other task
}
// update for Swift UI
Text("Tap me!")
.tapAction {
print("Tapped!")
}
It sounds like that if you request faq.html
the webserver signals your browser that the file is in UTF-8 encoding.
Check that with your browser which encoding is announced and used, please see the documentation of your browser how to do that. Every browser has this, most often accessible via the menu (to specify your preference which website's encoding should be used) and to see what the server returned, you often find this in page properties.
Then it sounds like that if you request faq.php
the webserver singals your browser that the file is in some other encoding. Probably no charset/encoding is given as per default PHP configuration setting. As it's a PHP file you can most often solve this by changing the PHP configuration default_charset
Docs directive:
default_charset = "UTF-8"
Locate your php.ini on the host and edit it accordingly.
If you don't have the php.ini available, you can change this by code as well by using the ini_set
Docs function:
ini_set('default_charset', 'UTF-8');
Take care that you change this very early in your script because PHP needs to be able to send out headers to have this working, and headers can't be set any longer if they have already been send.
Manually sending the Content-Type
header-line does work, too:
header('Content-Type: text/html; charset=UTF-8');
Additionally it's good practice that all the HTML pages you output have this header as well in their HTML <head>
section:
<html>
<head>
...
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
...
Hope this is helpful.
public class PermutationGenerator
{
private LinkedList<List<int>> _permutationsList;
public void FindPermutations(List<int> list, int permutationLength)
{
_permutationsList = new LinkedList<List<int>>();
foreach(var value in list)
{
CreatePermutations(value, permutationLength);
}
}
private void CreatePermutations(int value, int permutationLength)
{
var node = _permutationsList.First;
var last = _permutationsList.Last;
while (node != null)
{
if (node.Value.Count < permutationLength)
{
GeneratePermutations(node.Value, value, permutationLength);
}
if (node == last)
{
break;
}
node = node.Next;
}
List<int> permutation = new List<int>();
permutation.Add(value);
_permutationsList.AddLast(permutation);
}
private void GeneratePermutations(List<int> permutation, int value, int permutationLength)
{
if (permutation.Count < permutationLength)
{
List<int> copyOfInitialPermutation = new List<int>(permutation);
copyOfInitialPermutation.Add(value);
_permutationsList.AddLast(copyOfInitialPermutation);
List<int> copyOfPermutation = new List<int>();
copyOfPermutation.AddRange(copyOfInitialPermutation);
int lastIndex = copyOfInitialPermutation.Count - 1;
for (int i = lastIndex;i > 0;i--)
{
int temp = copyOfPermutation[i - 1];
copyOfPermutation[i - 1] = copyOfPermutation[i];
copyOfPermutation[i] = temp;
List<int> perm = new List<int>();
perm.AddRange(copyOfPermutation);
_permutationsList.AddLast(perm);
}
}
}
public void PrintPermutations(int permutationLength)
{
int count = _permutationsList.Where(perm => perm.Count() == permutationLength).Count();
Console.WriteLine("The number of permutations is " + count);
}
}
I have found one solution to this, not saying it's the best one, but it feels clean to me and doesn't require any major changes to my code. My code looked similar to yours until I realized it didn't work.
My Base Class
public class MyBaseClass
{
public string BaseProperty1 { get; set; }
public string BaseProperty2 { get; set; }
public string BaseProperty3 { get; set; }
public string BaseProperty4 { get; set; }
public string BaseProperty5 { get; set; }
}
My Derived Class
public class MyDerivedClass : MyBaseClass
{
public string DerivedProperty1 { get; set; }
public string DerivedProperty2 { get; set; }
public string DerivedProperty3 { get; set; }
}
Previous method to get a populated base class
public MyBaseClass GetPopulatedBaseClass()
{
var myBaseClass = new MyBaseClass();
myBaseClass.BaseProperty1 = "Something"
myBaseClass.BaseProperty2 = "Something else"
myBaseClass.BaseProperty3 = "Something more"
//etc...
return myBaseClass;
}
Before I was trying this, which gave me a unable to cast error
public MyDerivedClass GetPopulatedDerivedClass()
{
var newDerivedClass = (MyDerivedClass)GetPopulatedBaseClass();
newDerivedClass.UniqueProperty1 = "Some One";
newDerivedClass.UniqueProperty2 = "Some Thing";
newDerivedClass.UniqueProperty3 = "Some Thing Else";
return newDerivedClass;
}
I changed my code as follows bellow and it seems to work and makes more sense now:
Old
public MyBaseClass GetPopulatedBaseClass()
{
var myBaseClass = new MyBaseClass();
myBaseClass.BaseProperty1 = "Something"
myBaseClass.BaseProperty2 = "Something else"
myBaseClass.BaseProperty3 = "Something more"
//etc...
return myBaseClass;
}
New
public void FillBaseClass(MyBaseClass myBaseClass)
{
myBaseClass.BaseProperty1 = "Something"
myBaseClass.BaseProperty2 = "Something else"
myBaseClass.BaseProperty3 = "Something more"
//etc...
}
Old
public MyDerivedClass GetPopulatedDerivedClass()
{
var newDerivedClass = (MyDerivedClass)GetPopulatedBaseClass();
newDerivedClass.UniqueProperty1 = "Some One";
newDerivedClass.UniqueProperty2 = "Some Thing";
newDerivedClass.UniqueProperty3 = "Some Thing Else";
return newDerivedClass;
}
New
public MyDerivedClass GetPopulatedDerivedClass()
{
var newDerivedClass = new MyDerivedClass();
FillBaseClass(newDerivedClass);
newDerivedClass.UniqueProperty1 = "Some One";
newDerivedClass.UniqueProperty2 = "Some Thing";
newDerivedClass.UniqueProperty3 = "Some Thing Else";
return newDerivedClass;
}
Thomas, I think your wrapper code, or just the condition itself, is the cleanest way to do what you want to do in java, which is convert "1" to the Boolean True value. Actually, comparing to "0" and taking the inverse would match the C behavior of treating 0 as false and everything else as true.
Boolean intStringToBoolean(numericBooleanValueString) {
return !"0".equals(numericBooleanValueString);
}
In recent browsers you can use:
Object.keys(obj.Data).length
See MDN
For older browsers, use the for-in
loop in Michael Geary's answer.
<div id="cblist">
<input type="checkbox" value="first checkbox" id="cb1" /> <label for="cb1">first checkbox</label>
</div>
<input type="text" id="txtName" />
<input type="button" value="ok" id="btnSave" />
<script type="text/javascript">
$(document).ready(function() {
$('#btnSave').click(function() {
addCheckbox($('#txtName').val());
});
});
function addCheckbox(name) {
var container = $('#cblist');
var inputs = container.find('input');
var id = inputs.length+1;
$('<input />', { type: 'checkbox', id: 'cb'+id, value: name }).appendTo(container);
$('<label />', { 'for': 'cb'+id, text: name }).appendTo(container);
}
</script>
You can use java.util.Arrays.binarySearch to find an element in an array or to check for its existence:
import java.util.Arrays;
...
char[] array = new char[] {'a', 'x', 'm'};
Arrays.sort(array);
if (Arrays.binarySearch(array, 'm') >= 0) {
System.out.println("Yes, m is there");
}
Be aware that for binarySearch to work correctly, the array needs to be sorted. Hence the call to Arrays.sort() in the example. If your data is already sorted, you don't need to do that. Thus, this isn't strictly a one-liner if you need to sort your array first. Unfortunately, Arrays.sort() does not return a reference to the array - thus it is not possible to combine sort and binarySearch (i.e. Arrays.binarySearch(Arrays.sort(myArray), key)) does not work).
If you can afford the extra allocation, using Arrays.asList() seems cleaner.
It might be an easiest way-
String recipientList = mEditTextTo.getText().toString();
String[] recipients = recipientList.split(",");
String subject = mEditTextSubject.getText().toString();
String message = mEditTextMessage.getText().toString();
Intent intent = new Intent(Intent.ACTION_SEND);
intent.putExtra(Intent.EXTRA_EMAIL, recipients);
intent.putExtra(Intent.EXTRA_SUBJECT, subject);
intent.putExtra(Intent.EXTRA_TEXT, message);
intent.setType("message/rfc822");
startActivity(Intent.createChooser(intent, "Choose an email client"));
It is a little tricky. First you can use keytool to put the private key into PKCS12 format, which is more portable/compatible than Java's various keystore formats. Here is an example taking a private key with alias 'mykey' in a Java keystore and copying it into a PKCS12 file named myp12file.p12
.
[note that on most screens this command extends beyond the right side of the box: you need to scroll right to see it all]
keytool -v -importkeystore -srckeystore .keystore -srcalias mykey -destkeystore myp12file.p12 -deststoretype PKCS12
Enter destination keystore password:
Re-enter new password:
Enter source keystore password:
[Storing myp12file.p12]
Now the file myp12file.p12
contains the private key in PKCS12 format which may be used directly by many software packages or further processed using the openssl pkcs12
command. For example,
openssl pkcs12 -in myp12file.p12 -nocerts -nodes
Enter Import Password:
MAC verified OK
Bag Attributes
friendlyName: mykey
localKeyID: 54 69 6D 65 20 31 32 37 31 32 37 38 35 37 36 32 35 37
Key Attributes: <No Attributes>
-----BEGIN RSA PRIVATE KEY-----
MIIC...
.
.
.
-----END RSA PRIVATE KEY-----
Prints out the private key unencrypted.
Note that this is a private key, and you are responsible for appreciating the security implications of removing it from your Java keystore and moving it around.
Adding to what @sateesh said, when you just want to mock a void method in order to prevent the test from calling it, you could use a Spy
this way:
World world = new World();
World spy = Mockito.spy(world);
Mockito.doNothing().when(spy).methodToMock();
When you want to run your test, make sure you call the method in test on the spy
object and not on the world
object. For example:
assertEquals(0, spy.methodToTestThatShouldReturnZero());
Give them a default value:
double lateFee=0.0;
double monthlyCharge = 0.0;
double annualRate = 0.0;
Basically, all possible paths don't initialize these variables.
Greg Hewgill's answer is great but if you need more nodes per level you can use a list|dictionary to create them: And then use method to access them either by name or order (like id)
class node(object):
def __init__(self):
self.name=None
self.node=[]
self.otherInfo = None
self.prev=None
def nex(self,child):
"Gets a node by number"
return self.node[child]
def prev(self):
return self.prev
def goto(self,data):
"Gets the node by name"
for child in range(0,len(self.node)):
if(self.node[child].name==data):
return self.node[child]
def add(self):
node1=node()
self.node.append(node1)
node1.prev=self
return node1
Now just create a root and build it up: ex:
tree=node() #create a node
tree.name="root" #name it root
tree.otherInfo="blue" #or what ever
tree=tree.add() #add a node to the root
tree.name="node1" #name it
root
/
child1
tree=tree.add()
tree.name="grandchild1"
root
/
child1
/
grandchild1
tree=tree.prev()
tree=tree.add()
tree.name="gchild2"
root
/
child1
/ \
grandchild1 gchild2
tree=tree.prev()
tree=tree.prev()
tree=tree.add()
tree=tree.name="child2"
root
/ \
child1 child2
/ \
grandchild1 gchild2
tree=tree.prev()
tree=tree.goto("child1") or tree=tree.nex(0)
tree.name="changed"
root
/ \
changed child2
/ \
grandchild1 gchild2
That should be enough for you to start figuring out how to make this work
Using EnumerateFiles to get files in nested directories. Use AllDirectories to recurse throught directories.
using System;
using System.IO;
class Program
{
static void Main()
{
// Call EnumerateFiles in a foreach-loop.
foreach (string file in Directory.EnumerateFiles(@"c:\files",
"*.xml",
SearchOption.AllDirectories))
{
// Display file path.
Console.WriteLine(file);
}
}
}
Per the docs, replace
returns the new string - it does not modify the string you pass it.
var tt="88,9827";
tt = tt.replace(/,/g, '.');
^^^^
alert(tt);
if you want to open incognito window, put the command below:
start chrome /incognito
Standard CSS3 rotate should work in IE9, but I believe you need to give it a vendor prefix, like so:
-ms-transform: rotate(10deg);
It is possible that it may not work in the beta version; if not, try downloading the current preview version (preview 7), which is a later revision that the beta. I don't have the beta version to test against, so I can't confirm whether it was in that version or not. The final release version is definitely slated to support it.
I can also confirm that the IE-specific filter
property has been dropped in IE9.
[Edit]
People have asked for some further documentation. As they say, this is quite limited, but I did find this page: http://css3please.com/ which is useful for testing various CSS3 features in all browsers.
But testing the rotate feature on this page in IE9 preview caused it to crash fairly spectacularly.
However I have done some independant tests using -ms-transform:rotate()
in IE9 in my own test pages, and it is working fine. So my conclusion is that the feature is implemented, but has got some bugs, possibly related to setting it dynamically.
Another useful reference point for which features are implemented in which browsers is www.canIuse.com -- see http://caniuse.com/#search=rotation
[EDIT]
Reviving this old answer because I recently found out about a hack called CSS Sandpaper which is relevant to the question and may make things easier.
The hack implements support for the standard CSS transform
for for old versions of IE. So now you can add the following to your CSS:
-sand-transform: rotate(10deg);
...and have it work in IE 6/7/8, without having to use the filter
syntax. (of course it still uses the filter syntax behind the scenes, but this makes it a lot easier to manage because it's using similar syntax to other browsers)
Maven dependency
<dependency>
<groupId>org.springframework.ws</groupId>
<artifactId>spring-ws-security</artifactId>
</dependency>
<dependency>
<groupId>org.apache.ws.security</groupId>
<artifactId>wss4j</artifactId>
<version>1.6.19</version>
</dependency>
Configuration class
import org.springframework.ws.soap.security.wss4j.Wss4jSecurityInterceptor;
@Configuration
public class ConfigurationClass{
@Bean
public Wss4jSecurityInterceptor securityInterceptor() {
Wss4jSecurityInterceptor wss4jSecurityInterceptor = new Wss4jSecurityInterceptor();
wss4jSecurityInterceptor.setSecurementActions("UsernameToken");
wss4jSecurityInterceptor.setSecurementMustUnderstand(true);
wss4jSecurityInterceptor.setSecurementPasswordType("PasswordText");
wss4jSecurityInterceptor.setSecurementUsername("123456789011");
wss4jSecurityInterceptor.setSecurementPassword("TestPass123");
return wss4jSecurityInterceptor;
}
Result xml
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/">
<SOAP-ENV:Header>
<wsse:Security
xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd"
xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd"
SOAP-ENV:mustUnderstand="1">
<wsse:UsernameToken wsu:Id="UsernameToken-F57F40DC89CD6998E214700450735811">
<wsse:Username>123456789011</wsse:Username>
<wsse:Password Type="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText">TestPass123</wsse:Password>
</wsse:UsernameToken>
</wsse:Security>
</SOAP-ENV:Header>
<SOAP-ENV:Body>
...
something
...
</SOAP-ENV:Body>
Note that it is now possible to use some of C++11 std::thread in the win32 threading mode. These header-only adapters worked out of the box for me: https://github.com/meganz/mingw-std-threads
From the revision history it looks like there is some recent attempt to make this a part of the mingw64 runtime.
If you are using Facebook SDK, you don't need to bother yourself to enter anything for redirect URI on the app management page of facebook. Just setup a URL scheme for your iOS app. The URL scheme of your app should be a value "fbxxxxxxxxxxx" where xxxxxxxxxxx is your app id as identified on facebook. To setup URL scheme for your iOS app, go to info tab of your app settings and add URL Type.
DataSet ds = new DataSet();
using (var reader = cmd.ExecuteReader())
{
while (!reader.IsClosed)
{
ds.Tables.Add().Load(reader);
}
}
return ds;
The first set of errors, for the missing vtable, are caused because you do not implement takeaway::textualGame()
; instead you implement a non-member function, textualGame()
. I think that adding the missing takeaway::
will fix that.
The cause of the last error is that you're calling a virtual function, initialData()
, from the constructor of gameCore
. At this stage, virtual functions are dispatched according to the type currently being constructed (gameCore
), not the most derived class (takeaway
). This particular function is pure virtual, and so calling it here gives undefined behaviour.
Two possible solutions:
gameCore
out of the constructor and into a separate initialisation function, which must be called after the object is fully constructed; orgameCore
into two classes: an abstract interface to be implemented by takeaway
, and a concrete class containing the state. Construct takeaway
first, and then pass it (via a reference to the interface class) to the constructor of the concrete class.I would recommend the second, as it is a move towards smaller classes and looser coupling, and it will be harder to use the classes incorrectly. The first is more error-prone, as there is no way be sure that the initialisation function is called correctly.
One final point: the destructor of a base class should usually either be virtual (to allow polymorphic deletion) or protected (to prevent invalid polymorphic deletion).
Late to the party, but I think it is a useful answer.
flatMap
would be the shortest way to do it.
Stream.of(objects).flatMap(o->(o instanceof Client)?Stream.of((Client)o):Stream.empty())
If o
is a Client
then create a Stream with a single element, otherwise use the empty stream. These streams will then be flattened into a Stream<Client>
.
For add new PCH file follow bellow steps :
(1) Add New fiew - Select iOS - Other and PCH File
(2) add path of this PCH file to your Project - BuildSetting - Apple LLVM 6.0 Language
Add Set Prefix Header Path YourApplicationName(root-path)/filename.pch
Power is **
and e^
is math.exp
:
x.append(1 - math.exp(-0.5 * (value1*value2)**2))
You're looking for calls to sys.exit()
in the script. The argument to that method is returned to the environment as the exit code.
It's fairly likely that the script is never calling the exit method, and that 0 is the default exit code.
You create the relationships the other way around; add foreign keys to the Person
type to create a Many-to-One relationship:
class Person(models.Model):
name = models.CharField(max_length=50)
birthday = models.DateField()
anniversary = models.ForeignKey(
Anniversary, on_delete=models.CASCADE)
address = models.ForeignKey(
Address, on_delete=models.CASCADE)
class Address(models.Model):
line1 = models.CharField(max_length=150)
line2 = models.CharField(max_length=150)
postalcode = models.CharField(max_length=10)
city = models.CharField(max_length=150)
country = models.CharField(max_length=150)
class Anniversary(models.Model):
date = models.DateField()
Any one person can only be connected to one address and one anniversary, but addresses and anniversaries can be referenced from multiple Person
entries.
Anniversary
and Address
objects will be given a reverse, backwards relationship too; by default it'll be called person_set
but you can configure a different name if you need to. See Following relationships "backward" in the queries documentation.
This question was posted in 2015. In 2018, node recognizes both .js and .ts. So, running node file.ts
will also run.
Disclamer: This is just a wild guess
I know everybody loves an easy-to-read list:
toBe(<value>)
- The returned value is the same as <value>
toBeTrue()
- Checks if the returned value is true
toBeTruthy()
- Check if the value, when cast to a boolean, will be a truthy value
Truthy values are all values that aren't 0
, ''
(empty string), false
, null
, NaN
, undefined
or []
(empty array)*.
* Notice that when you run !![]
, it returns true
, but when you run [] == false
it also returns true
. It depends on how it is implemented. In other words: (!![]) === ([] == false)
On your example, toBe(true)
and toBeTrue()
will yield the same results.
What all of these answers do not highlight is that when comparing a value to $null, you have to put $null on the left-hand side, otherwise you may get into trouble when comparing with a collection-type value. See: https://github.com/nightroman/PowerShellTraps/blob/master/Basic/Comparison-operators-with-collections/looks-like-object-is-null.ps1
$value = @(1, $null, 2, $null)
if ($value -eq $null) {
Write-Host "$value is $null"
}
The above block is (unfortunately) executed. What's even more interesting is that in Powershell a $value can be both $null and not $null:
$value = @(1, $null, 2, $null)
if (($value -eq $null) -and ($value -ne $null)) {
Write-Host "$value is both $null and not $null"
}
So it is important to put $null on the left-hand side to make these comparisons work with collections:
$value = @(1, $null, 2, $null)
if (($null -eq $value) -and ($null -ne $value)) {
Write-Host "$value is both $null and not $null"
}
I guess this shows yet again the power of Powershell !
What's the fastest I don't know, but I know what's the most readable - that what's shortest and simplest. Even if it's a little bit slower than other solution it's worth to use.
So use:
"string".replace("a", "b");
"string".replace(/abc?/g, "def");
And enjoy good code instead of faster (well... 1/100000 sec. is not a difference) and ugly one. ;)
If you want to delete any commit then you might need to use git rebase command
git rebase -i HEAD~2
it will show you last 2 commit messages, if you delete the commit message and save that file deleted commit will automatically disappear...
The line height of the <br>
can be different from the line height of the rest of the text inside a <p>
. You can control the line height of your <br>
tags independently of the rest of the text by enclosing two of them in a <span>
that is styled. Use the line-height
css property, as others have suggested.
<p class="normalLineHeight">
Lots of text here which will display on several lines with normal line height if you put it in a narrow container...
<span class="customLineHeight"><br><br></span>
After a custom break, this text will again display on several lines with normal line height...
</p>
json:
[{"ew":"vehicles","hws":["car","van","bike","plane","bus"]},{"ew":"countries","hws":["America","India","France","Japan","South Africa"]}]
c# code: to take only a single value, for example the word "bike".
//res=[{"ew":"vehicles","hws":["car","van","bike","plane","bus"]},{"ew":"countries","hws":["America","India","France","Japan","South Africa"]}]
dynamic stuff1 = Newtonsoft.Json.JsonConvert.DeserializeObject(res);
string Text = stuff1[0].hws[2];
Console.WriteLine(Text);
output:
bike
If your query is something like this SELECT Count(*) FROM tranbook
, then do this rs.next(); System.out.println(rs.getInt("Count(*)"));
Don't know for sure, but it sounds like it is still submitting. I quick solution would be to change your (guessing at your code here):
<input type="submit" value="Submit" onclick="checkform()">
to a button:
<input type="button" value="Submit" onclick="checkform()">
That way your form still gets submitted (from the else part of your checkform()) and it shouldn't be reloading the page.
There are other, perhaps better, ways of handling it but this works in the mean time.
You can use IIF for a similar result.
Note that you can nest the IIF statements to handle multiple cases. There is an example here: http://forums.devshed.com/database-management-46/query-ms-access-iif-statement-multiple-conditions-358130.html
SELECT IIf([Combinaison] = "Mike", 12, IIf([Combinaison] = "Steve", 13)) As Answer
FROM MyTable;
You must want to determine the lower and upper bound before writing the condition
function between(value,first,last) {
let lower = Math.min(first,last) , upper = Math.max(first,last);
return value >= lower && value <= upper ;
}
Verify that Postgres is running using:
ps -ef | grep postgres
root@959dca34cc6d:/var/lib/edb# ps -ef|grep postgres
enterpr+ 476 1 0 06:38 ? 00:00:00 /usr/lib/edb-as/11/bin/edb-postgres -D /var/lib/edb-as/11/main2 -c config_file=/etc/edb-as/11/main2/postgresql.conf
Check for data directory and postgresql.conf
.
In my case data directory in -D
was different than that in postgresql.conf
So I changed the data directory in postgresql.conf
and it worked.
CONNECTION_REFUSED is standard when the port is closed, but it could be rejected because SSL is failing authentication (one of a billion reasons). Did you configure SSL with Ratchet? (Apache is bypassed) Did you try without SSL in JavaScript?
I don't think Ratchet has built-in support for SSL. But even if it does you'll want to try the ws:// protocol first; it's a lot simpler, easier to debug, and closer to telnet. Chrome or the socket service may also be generating the REFUSED error if the service doesn't support SSL (because you explicitly requested SSL).
However the refused message is likely a server side problem, (usually port closed).
Familiar with multilevel hierarchy?
You can use subclass as superclass to your another class.
You can try this.
public class PreferenceActivity extends AbstractBillingActivity {}
then
public class Preferences extends PreferenceActivity {}
In this case, Preferences class inherits both PreferencesActivity and AbstractBillingActivity as well.
Ok, find color in HSV
space is an old but common question. I made a hsv-colormap
to fast look up special color. Here it is:
The x-axis represents Hue
in [0,180), the y-axis1 represents Saturation
in [0,255], the y-axis2 represents S = 255
, while keep V = 255
.
To find a color, usually just look up for the range of H
and S
, and set v in range(20, 255).
To find the orange color, we look up for the map, and find the best range: H :[10, 25], S: [100, 255], and V: [20, 255]
. So the mask is cv2.inRange(hsv,(10, 100, 20), (25, 255, 255) )
Then we use the found range to look for the orange color, this is the result:
The method is simple but common to use:
#!/usr/bin/python3
# 2018.01.21 20:46:41 CST
import cv2
img = cv2.imread("test.jpg")
hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
mask = cv2.inRange(hsv,(10, 100, 20), (25, 255, 255) )
cv2.imshow("orange", mask);cv2.waitKey();cv2.destroyAllWindows()
Similar answers:
here is the one working fine:
import sys
from PyQt4.QtCore import *
from PyQt4.QtGui import *
from PyQt4.QtWebKit import *
app = QApplication(sys.argv)
web = QWebView()
web.load(QUrl("http://www.yahoo.com"))
printer = QPrinter()
printer.setPageSize(QPrinter.A4)
printer.setOutputFormat(QPrinter.PdfFormat)
printer.setOutputFileName("fileOK.pdf")
def convertIt():
web.print_(printer)
print("Pdf generated")
QApplication.exit()
QObject.connect(web, SIGNAL("loadFinished(bool)"), convertIt)
sys.exit(app.exec_())
spark.default.parallelism is the default number of partition set by spark which is by default 200. and if you want to increase the number of partition than you can apply the property spark.sql.shuffle.partitions to set number of partition in the spark configuration or while running spark SQL.
Normally this spark.sql.shuffle.partitions it is being used when we have a memory congestion and we see below error: spark error:java.lang.IllegalArgumentException: Size exceeds Integer.MAX_VALUE
so set your can allocate a partition as 256 MB per partition and that you can use to set for your processes.
also If number of partitions is near to 2000 then increase it to more than 2000. As spark applies different logic for partition < 2000 and > 2000 which will increase your code performance by decreasing the memory footprint as data default is highly compressed if >2000.
function updateURL(url_params) {
if (history.pushState) {
var newurl = window.location.protocol + "//" + window.location.host + window.location.pathname + '?' + url_params;
window.history.replaceState({path:newurl},'',newurl);
}
}
function setActiveTab(tab) {
$('.nav-tabs li').removeClass('active');
$('.tab-content .tab-pane').removeClass('active');
$('a[href="#tab-' + tab + '"]').closest('li').addClass('active');
$('#tab-' + tab).addClass('active');
}
// Set active tab
$url_params = new URLSearchParams(window.location.search);
// Get active tab and remember it
$('a[data-toggle="tab"]')
.on('click', function() {
$href = $(this).attr('href')
$active_tab = $href.replace('#tab-', '');
$url_params.set('tab', $active_tab);
updateURL($url_params.toString());
});
if ($url_params.has('tab')) {
$tab = $url_params.get('tab');
$tab = '#tab-' + $tab;
$myTab = JSON.stringify($tab);
$thisTab = $('.nav-tabs a[href=' + $myTab +']');
$('.nav-tabs a[href=' + $myTab +']').tab('show');
}
You need to put the format arguments into a tuple (add parentheses):
instr = "'%s', '%s', '%d', '%s', '%s', '%s', '%s'" % (softname, procversion, int(percent), exe, description, company, procurl)
What you currently have is equivalent to the following:
intstr = ("'%s', '%s', '%d', '%s', '%s', '%s', '%s'" % softname), procversion, int(percent), exe, description, company, procurl
Example:
>>> "%s %s" % 'hello', 'world'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: not enough arguments for format string
>>> "%s %s" % ('hello', 'world')
'hello world'
First you download ODBC driver psqlodbc_09_01_0200-x64.zip then you installed it.After that go to START->Program->Administrative tools then you select Data Source ODBC then you double click on the same after that you select PostgreSQL 30 then you select configure then you provide proper details such as db name user Id host name password of the same database in this way you will configured your DSN connection.After That you will check SSL should be allow .
Then you go on next tab system DSN then you select ADD tabthen select postgreSQL_ANSI_64X ODBC after you that you have created PostgreSQL ODBC connection.
Use reindex
to get all columns you need. It'll preserve the ones that are already there and put in empty columns otherwise.
p = p.reindex(columns=['1Sun', '2Mon', '3Tue', '4Wed', '5Thu', '6Fri', '7Sat'])
So, your entire code example should look like this:
df = pd.read_csv(CsvFileName)
p = df.pivot_table(index=['Hour'], columns='DOW', values='Changes', aggfunc=np.mean).round(0)
p.fillna(0, inplace=True)
columns = ["1Sun", "2Mon", "3Tue", "4Wed", "5Thu", "6Fri", "7Sat"]
p = p.reindex(columns=columns)
p[columns] = p[columns].astype(int)
To do a border along one side of a select in IE use IE's filters:
select.required { border-left:2px solid red; filter: progid:DXImageTransform.Microsoft.dropshadow(OffX=-2, OffY=0,color=#FF0000) }
I put a border on one side only of all my inputs for required status.
There is probably an effects that do a better job for an all-round border ...
http://msdn.microsoft.com/en-us/library/ms532853(v=VS.85).aspx
export ANDROID_HOME=/usr/local/share/android-sdk/tools/bin
export PATH=$PATH:/usr/local/share/android-sdk/tools/bin
If you don't want to add a new column, and you can guarantee that your current int column is unique, you could select all of the data out into a temporary table, drop the table and recreate with the IDENTITY column specified. Then using SET IDENTITY INSERT ON
you can insert all of your data in the temporary table into the new table.
Have you tried using JsonSlurper?
Example usage:
def slurper = new JsonSlurper()
def result = slurper.parseText('{"person":{"name":"Guillaume","age":33,"pets":["dog","cat"]}}')
assert result.person.name == "Guillaume"
assert result.person.age == 33
assert result.person.pets.size() == 2
assert result.person.pets[0] == "dog"
assert result.person.pets[1] == "cat"
I have to read own parameters by startup.
That has to be there before the WebHost is started (as I need the “to listen” url/IP and port from the parameter file and apply it to the WebHost). Further, I need the settings public in the whole application.
After searching for a while (no complete example found, only snippets) and after various try-and-error's, I have decided to do it the “old way" with an own .ini file.
So.. if you want to use your own .ini file and/or set the "to listen url/IP" your own and/or need the settings public, this is for you...
Complete example, valid for core 2.1 (mvc):
Create an .ini-file - example:
[Startup]
URL=http://172.16.1.201:22222
[Parameter]
*Dummy1=gew7623
Dummy1=true
Dummy2=1
whereby the Dummyx are only included as example for other date types than string (and also to test the case “wrong param” (see code below).
Added a code file in the root of the project, to store the global variables:
namespace MatrixGuide
{
public static class GV
{
// In this class all gobals are defined
static string _cURL;
public static string cURL // URL (IP + Port) on that the application has to listen
{
get { return _cURL; }
set { _cURL = value; }
}
static bool _bdummy1;
public static bool bdummy1 //
{
get { return _bdummy1; }
set { _bdummy1 = value; }
}
static int _idummy1;
public static int idummy1 //
{
get { return _idummy1; }
set { _idummy1 = value; }
}
static bool _bFehler_Ini;
public static bool bFehler_Ini //
{
get { return _bFehler_Ini; }
set { _bFehler_Ini = value; }
}
// add further GV variables here..
}
// Add further classes here...
}
Changed the code in program.cs (before CreateWebHostBuilder()):
namespace MatrixGuide
{
public class Program
{
public static void Main(string[] args)
{
// Read .ini file and overtake the contend in globale
// Do it in an try-catch to be able to react to errors
GV.bFehler_Ini = false;
try
{
var iniconfig = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddIniFile("matrixGuide.ini", optional: false, reloadOnChange: true)
.Build();
string cURL = iniconfig.GetValue<string>("Startup:URL");
bool bdummy1 = iniconfig.GetValue<bool>("Parameter:Dummy1");
int idummy2 = iniconfig.GetValue<int>("Parameter:Dummy2");
//
GV.cURL = cURL;
GV.bdummy1 = bdummy1;
GV.idummy1 = idummy2;
}
catch (Exception e)
{
GV.bFehler_Ini = true;
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("!! Fehler beim Lesen von MatrixGuide.ini !!");
Console.WriteLine("Message:" + e.Message);
if (!(e.InnerException != null))
{
Console.WriteLine("InnerException: " + e.InnerException.ToString());
}
Console.ForegroundColor = ConsoleColor.White;
}
// End .ini file processing
//
CreateWebHostBuilder(args).Build().Run();
}
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>() //;
.UseUrls(GV.cURL, "http://localhost:5000"); // set the to use URL from .ini -> no impact to IISExpress
}
}
This way:
Ideally, the Python script you want to run will be set up with code like this near the end:
def main(arg1, arg2, etc):
# do whatever the script does
if __name__ == "__main__":
main(sys.argv[1], sys.argv[2], sys.argv[3])
In other words, if the module is called from the command line, it parses the command line options and then calls another function, main()
, to do the actual work. (The actual arguments will vary, and the parsing may be more involved.)
If you want to call such a script from another Python script, however, you can simply import
it and call modulename.main()
directly, rather than going through the operating system.
os.system
will work, but it is the roundabout (read "slow") way to do it, as you are starting a whole new Python interpreter process each time for no raisin.
If you want to insert a list into a list, you can do this:
>>> a = [1,2,3,4,5]
>>> for x in reversed(['a','b','c']): a.insert(2,x)
>>> a
[1, 2, 'a', 'b', 'c', 3, 4, 5]
Threads share the code and data segments and the heap, but they don't share the stack.
You could try qemu, which is what the Android emulator uses. I believe it actually emulates the ARM hardware.
If you're using PHP you can funnel your request to Node scripts via shell_exec, passing arguments to scripts as JSON strings in the command line. Example call:
<?php
shell_exec("node nodeScript.js"); // without arguments
shell_exec("node nodeScript.js '{[your JSON here]}'"); //with arguments
?>
The caveat is you need to be very careful about handling user data when it goes anywhere near a command line. Example nightmare:
<?php
$evilUserData = "'; [malicious commands here];";
shell_exec("node nodeScript.js '{$evilUserData}'");
?>
This is just an explanation not addressed in other answers
At least in recent versions of Mysql, your first query is not committed.
If you query it under the same session you will see the changes, but if you query it from a different session, the changes are not there, they are not committed.
What's going on?
When you open a transaction, and a query inside it fails, the transaction keeps open, it does not commit nor rollback the changes.
So BE CAREFUL, any table/row that was locked with a previous query likeSELECT ... FOR SHARE/UPDATE
, UPDATE
, INSERT
or any other locking-query, keeps locked until that session is killed (and executes a rollback), or until a subsequent query commits it explicitly (COMMIT
) or implicitly, thus making the partial changes permanent (which might happen hours later, while the transaction was in a waiting state).
That's why the solution involves declaring handlers to immediately ROLLBACK
when an error happens.
Extra
Inside the handler you can also re-raise the error using RESIGNAL
, otherwise the stored procedure executes "Successfully"
BEGIN
DECLARE EXIT HANDLER FOR SQLEXCEPTION
BEGIN
ROLLBACK;
RESIGNAL;
END;
START TRANSACTION;
#.. Query 1 ..
#.. Query 2 ..
#.. Query 3 ..
COMMIT;
END
Ok now I've done my research, here is the deal:
In TDS protocol, SET NOCOUNT ON
only saves 9-bytes per query while the text "SET NOCOUNT ON" itself is a whopping 14 bytes. I used to think that 123 row(s) affected
was returned from server in plain text in a separate network packet but that's not the case. It's in fact a small structure called DONE_IN_PROC
embedded in the response. It's not a separate network packet so no roundtrips are wasted.
I think you can stick to default counting behavior almost always without worrying about the performance. There are some cases though, where calculating the number of rows beforehand would impact the performance, such as a forward-only cursor. In that case NOCOUNT might be a necessity. Other than that, there is absolutely no need to follow "use NOCOUNT wherever possible" motto.
Here is a very detailed analysis about insignificance of SET NOCOUNT
setting: http://daleburnett.com/2014/01/everything-ever-wanted-know-set-nocount/
You can specify multiple patterns in an array.
select-string VendorEnquiry,Failed C:\Logs
This works with -notmatch as well:
select-string -notmatch VendorEnquiry,Failed C:\Logs
To only modify the title's font (and not the font of the axis) I used this:
import matplotlib.pyplot as plt
fig = plt.Figure()
ax = fig.add_subplot(111)
ax.set_title('My Title', fontdict={'fontsize': 8, 'fontweight': 'medium'})
The fontdict accepts all kwargs from matplotlib.text.Text.
Definitely regex:
string CleanPhone(string phone)
{
Regex digitsOnly = new Regex(@"[^\d]");
return digitsOnly.Replace(phone, "");
}
or within a class to avoid re-creating the regex all the time:
private static Regex digitsOnly = new Regex(@"[^\d]");
public static string CleanPhone(string phone)
{
return digitsOnly.Replace(phone, "");
}
Depending on your real-world inputs, you may want some additional logic there to do things like strip out leading 1's (for long distance) or anything trailing an x or X (for extensions).
Here's a different example that can't be rewritten without aliases ( can't GROUP BY DISTINCT
).
Imagine a table called purchases
that records purchases made by customers
at stores
, i.e. it's a many to many table and the software needs to know which customers have made purchases at more than one store:
SELECT DISTINCT customer_id, SUM(1)
FROM ( SELECT DISTINCT customer_id, store_id FROM purchases)
GROUP BY customer_id HAVING 1 < SUM(1);
..will break with the error Every derived table must have its own alias
. To fix:
SELECT DISTINCT customer_id, SUM(1)
FROM ( SELECT DISTINCT customer_id, store_id FROM purchases) AS custom
GROUP BY customer_id HAVING 1 < SUM(1);
( Note the AS custom
alias).
To install SOAP in PHP-7 run following in your Ubuntu terminal:
sudo apt-get install php7.0-soap
To install SOAP in PHP-7.1 run following in your Ubuntu terminal:
sudo apt-get install php7.1-soap
To install SOAP in PHP-7.2 run following in your Ubuntu terminal:
sudo apt-get install php7.2-soap
To install SOAP in PHP-7.3 run following in your Ubuntu terminal:
sudo apt-get install php7.3-soap
With jQuery 3.x use something like:
$('<img src="'+ imgPath +'">').on('load', function() {
$(this).width(some).height(some).appendTo('#some_target');
});
Go to "%TOMCAT_FOLDER%/conf/tomcat-users.xml" and configure the following :
<tomcat-users>
<role rolename="manager-gui"/>
<role rolename="manager-script"/>
<role rolename="manager-jmx"/>
<role rolename="manager-status"/>
<role rolename="admin"/>
<user username="admin" password="admin" roles="admin,manager-gui,manager-script"/>
</tomcat-users>
Hence, the username is "admin" and password is "admin"
For 2005 and later, these will both give what you're looking for.
SELECT name FROM sys.schemas
SELECT SCHEMA_NAME FROM INFORMATION_SCHEMA.SCHEMATA
For 2000, this will give a list of the databases in the instance.
SELECT * FROM INFORMATION_SCHEMA.SCHEMATA
That's the "backward incompatability" noted in @Adrift's answer.
In SQL Server 2000 (and lower), there aren't really "schemas" as such, although you can use roles as namespaces in a similar way. In that case, this may be the closest equivalent.
SELECT * FROM sysusers WHERE gid <> 0
Here is my solution, which I think is a bit less hackish than most others here. It is similar to nightowl's answer.
someclasses = [MyClass(), MyClass(), MyClass()]
def method_caller(some_object, some_method='the method'):
return getattr(some_object, some_method)()
othermethod = partial(method_caller, some_method='othermethod')
with Pool(6) as pool:
result = pool.map(othermethod, someclasses)
If you want to create dynamically/runtime data table in VB.Net then you should follow these steps as mentioned below :
For eg.
Dim dt As New DataTable
dt.Columns.Add("Id", GetType(Integer))
dt.Columns.Add("FirstName", GetType(String))
dt.Columns.Add("LastName", GetType(String))
dt.Rows.Add(1, "Test", "data")
dt.Rows.Add(15, "Robert", "Wich")
dt.Rows.Add(18, "Merry", "Cylon")
dt.Rows.Add(30, "Tim", "Burst")
You can use below code if object has attibutes under it.
String getCommonSeperatedString(List<ActionObject> actionObjects) {
StringBuffer sb = new StringBuffer();
for (ActionObject actionObject : actionObjects){
sb.append(actionObject.Id).append(",");
}
sb.deleteCharAt(sb.lastIndexOf(","));
return sb.toString();
}
HTTP Error 500.30 – ANCM In-Process Start Failure” is moreover a generic error. To know more information about the error
Go to Azure Portal > your App Service > under development tools open console. We can run the application through this console and thus visualize the real error that is causing our application not to load.
For that put, the name of our project followed by “.exe” and press the enter key.
To keep your requests fast, cache the server side results of the ping and update the ping file or database every couple of minutes(or however accurate you want it to be). You can use cron to run a shell command with your 8 pings and write the output into a file, the webserver will include this file into your view.