Geonames has a lot of data on places (including towns and cities) but it seems to be contributed and perhaps not complete.
Perhaps also try SQL Dumpster, I've used this website a lot for these kinds of databases, cities, provinces, etc. Unfortunately it's not free but only appears to be a one-time fee.
Surprise! You can use split to split.
var parts = "1234567890 ".split(/(.{2})/).filter(O=>O)
Results in [ '12', '34', '56', '78', '90', ' ' ]
A simple semantic name would be last
. This would allow code always positive code like:
if (item.last)
...
do {
...
} until (item.last);
On Firefox 78 use this ("keypress" doesn't work for Escape key):
function keyPress (e)(){
if (e.key == "Escape"){
//do something here
}
document.addEventListener("keyup", keyPress);
please try below answer.
+(void)callAFWSPost:(NSDictionary *)dict withURL:(NSString *)strUrl
withBlock:(dictionary)block
{
AFHTTPSessionManager *manager = [[AFHTTPSessionManager alloc]initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
[manager.requestSerializer setValue:@"application/x-www-form-urlencoded; charset=UTF-8" forHTTPHeaderField:@"Content-Type"];
manager.requestSerializer = [AFHTTPRequestSerializer serializer];
manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html", nil];
[manager POST:[NSString stringWithFormat:@"%@/%@",WebserviceUrl,strUrl] parameters:dict progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject)
{
if (!responseObject)
{
NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
[dict setObject:ServerResponceError forKey:@"error"];
block(responseObject);
return ;
}
else if ([responseObject isKindOfClass:[NSDictionary class]]) {
block(responseObject);
return ;
}
}
failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error)
{
NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
[dict setObject:ServerResponceError forKey:@"error"];
block(dict);
}];
}
Because $xml->xpath
always return an array, and strlen
expects a string.
Here is a new solution based on Bennett McElwee answer in the same question as mentioned below.
Tested with IE 9 & 10, Opera 12.01, Google Chrome 22 and Firefox 15.0.
jsFiddle example
@media screen {
#printSection {
display: none;
}
}
@media print {
body * {
visibility:hidden;
}
#printSection, #printSection * {
visibility:visible;
}
#printSection {
position:absolute;
left:0;
top:0;
}
}
function printElement(elem, append, delimiter) {
var domClone = elem.cloneNode(true);
var $printSection = document.getElementById("printSection");
if (!$printSection) {
$printSection = document.createElement("div");
$printSection.id = "printSection";
document.body.appendChild($printSection);
}
if (append !== true) {
$printSection.innerHTML = "";
}
else if (append === true) {
if (typeof (delimiter) === "string") {
$printSection.innerHTML += delimiter;
}
else if (typeof (delimiter) === "object") {
$printSection.appendChild(delimiter);
}
}
$printSection.appendChild(domClone);
}?
You're ready to print any element on your site!
Just call printElement()
with your element(s) and execute window.print()
when you're finished.
Note: If you want to modify the content before it is printed (and only in the print version), checkout this example (provided by waspina in the comments): http://jsfiddle.net/95ezN/121/
One could also use CSS in order to show the additional content in the print version (and only there).
I think, you have to hide all other parts of the site via CSS.
It would be the best, to move all non-printable content into a separate DIV
:
<body>
<div class="non-printable">
<!-- ... -->
</div>
<div class="printable">
<!-- Modal dialog comes here -->
</div>
</body>
And then in your CSS:
.printable { display: none; }
@media print
{
.non-printable { display: none; }
.printable { display: block; }
}
Credits go to Greg who has already answered a similar question: Print <div id="printarea"></div> only?
There is one problem in using JavaScript: the user cannot see a preview - at least in Internet Explorer!
You have to set the associatedEmployee on the Vehicle before persisting the Employee.
Employee newEmployee = new Employee("matt");
vehicle1.setAssociatedEmployee(newEmployee);
vehicles.add(vehicle1);
newEmployee.setVehicles(vehicles);
Employee savedEmployee = employeeDao.persistOrMerge(newEmployee);
Use ==
:
pip install django_modeltranslation==0.4.0-beta2
You try to access private member of one class from another. The fact that bar-class is declared within foo-class means that bar in visible only inside foo class, but that is still other class.
And what is p->param?
Actually, it isn't clear what do you want to do
I don't like fiddling with the array's internal pointer, but it's also inefficient to build a second array with array_keys()
or array_values()
, so I usually define this:
function array_first(array $f) {
foreach ($f as $v) {
return $v;
}
throw new Exception('array was empty');
}
At first find out where ruby is? then
rm -rf /usr/local/lib/ruby
rm -rf /usr/lib/ruby
rm -f /usr/local/bin/ruby
rm -f /usr/bin/ruby
rm -f /usr/local/bin/irb
rm -f /usr/bin/irb
rm -f /usr/local/bin/gem
rm -f /usr/bin/gem
LIST FILES IN FOLDER - 1 solution
<?php
// open this directory
$myDirectory = opendir(".");
// get each entry
while($entryName = readdir($myDirectory)) {
$dirArray[] = $entryName;
}
// close directory
closedir($myDirectory);
// count elements in array
$indexCount = count($dirArray);
Print ("$indexCount files<br>\n");
// sort 'em
sort($dirArray);
// print 'em
print("<TABLE border=1 cellpadding=5 cellspacing=0 class=whitelinks>\n");
print("<TR><TH>Filename</TH><th>Filetype</th><th>Filesize</th></TR>\n");
// loop through the array of files and print them all
for($index=0; $index < $indexCount; $index++) {
if (substr("$dirArray[$index]", 0, 1) != "."){ // don't list hidden files
print("<TR><TD><a href=\"$dirArray[$index]\">$dirArray[$index]</a></td>");
print("<td>"); print(filetype($dirArray[$index])); print("</td>");
print("<td>"); print(filesize($dirArray[$index])); print("</td>");
print("</TR>\n");
}
}
print("</TABLE>\n");
?>
2 solution
<?PHP
# The current directory
$directory = dir("./");
# If you want to turn on Extension Filter, then uncomment this:
### $allowed_ext = array(".sample", ".png", ".jpg", ".jpeg", ".txt", ".doc", ".xls");
## Description of the soft: list_dir_files.php
## Major credits: phpDIRList 2.0 -(c)2005 Ulrich S. Kapp :: Systemberatung ::
$do_link = TRUE;
$sort_what = 0; //0- by name; 1 - by size; 2 - by date
$sort_how = 0; //0 - ASCENDING; 1 - DESCENDING
# # #
function dir_list($dir){
$i=0;
$dl = array();
if ($hd = opendir($dir)) {
while ($sz = readdir($hd)) {
if (preg_match("/^\./",$sz)==0) $dl[] = $sz;$i.=1;
}
closedir($hd);
}
asort($dl);
return $dl;
}
if ($sort_how == 0) {
function compare0($x, $y) {
if ( $x[0] == $y[0] ) return 0;
else if ( $x[0] < $y[0] ) return -1;
else return 1;
}
function compare1($x, $y) {
if ( $x[1] == $y[1] ) return 0;
else if ( $x[1] < $y[1] ) return -1;
else return 1;
}
function compare2($x, $y) {
if ( $x[2] == $y[2] ) return 0;
else if ( $x[2] < $y[2] ) return -1;
else return 1;
}
}else{
function compare0($x, $y) {
if ( $x[0] == $y[0] ) return 0;
else if ( $x[0] < $y[0] ) return 1;
else return -1;
}
function compare1($x, $y) {
if ( $x[1] == $y[1] ) return 0;
else if ( $x[1] < $y[1] ) return 1;
else return -1;
}
function compare2($x, $y) {
if ( $x[2] == $y[2] ) return 0;
else if ( $x[2] < $y[2] ) return 1;
else return -1;
}
}
##################################################
# We get the information here
##################################################
$i = 0;
while($file=$directory->read()) {
$file = strtolower($file);
$ext = strrchr($file, '.');
if (isset($allowed_ext) && (!in_array($ext,$allowed_ext)))
{
// dump
}
else {
$temp_info = stat($file);
$new_array[$i][0] = $file;
$new_array[$i][1] = $temp_info[7];
$new_array[$i][2] = $temp_info[9];
$new_array[$i][3] = date("F d, Y", $new_array[$i][2]);
$i = $i + 1;
}
}
$directory->close();
##################################################
# We sort the information here
#################################################
switch ($sort_what) {
case 0:
usort($new_array, "compare0");
break;
case 1:
usort($new_array, "compare1");
break;
case 2:
usort($new_array, "compare2");
break;
}
###############################################################
# We display the infomation here
###############################################################
$i2 = count($new_array);
$i = 0;
echo "<table border=1>
<tr>
<td width=150> File name</td>
<td width=100> File Size</td>
<td width=100>Last Modified</td>
</tr>";
for ($i=0;$i<$i2;$i++) {
if (!$do_link) {
$line = "<tr><td align=right>" .
$new_array[$i][0] .
"</td><td align=right>" .
number_format(($new_array[$i][1]/1024)) .
"k";
$line = $line . "</td><td align=right>" . $new_array[$i][3] . "</td></tr>";
}else{
$line = '<tr><td align=right><A HREF="' .
$new_array[$i][0] . '">' .
$new_array[$i][0] .
"</A></td><td align=right>";
$line = $line . number_format(($new_array[$i][1]/1024)) .
"k" . "</td><td align=right>" .
$new_array[$i][3] . "</td></tr>";
}
echo $line;
}
echo "</table>";
?>
Try
android:layout_centerHorizontal="true"
Exactly like this, it works for me:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#ff0000">
<Button
android:id="@+id/btn_mybutton"
android:layout_height="wrap_content"
android:layout_width="124dip"
android:layout_marginTop="5dip"
android:layout_centerHorizontal="true"/>
</RelativeLayout>
Yep ! I finally Find it.
implement following code on your button click event, to pop up action sheet as given in the image of question.
UIActionSheet *aac = [[UIActionSheet alloc] initWithTitle:@"How many?"
delegate:self
cancelButtonTitle:nil
destructiveButtonTitle:nil
otherButtonTitles:nil];
UIDatePicker *theDatePicker = [[UIDatePicker alloc] initWithFrame:CGRectMake(0.0, 44.0, 0.0, 0.0)];
if(IsDateSelected==YES)
{
theDatePicker.datePickerMode = UIDatePickerModeDate;
theDatePicker.maximumDate=[NSDate date];
}else {
theDatePicker.datePickerMode = UIDatePickerModeTime;
}
self.dtpicker = theDatePicker;
[theDatePicker release];
[dtpicker addTarget:self action:@selector(dateChanged) forControlEvents:UIControlEventValueChanged];
pickerDateToolbar = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 0, 320, 44)];
pickerDateToolbar.barStyle = UIBarStyleBlackOpaque;
[pickerDateToolbar sizeToFit];
NSMutableArray *barItems = [[NSMutableArray alloc] init];
UIBarButtonItem *flexSpace = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:self action:nil];
[barItems addObject:flexSpace];
UIBarButtonItem *doneBtn = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:@selector(DatePickerDoneClick)];
[barItems addObject:doneBtn];
[pickerDateToolbar setItems:barItems animated:YES];
[aac addSubview:pickerDateToolbar];
[aac addSubview:dtpicker];
[aac showInView:self.view];
[aac setBounds:CGRectMake(0,0,320, 464)];
To resolve this issue you have to do two things :
You will need to set a registry entry on the target computer so that the driver can maintain a connection to the instance of Internet Explorer it creates.
Change few settings of Internet Explorer browser on that machine (where you desire to run automation).
1 . Setting Registry Key / Entry :
To set registry key or entry, you need to open "Registry Editor".
To open "Registry Editor" press windows button key + r alphabet key which will open "Run Window" and then type "regedit" and press enter.
Or Press Windows button key and enter "regedit" at start menu and press enter. Now depending upon your OS type whether 32/64 bit follow the corresponding steps.
Windows 32 bit : go to this location - "HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Internet Explorer\Main\FeatureControl" and check for "FEATURE_BFCACHE" key.
Windows 64 bit : go to this location - HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\Internet Explorer\Main\FeatureControl and check for "FEATURE_BFCACHE" key. Please note that the FEATURE_BFCACHE subkey may or may not be present, and should be created if it is not present.
Important: Inside this key, create a DWORD value named iexplore.exe with the value of 0.
2 . Change Settings of Internet Explorer Browser :
Click on setting button and select "Internet options".
On "Internet options" window go to "Security" tab
Now select "Internet" option and unchecked the "Enable Protected Mode" check box and change the "Security level" to low.
Now select "Local Intranet" Option and change the "Security level" to low.
Now select "Trusted Sites" Option and change the "Security level" to low.
I know this is not possible for alert(), so I guess it is not possible for confirm either. Reason is security: it is not allowed for you to change it so you wouldn't present yourself as some system process or something.
I tried this, but it is not possible to remove "Watch on YouTube" icon. Following solution of mine does not remove the icon itself but "blocks" the mouse hover so that watch on YouTube is not click-able. I added a div over icon, so no mouseover will be affected for that logo.
<div class="holder">
<div class="frame" id="player" style="height 350"></div>
<div class="bar" id="bottom-layer">.</div>
</div>
Where frame is my embedded player. include following to your css file
.holder{
position:relative;
width:640px;
height:350px;
}
.frame{
width: 100%;
height:100%;
}
.bar{
position:absolute;
bottom:0;
right:0;
width:100%;
height:40px;
}
This is not full solution but helps you if you are bothered with users' getting full youtube url.
Never construct BigDecimals from floats or doubles. Construct them from ints or strings. floats and doubles loose precision.
This code works as expected (I just changed the type from double to String):
public static void main(String[] args) {
String doubleVal = "1.745";
String doubleVal1 = "0.745";
BigDecimal bdTest = new BigDecimal( doubleVal);
BigDecimal bdTest1 = new BigDecimal( doubleVal1 );
bdTest = bdTest.setScale(2, BigDecimal.ROUND_HALF_UP);
bdTest1 = bdTest1.setScale(2, BigDecimal.ROUND_HALF_UP);
System.out.println("bdTest:"+bdTest); //1.75
System.out.println("bdTest1:"+bdTest1);//0.75, no problem
}
I usually use
DATE_ADD(CURDATE(), INTERVAL - 1 MONTH)
Which is almost same as Pekka's but this way you can control your INTERVAL to be negative or positive...
In building a custom set of layout tags, I found another answer to this problem. Provided here is the custom set of tags and their CSS classes.
HTML
<layout-table>
<layout-header>
<layout-column> 1 a</layout-column>
<layout-column> </layout-column>
<layout-column> 3 </layout-column>
<layout-column> 4 </layout-column>
</layout-header>
<layout-row>
<layout-column> a </layout-column>
<layout-column> a 1</layout-column>
<layout-column> a </layout-column>
<layout-column> a </layout-column>
</layout-row>
<layout-footer>
<layout-column> 1 </layout-column>
<layout-column> </layout-column>
<layout-column> 3 b</layout-column>
<layout-column> 4 </layout-column>
</layout-footer>
</layout-table>
CSS
layout-table
{
display : table;
clear : both;
table-layout : fixed;
width : 100%;
}
layout-table:unresolved
{
color : red;
border: 1px blue solid;
empty-cells : show;
}
layout-header, layout-footer, layout-row
{
display : table-row;
clear : both;
empty-cells : show;
width : 100%;
}
layout-column
{
display : table-column;
float : left;
width : 25%;
min-width : 25%;
empty-cells : show;
box-sizing: border-box;
/* border: 1px solid white; */
padding : 1px 1px 1px 1px;
}
layout-row:nth-child(even)
{
background-color : lightblue;
}
layout-row:hover
{ background-color: #f5f5f5 }
The key to getting empty cells and cells in general to be the right size, is Box-Sizing and Padding. Border will do the same thing as well, but creates a line in the row. Padding doesn't. And, while I haven't tried it, I think Margin will act the same way as Padding, in forcing and empty cell to be rendered properly.
Imports System.Runtime.InteropServices
Please Note: The original poster was not specifically asking about PHP. All the php centric answers make large assumptions not relevant to the actual question.
The default error log as opposed to the scripts error logs usually has the (more) specific error. often it will be permissions denied or even an interpreter that can't be found.
This means the fault almost always lies with your script. e.g you uploaded a perl script but didnt give it execute permissions? or perhaps it was corrupted in a linux environment if you write the script in windows and then upload it to the server without the line endings being converted you will get this error.
in perl if you forget
print "content-type: text/html\r\n\r\n";
you will get this error
There are many reasons for it. so please first check your error log and then provide some more information.
The default error log is often in /var/log/httpd/error_log
or /var/log/apache2/error.log
.
The reason you look at the default error logs (as indicated above) is because errors don't always get posted into the custom error log as defined in the virtual host.
Assumes linux and not necessarily perl
If <!DOCTYPE>
is missing in your HTML content you may experience that the browser gives preference to the "user agent stylesheet" over your custom stylesheet. Adding the doctype fixes this.
class Testclass
{
public $testvar;
function dosomething()
{
echo $this->testvar;
}
}
$Testclass = new Testclass();
$Testclass->testvar = "another value";
$Testclass->dosomething(); ////It will print "another value"
Personally I like to validate the form on submit and if there are errors, just return false.
$('form').submit(function() {
var error;
if ( !$('input').val() ) {
error = true
}
if (error) {
alert('there are errors')
return false
}
});
CSS will not be able to zoom on demand, but if you couple CSS with JS, you could change some values to make a page look bigger. However, as it has been said, this feature is standard nowadays in modern browsers: no need to replicate it. As a matter of fact, replicating it will slow down your website (more things to load, more JS or CSS to parse or execute and apply, etc.)
For me, the only way on SQL 2008 R2 was this :
EXEC sp_configure 'Show Advanced Options', 1
RECONFIGURE **WITH OVERRIDE**
EXEC sp_configure 'xp_cmdshell', 1
RECONFIGURE **WITH OVERRIDE**
In C++ projects past, I have used PCRE with good success. It's very complete and well-tested since it's used in many high profile projects. And I see that Google has contributed a set of C++ wrappers for PCRE recently, too.
I'm an idiot so it took me a while to realize this, but make sure that the Gear icon is clicked on the global search so your settings can be applied.
It looks OK apart from the space in your ID attribute, which is not valid, and the fact that you're replacing the value of your input before checking the selection.
function textbox()_x000D_
{_x000D_
var ctl = document.getElementById('Javascript_example');_x000D_
var startPos = ctl.selectionStart;_x000D_
var endPos = ctl.selectionEnd;_x000D_
alert(startPos + ", " + endPos);_x000D_
}
_x000D_
<input id="Javascript_example" name="one" type="text" value="Javascript example" onclick="textbox()">
_x000D_
Also, if you're supporting IE <= 8 you need to be aware that those browsers do not support selectionStart
and selectionEnd
.
Answer is adding to @Sebas' answer - setting the collation of my local environment. Do not try this on production.
ALTER DATABASE databasename CHARACTER SET utf8 COLLATE utf8_unicode_ci;
ALTER TABLE tablename CONVERT TO CHARACTER SET utf8 COLLATE utf8_unicode_ci;
Source of this solution
Use this simple inline onClick function on a button if you want to programatically write data to the clipboard.
onClick={() => {navigator.clipboard.writeText(this.state.textToCopy)}}
I've used the implementation above and just now I came to know that it doesn't work on iPad running iOS 13. I had to add these lines before present() call in order to make it work
//avoiding to crash on iPad
if let popoverController = activityViewController.popoverPresentationController {
popoverController.sourceRect = CGRect(x: UIScreen.main.bounds.width / 2, y: UIScreen.main.bounds.height / 2, width: 0, height: 0)
popoverController.sourceView = self.view
popoverController.permittedArrowDirections = UIPopoverArrowDirection(rawValue: 0)
}
That's how it works for me
func shareData(_ dataToShare: [Any]){
let activityViewController = UIActivityViewController(activityItems: dataToShare, applicationActivities: nil)
//exclude some activity types from the list (optional)
//activityViewController.excludedActivityTypes = [
//UIActivity.ActivityType.postToFacebook
//]
//avoiding to crash on iPad
if let popoverController = activityViewController.popoverPresentationController {
popoverController.sourceRect = CGRect(x: UIScreen.main.bounds.width / 2, y: UIScreen.main.bounds.height / 2, width: 0, height: 0)
popoverController.sourceView = self.view
popoverController.permittedArrowDirections = UIPopoverArrowDirection(rawValue: 0)
}
self.present(activityViewController, animated: true, completion: nil)
}
T-SQL doesn't support arrays that I'm aware of.
What's your table structure? You could probably design a query that does this instead:
select
month,
sum(sales)
from sales_table
group by month
order by month
I tried changing the port from 8080
to 80
in the server.xml
but it didn't work for me. Then I found alternative, update the iptables
which i'm sure there is an impact on performance.
I use the following commands:
sudo /sbin/iptables -t nat -I PREROUTING -p tcp --dport 80 -j REDIRECT --to-port 8080
sudo /sbin/service iptables save
http://www.excelsior-usa.com/articles/tomcat-amazon-ec2-advanced.html#port80
One of the things I would suggest is to have two separate stylesheets: One with your regular style definitions and another one that contains your images in base64 encoding.
You have to include the base stylesheet before the image stylesheet of course.
This way you will assure that you're regular stylesheet is downloaded and applied as soon as possible to the document, yet at the same time you profit from reduced http-requests and other benefits data-uris give you.
WOOCOMMERCE ORDERS IN VERSION 3.0+
Since Woocommerce mega major Update 3.0+ things have changed quite a lot:
WC_Order
Object, properties can't be accessed directly anymore as before and will throw some errors.WC_Order
and WC_Abstract_Order
getter and setter methods are now required on the WC_Order
object instance.WC_Data
Abstract class allow to access Order and order items data using get_data()
, get_meta_data()
and get_meta()
methods.Related:
• How to get Customer details from Order in WooCommerce?
• Get Order items and WC_Order_Item_Product in WooCommerce 3
So the Order items properties will not be accessible as before in a foreach
loop and you will have to use these specific getter and setter methods instead.
Using some WC_Order
and WC_Abstract_Order
methods (example):
// Get an instance of the WC_Order object (same as before)
$order = wc_get_order( $order_id );
$order_id = $order->get_id(); // Get the order ID
$parent_id = $order->get_parent_id(); // Get the parent order ID (for subscriptions…)
$user_id = $order->get_user_id(); // Get the costumer ID
$user = $order->get_user(); // Get the WP_User object
$order_status = $order->get_status(); // Get the order status (see the conditional method has_status() below)
$currency = $order->get_currency(); // Get the currency used
$payment_method = $order->get_payment_method(); // Get the payment method ID
$payment_title = $order->get_payment_method_title(); // Get the payment method title
$date_created = $order->get_date_created(); // Get date created (WC_DateTime object)
$date_modified = $order->get_date_modified(); // Get date modified (WC_DateTime object)
$billing_country = $order->get_billing_country(); // Customer billing country
// ... and so on ...
For order status as a conditional method (where "the_targeted_status" need to be defined and replaced by an order status to target a specific order status):
if ( $order->has_status('completed') ) { // Do something }
Get and access to the order data properties (in an array of values):
// Get an instance of the WC_Order object
$order = wc_get_order( $order_id );
$order_data = $order->get_data(); // The Order data
$order_id = $order_data['id'];
$order_parent_id = $order_data['parent_id'];
$order_status = $order_data['status'];
$order_currency = $order_data['currency'];
$order_version = $order_data['version'];
$order_payment_method = $order_data['payment_method'];
$order_payment_method_title = $order_data['payment_method_title'];
$order_payment_method = $order_data['payment_method'];
$order_payment_method = $order_data['payment_method'];
## Creation and modified WC_DateTime Object date string ##
// Using a formated date ( with php date() function as method)
$order_date_created = $order_data['date_created']->date('Y-m-d H:i:s');
$order_date_modified = $order_data['date_modified']->date('Y-m-d H:i:s');
// Using a timestamp ( with php getTimestamp() function as method)
$order_timestamp_created = $order_data['date_created']->getTimestamp();
$order_timestamp_modified = $order_data['date_modified']->getTimestamp();
$order_discount_total = $order_data['discount_total'];
$order_discount_tax = $order_data['discount_tax'];
$order_shipping_total = $order_data['shipping_total'];
$order_shipping_tax = $order_data['shipping_tax'];
$order_total = $order_data['total'];
$order_total_tax = $order_data['total_tax'];
$order_customer_id = $order_data['customer_id']; // ... and so on
## BILLING INFORMATION:
$order_billing_first_name = $order_data['billing']['first_name'];
$order_billing_last_name = $order_data['billing']['last_name'];
$order_billing_company = $order_data['billing']['company'];
$order_billing_address_1 = $order_data['billing']['address_1'];
$order_billing_address_2 = $order_data['billing']['address_2'];
$order_billing_city = $order_data['billing']['city'];
$order_billing_state = $order_data['billing']['state'];
$order_billing_postcode = $order_data['billing']['postcode'];
$order_billing_country = $order_data['billing']['country'];
$order_billing_email = $order_data['billing']['email'];
$order_billing_phone = $order_data['billing']['phone'];
## SHIPPING INFORMATION:
$order_shipping_first_name = $order_data['shipping']['first_name'];
$order_shipping_last_name = $order_data['shipping']['last_name'];
$order_shipping_company = $order_data['shipping']['company'];
$order_shipping_address_1 = $order_data['shipping']['address_1'];
$order_shipping_address_2 = $order_data['shipping']['address_2'];
$order_shipping_city = $order_data['shipping']['city'];
$order_shipping_state = $order_data['shipping']['state'];
$order_shipping_postcode = $order_data['shipping']['postcode'];
$order_shipping_country = $order_data['shipping']['country'];
Get the order items and access the data with WC_Order_Item_Product
and WC_Order_Item
methods:
// Get an instance of the WC_Order object
$order = wc_get_order($order_id);
// Iterating through each WC_Order_Item_Product objects
foreach ($order->get_items() as $item_key => $item ):
## Using WC_Order_Item methods ##
// Item ID is directly accessible from the $item_key in the foreach loop or
$item_id = $item->get_id();
## Using WC_Order_Item_Product methods ##
$product = $item->get_product(); // Get the WC_Product object
$product_id = $item->get_product_id(); // the Product id
$variation_id = $item->get_variation_id(); // the Variation id
$item_type = $item->get_type(); // Type of the order item ("line_item")
$item_name = $item->get_name(); // Name of the product
$quantity = $item->get_quantity();
$tax_class = $item->get_tax_class();
$line_subtotal = $item->get_subtotal(); // Line subtotal (non discounted)
$line_subtotal_tax = $item->get_subtotal_tax(); // Line subtotal tax (non discounted)
$line_total = $item->get_total(); // Line total (discounted)
$line_total_tax = $item->get_total_tax(); // Line total tax (discounted)
## Access Order Items data properties (in an array of values) ##
$item_data = $item->get_data();
$product_name = $item_data['name'];
$product_id = $item_data['product_id'];
$variation_id = $item_data['variation_id'];
$quantity = $item_data['quantity'];
$tax_class = $item_data['tax_class'];
$line_subtotal = $item_data['subtotal'];
$line_subtotal_tax = $item_data['subtotal_tax'];
$line_total = $item_data['total'];
$line_total_tax = $item_data['total_tax'];
// Get data from The WC_product object using methods (examples)
$product = $item->get_product(); // Get the WC_Product object
$product_type = $product->get_type();
$product_sku = $product->get_sku();
$product_price = $product->get_price();
$stock_quantity = $product->get_stock_quantity();
endforeach;
So using
get_data()
method allow us to access to the protected data (associative array mode) …
Following on from the earlier answers above but based on a VS 2019 install ;
I needed to run "tf git permission" commands, and copied the following files from:
C:\Program Files (x86)\Microsoft Visual Studio\2019\TeamExplorer\Common7\IDE\CommonExtensions\Microsoft\TeamFoundation\Team Explorer
Microsoft.TeamFoundation.Client.dll
Microsoft.TeamFoundation.Common.dll
Microsoft.TeamFoundation.Core.WebApi.dll
Microsoft.TeamFoundation.Diff.dll
Microsoft.TeamFoundation.Git.Client.dll
Microsoft.TeamFoundation.Git.Contracts.dll
Microsoft.TeamFoundation.Git.Controls.dll
Microsoft.TeamFoundation.Git.CoreServices.dll
Microsoft.TeamFoundation.Git.dll
Microsoft.TeamFoundation.Git.Graph.dll
Microsoft.TeamFoundation.Git.HostingProvider.AzureDevOps.dll
Microsoft.TeamFoundation.Git.HostingProvider.GitHub.dll
Microsoft.TeamFoundation.Git.HostingProvider.GitHub.imagemanifest
Microsoft.TeamFoundation.Git.Provider.dll
Microsoft.TeamFoundation.SourceControl.WebApi.dll
Microsoft.TeamFoundation.VersionControl.Client.dll
Microsoft.TeamFoundation.VersionControl.Common.dll
Microsoft.TeamFoundation.VersionControl.Common.Integration.dll
Microsoft.TeamFoundation.VersionControl.Controls.dll
Microsoft.VisualStudio.Services.Client.Interactive.dll
Microsoft.VisualStudio.Services.Common.dll
Microsoft.VisualStudio.Services.WebApi.dll
TF.exe
TF.exe.config
You can add an extension to simplify this process. It enables you to just call context.dp(R.dimen. tutorial_cross_marginTop)
to get the Float value
fun Context.px(@DimenRes dimen: Int): Int = resources.getDimension(dimen).toInt()
fun Context.dp(@DimenRes dimen: Int): Float = px(dimen) / resources.displayMetrics.density
If you want to handle it without context, you can use Resources.getSystem()
:
val Int.dp get() = this / Resources.getSystem().displayMetrics.density // Float
val Int.px get() = (this * Resources.getSystem().displayMetrics.density).toInt()
For example, on an xhdpi device, use 24.dp
to get 12.0 or 12.px
to get 24
Just to be clear, you are wanting to launch a program from a batch file and then have the batch file press keys (in your example, the arrow keys) within that launched program?
If that is the case, you aren't going to be able to do that with simply a ".bat" file as the launched would stop the batch file from continuing until it terminated--
My first recommendation would be to use something like AutoHotkey or AutoIt if possible, simply because they both have active forums where you'd find countless examples of people launching applications and sending key presses not to mention tools to simply "record" what you want to do. However you said this is a work computer and you may not be able to load a 3rd party program.. but you aren't without options.
You can use Windows Scripting Host from something like a .vbs file to launch a program and send keys to that process. If you're running a version of Windows that includes PowerShell 2.0 (Windows XP with Service Pack 3, Windows Vista with Service Pack 1, Windows 7, etc.) you can use Windows Scripting Host as a COM object from your PS script or use VB's Intereact class.
The specifics of how to do it are outside the scope of this answer but you can find numerous examples using the methods I just described by searching on SO or Google.
edit: Just to help you get started you can look here:
Just adding .htaccess in root resolved 404 while refreshing the page in angular 4 apache2.
<IfModule mod_rewrite.c>
RewriteEngine on
# Don't rewrite files or directories
RewriteCond %{REQUEST_FILENAME} -f [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^ - [L]
# Rewrite everything else to index.html
# to allow html5 state links
RewriteRule ^ index.html [L]
</IfModule>
You either use the child selector
So using
#parent > child
Will make only the first level children to have the styles applied. Unfortunately IE6 doesn't support the child selector.
Otherwise you can use
#parent child child
To set another specific styles to children that are more than one level below.
EXISTS
will be faster because once the engine has found a hit, it will quit looking as the condition has proved true.
With IN
, it will collect all the results from the sub-query before further processing.
DateTime.Now.ToShortDateString()
will display only the date part
If you don't want to use SMO (which is better than the solution below, but i want to give an alternative...) you can split your query with this function.
It is:
String proof (example print 'no go ')
private List<string> SplitScriptGo(string script)
{
var result = new List<string>();
int pos1 = 0;
int pos2 = 0;
bool whiteSpace = true;
bool emptyLine = true;
bool inStr = false;
bool inComment1 = false;
bool inComment2 = false;
while (true)
{
while (pos2 < script.Length && Char.IsWhiteSpace(script[pos2]))
{
if (script[pos2] == '\r' || script[pos2] == '\n')
{
emptyLine = true;
inComment1 = false;
}
pos2++;
}
if (pos2 == script.Length)
break;
bool min2 = (pos2 + 1) < script.Length;
bool min3 = (pos2 + 2) < script.Length;
if (!inStr && !inComment2 && min2 && script.Substring(pos2, 2) == "--")
inComment1 = true;
if (!inStr && !inComment1 && min2 && script.Substring(pos2, 2) == "/*")
inComment2 = true;
if (!inComment1 && !inComment2 && script[pos2] == '\'')
inStr = !inStr;
if (!inStr && !inComment1 && !inComment2 && emptyLine
&& (min2 && script.Substring(pos2, 2).ToLower() == "go")
&& (!min3 || char.IsWhiteSpace(script[pos2 + 2]) || script.Substring(pos2 + 2, 2) == "--" || script.Substring(pos2 + 2, 2) == "/*"))
{
if (!whiteSpace)
result.Add(script.Substring(pos1, pos2 - pos1));
whiteSpace = true;
emptyLine = false;
pos2 += 2;
pos1 = pos2;
}
else
{
pos2++;
whiteSpace = false;
if (!inComment2)
emptyLine = false;
}
if (!inStr && inComment2 && pos2 > 1 && script.Substring(pos2 - 2, 2) == "*/")
inComment2 = false;
}
if (!whiteSpace)
result.Add(script.Substring(pos1));
return result;
}
Try this
$(function(){
$("input[type='number']").prop('min',1);
$("input[type='number']").prop('max',10);
});
kw=(EditText)findViewById(R.id.kw);
btn=(Button)findViewById(R.id.btn);
cost=(TextView )findViewById(R.id.cost);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) { cst = Double.valueOf(kw.getText().toString());
cst = cst*0.551;
cost.setText(cst.toString());
}
});
I had the same issue trying to do something the same as you and I fixed it with something similar to Richie Fredicson's answer.
When you run createComponent() it is created with undefined input variables. Then after that when you assign data to those input variables it changes things and causes that error in your child template (in my case it was because I was using the input in an ngIf, which changed once I assigned the input data).
The only way I could find to avoid it in this specific case is to force change detection after you assign the data, however I didn't do it in ngAfterContentChecked().
Your example code is a bit hard to follow but if my solution works for you it would be something like this (in the parent component):
export class ParentComponent implements AfterViewInit {
// I'm assuming you have a WidgetDirective.
@ViewChild(WidgetDirective) widgetHost: WidgetDirective;
constructor(
private componentFactoryResolver: ComponentFactoryResolver,
private changeDetector: ChangeDetectorRef
) {}
ngAfterViewInit() {
renderWidgetInsideWidgetContainer();
}
renderWidgetInsideWidgetContainer() {
let component = this.storeFactory.getWidgetComponent(this.dataSource.ComponentName);
let componentFactory = this.componentFactoryResolver.resolveComponentFactory(component);
let viewContainerRef = this.widgetHost.viewContainerRef;
viewContainerRef.clear();
let componentRef = viewContainerRef.createComponent(componentFactory);
debugger;
// This <IDataBind> type you are using here needs to be changed to be the component
// type you used for the call to resolveComponentFactory() above (if it isn't already).
// It tells it that this component instance if of that type and then it knows
// that WidgetDataContext and WidgetPosition are @Inputs for it.
(<IDataBind>componentRef.instance).WidgetDataContext = this.dataSource.DataContext;
(<IDataBind>componentRef.instance).WidgetPosition = this.dataSource.Position;
this.changeDetector.detectChanges();
}
}
Mine is almost the same as that except I'm using @ViewChildren instead of @ViewChild as I have multiple host elements.
Important step for Event binding on Ajax loading content...
01. First of all unbind or off the event on selector
$(".SELECTOR").off();
02. Add event listener on document level
$(document).on("EVENT", '.SELECTOR', function(event) {
console.log("Selector event occurred");
});
Although there are a lot of good tips here I'd like to answer the question you asked:
So in other words can they work hand in hand just like Apache/Perl or Apache/PHP etc..
YES, you can run Node.js on Apache along side Perl and PHP IF you run it as a CGI module. As of yet, I am unable to find a mod-node for Apache but check out: CGI-Node for Apache here http://www.cgi-node.org/ .
The interesting part about cgi-node is that it uses JavaScript exactly like you would use PHP to generate dynamic content, service up static pages, access SQL database etc. You can even share core JavaScript libraries between the server and the client/browser.
I think the shift to a single language between client and server is happening and JavaScript seems to be a good candidate.
A quick example from cgi-node.org site:
<? include('myJavaScriptFile.js'); ?>
<html>
<body>
<? var helloWorld = 'Hello World!'; ?>
<b><?= helloWorld ?><br/>
<? for( var index = 0; index < 10; index++) write(index + ' '); ?>
</body>
</html>
This outputs:
Hello World!
0 1 2 3 4 5 6 7 8 9
You also have full access to the HTTP request. That includes forms, uploaded files, headers etc.
I am currently running Node.js through the cgi-node module on Godaddy.
CGI-Node.org site has all the documentation to get started.
I know I'm raving about this but it is finally a relief to use something other than PHP. Also, to be able to code JavaScript on both client and server.
Hope this helps.
@RobinL as mentioned in previous comments, you can use chart.series[n].setData(). First you need to make sure you’ve assigned a chart instance to the chart variable, that way it adopts all the properties and methods you need to access and manipulate the chart.
I’ve also used the second parameter of setData() and had it false, to prevent automatic rendering of the chart. This was because I have multiple data series, so I’ll rather update each of them, with render=false, and then running chart.redraw(). This multiplied performance (I’m having 10,000-100,000 data points and refreshing the data set every 50 milliseconds).
Use:
<div id="parent">
<div class="child"></div>
</div>
Style:
#parent {
display: flex;
justify-content: center;
}
If you want to center it horizontally you should write as below:
#parent {
display: flex;
justify-content: center;
align-items: center;
}
If you or some other fox who need to have link with Icon Image and text as link text beside the image see bellow code:
CSS
.linkWithImageIcon{
Display:inline-block;
}
.MyLink{
Background:#FF3300;
width:200px;
height:70px;
vertical-align:top;
display:inline-block; font-weight:bold;
}
.MyLinkText{
/*---The margin depends on how the image size is ---*/
display:inline-block; margin-top:5px;
}
HTML
<a href="#" class="MyLink"><img src="./yourImageIcon.png" /><span class="MyLinkText">SIGN IN</span></a>
if you see the image the white portion is image icon and other is style this way you can create different buttons with any type of Icons you want to design
I had the similar problem with Win-8 and python-3.4 32 bit , I got it resolved by downloading same version from python.org .
Next step will be to hit the repair button and Install the Tk/tkinter Package or Just hit the repair. Now should get Python34/Lib/tkinter Module present. The import tkinter should work ..
If you're using Java 9, there's an easy way with less number of lines without needing to initialize or add
method.
List<String> list = List.of("first", "second", "third");
Try this code:
EndpointImpl impl = (EndpointImpl)Endpoint.publish(address, implementor);
impl.getServer().getEndpoint().getInInterceptors().add(new LoggingInInterceptor());
impl.getServer().getEndpoint().getOutInterceptors().add(new LoggingOutInterceptor());
Inside the logback.xml
you need to put the interface name for webservice:
<appender name="FILE" class="ch.qos.logback.classic.sift.SiftingAppender">
<discriminator
class="com.progressoft.ecc.integration.logging.ThreadNameDiscriminator">
<key>threadName</key>
<defaultValue>unknown</defaultValue>
</discriminator>
<filter class="ch.qos.logback.core.filter.EvaluatorFilter">
<evaluator>
<expression>logger.contains("InterfaceWebServiceSoap")</expression>
</evaluator>
<OnMismatch>DENY</OnMismatch>
<OnMatch>NEUTRAL</OnMatch>
</filter>
<filter class="ch.qos.logback.classic.filter.ThresholdFilter">
<level>TRACE</level>
</filter>
<sift>
<appender name="FILE-${threadName}"
class="ch.qos.logback.core.rolling.RollingFileAppender">
<File>${LOGGING_PATH}/${threadName}.log</File>
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<FileNamePattern>${ARCHIVING_PATH}/%d{yyyy-MM-dd}.${threadName}%i.log.zip
</FileNamePattern>
<MaxHistory>30</MaxHistory>
<TimeBasedFileNamingAndTriggeringPolicy
class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
<MaxFileSize>50MB</MaxFileSize>
</TimeBasedFileNamingAndTriggeringPolicy>
</rollingPolicy>
<encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
<Pattern>%date{dd-MM-yyyy HH:mm:ss.SSS} | %5level | %-60([%logger{53}:%line]): %msg %ex{full} %n</Pattern>
</encoder>
</appender>
</sift>
</appender>
<root>
<level value="ALL" />
<appender-ref ref="FILE" />
</root>
Here is how the default implementation (ASP.NET Framework or ASP.NET Core) works. It uses a Key Derivation Function with random salt to produce the hash. The salt is included as part of the output of the KDF. Thus, each time you "hash" the same password you will get different hashes. To verify the hash the output is split back to the salt and the rest, and the KDF is run again on the password with the specified salt. If the result matches to the rest of the initial output the hash is verified.
Hashing:
public static string HashPassword(string password)
{
byte[] salt;
byte[] buffer2;
if (password == null)
{
throw new ArgumentNullException("password");
}
using (Rfc2898DeriveBytes bytes = new Rfc2898DeriveBytes(password, 0x10, 0x3e8))
{
salt = bytes.Salt;
buffer2 = bytes.GetBytes(0x20);
}
byte[] dst = new byte[0x31];
Buffer.BlockCopy(salt, 0, dst, 1, 0x10);
Buffer.BlockCopy(buffer2, 0, dst, 0x11, 0x20);
return Convert.ToBase64String(dst);
}
Verifying:
public static bool VerifyHashedPassword(string hashedPassword, string password)
{
byte[] buffer4;
if (hashedPassword == null)
{
return false;
}
if (password == null)
{
throw new ArgumentNullException("password");
}
byte[] src = Convert.FromBase64String(hashedPassword);
if ((src.Length != 0x31) || (src[0] != 0))
{
return false;
}
byte[] dst = new byte[0x10];
Buffer.BlockCopy(src, 1, dst, 0, 0x10);
byte[] buffer3 = new byte[0x20];
Buffer.BlockCopy(src, 0x11, buffer3, 0, 0x20);
using (Rfc2898DeriveBytes bytes = new Rfc2898DeriveBytes(password, dst, 0x3e8))
{
buffer4 = bytes.GetBytes(0x20);
}
return ByteArraysEqual(buffer3, buffer4);
}
You can easily add a second legend by adding the line:
ax2.legend(loc=0)
You'll get this:
But if you want all labels on one legend then you should do something like this:
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import rc
rc('mathtext', default='regular')
time = np.arange(10)
temp = np.random.random(10)*30
Swdown = np.random.random(10)*100-10
Rn = np.random.random(10)*100-10
fig = plt.figure()
ax = fig.add_subplot(111)
lns1 = ax.plot(time, Swdown, '-', label = 'Swdown')
lns2 = ax.plot(time, Rn, '-', label = 'Rn')
ax2 = ax.twinx()
lns3 = ax2.plot(time, temp, '-r', label = 'temp')
# added these three lines
lns = lns1+lns2+lns3
labs = [l.get_label() for l in lns]
ax.legend(lns, labs, loc=0)
ax.grid()
ax.set_xlabel("Time (h)")
ax.set_ylabel(r"Radiation ($MJ\,m^{-2}\,d^{-1}$)")
ax2.set_ylabel(r"Temperature ($^\circ$C)")
ax2.set_ylim(0, 35)
ax.set_ylim(-20,100)
plt.show()
Which will give you this:
If you only need to merge a particular directory and leave everything else intact and yet preserve history, you could possibly try this... create a new target-branch
off of the master
before you experiment.
The steps below assume you have two branches target-branch
and source-branch
, and the directory dir-to-merge
that you want to merge is in the source-branch
. Also assume you have other directories like dir-to-retain
in the target that you don't want to change and retain history. Also, assumes there are merge conflicts in the dir-to-merge
.
git checkout target-branch
git merge --no-ff --no-commit -X theirs source-branch
# the option "-X theirs", will pick theirs when there is a conflict.
# the options "--no--ff --no-commit" prevent a commit after a merge, and give you an opportunity to fix other directories you want to retain, before you commit this merge.
# the above, would have messed up the other directories that you want to retain.
# so you need to reset them for every directory that you want to retain.
git reset HEAD dir-to-retain
# verify everything and commit.
The first value is the precision and the second is the scale, so 18,0
is essentially 18 digits with 0 digits after the decimal place. If you had 18,2
for example, you would have 18 digits, two of which would come after the decimal...
example of 18,2: 1234567890123456.12
There is no functional difference between numeric
and decimal
, other that the name and I think I recall that numeric came first, as in an earlier version.
And to answer, "can I add (-10) in that column?" - Yes, you can.
Under Trace properties > Events Selection tab > select show all columns. Now under column filters, you should see the database name. Enter the database name for the Like section and you should see traces only for that database.
It seems that Microsoft themselves prefer <>
to !=
as evidenced in their table constraints. I personally prefer using !=
because I clearly read that as "not equal", but if you enter [field1 != field2]
and save it as a constrait, the next time you query it, it will show up as [field1 <> field2]
. This says to me that the correct way to do it is <>
.
Try this:
package my_default;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.Iterator;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class Test {
public static void main(String[] args) {
try {
// Create Workbook instance holding reference to .xlsx file
XSSFWorkbook workbook = new XSSFWorkbook();
// Get first/desired sheet from the workbook
XSSFSheet sheet = createSheet(workbook, "Sheet 1", false);
// XSSFSheet sheet = workbook.getSheetAt(1);//Don't use this line
// because you get Sheet index (1) is out of range (no sheets)
//Write some information in the cells or do what you want
XSSFRow row1 = sheet.createRow(0);
XSSFCell r1c2 = row1.createCell(0);
r1c2.setCellValue("NAME");
XSSFCell r1c3 = row1.createCell(1);
r1c3.setCellValue("AGE");
//Save excel to HDD Drive
File pathToFile = new File("D:\\test.xlsx");
if (!pathToFile.exists()) {
pathToFile.createNewFile();
}
FileOutputStream fos = new FileOutputStream(pathToFile);
workbook.write(fos);
fos.close();
System.out.println("Done");
} catch (Exception e) {
e.printStackTrace();
}
}
private static XSSFSheet createSheet(XSSFWorkbook wb, String prefix, boolean isHidden) {
XSSFSheet sheet = null;
int count = 0;
for (int i = 0; i < wb.getNumberOfSheets(); i++) {
String sName = wb.getSheetName(i);
if (sName.startsWith(prefix))
count++;
}
if (count > 0) {
sheet = wb.createSheet(prefix + count);
} else
sheet = wb.createSheet(prefix);
if (isHidden)
wb.setSheetHidden(wb.getNumberOfSheets() - 1, XSSFWorkbook.SHEET_STATE_VERY_HIDDEN);
return sheet;
}
}
If you would want to change the logging level of all the loggers use the below method. This will enumerate over all the loggers and change the logging level to given level. Please make sure that you DO NOT have log4j.appender.loggerName.Threshold=DEBUG
property set in your log4j.properties
file.
public static void changeLogLevel(Level level) {
Enumeration<?> loggers = LogManager.getCurrentLoggers();
while(loggers.hasMoreElements()) {
Logger logger = (Logger) loggers.nextElement();
logger.setLevel(level);
}
}
This may also happen if you have a slash before the folder name:
path = '/folder1/folder2'
OSError: [Errno 13] Permission denied: '/folder1'
comes up with an error but this one works fine:
path = 'folder1/folder2'
You had thead
in your selector, but there is no thead
in your table. Also you had your selectors backwards. As you mentioned above, you wanted to be adding the tr
class to the th
, not vice-versa (although your comment seems to contradict what you wrote up above).
$('tr th').each(function(index){ if($('tr td').eq(index).attr('class') != ''){ // get the class of the td var tdClass = $('tr td').eq(index).attr('class'); // add it to this th $(this).addClass(tdClass ); } });
There are numerous ways to store credentials while still using boto3.resource(). I'm using the AWS CLI method myself. It works perfectly.
$observe() is a method on the Attributes object, and as such, it can only be used to observe/watch the value change of a DOM attribute. It is only used/called inside directives. Use $observe when you need to observe/watch a DOM attribute that contains interpolation (i.e., {{}}'s).
E.g., attr1="Name: {{name}}"
, then in a directive: attrs.$observe('attr1', ...)
.
(If you try scope.$watch(attrs.attr1, ...)
it won't work because of the {{}}s -- you'll get undefined
.) Use $watch for everything else.
$watch() is more complicated. It can observe/watch an "expression", where the expression can be either a function or a string. If the expression is a string, it is $parse'd (i.e., evaluated as an Angular expression) into a function. (It is this function that is called every digest cycle.) The string expression can not contain {{}}'s. $watch is a method on the Scope object, so it can be used/called wherever you have access to a scope object, hence in
Because strings are evaluated as Angular expressions, $watch is often used when you want to observe/watch a model/scope property. E.g., attr1="myModel.some_prop"
, then in a controller or link function: scope.$watch('myModel.some_prop', ...)
or scope.$watch(attrs.attr1, ...)
(or scope.$watch(attrs['attr1'], ...)
).
(If you try attrs.$observe('attr1')
you'll get the string myModel.some_prop
, which is probably not what you want.)
As discussed in comments on @PrimosK's answer, all $observes and $watches are checked every digest cycle.
Directives with isolate scopes are more complicated. If the '@' syntax is used, you can $observe or $watch a DOM attribute that contains interpolation (i.e., {{}}'s). (The reason it works with $watch is because the '@' syntax does the interpolation for us, hence $watch sees a string without {{}}'s.) To make it easier to remember which to use when, I suggest using $observe for this case also.
To help test all of this, I wrote a Plunker that defines two directives. One (d1
) does not create a new scope, the other (d2
) creates an isolate scope. Each directive has the same six attributes. Each attribute is both $observe'd and $watch'ed.
<div d1 attr1="{{prop1}}-test" attr2="prop2" attr3="33" attr4="'a_string'"
attr5="a_string" attr6="{{1+aNumber}}"></div>
Look at the console log to see the differences between $observe and $watch in the linking function. Then click the link and see which $observes and $watches are triggered by the property changes made by the click handler.
Notice that when the link function runs, any attributes that contain {{}}'s are not evaluated yet (so if you try to examine the attributes, you'll get undefined
). The only way to see the interpolated values is to use $observe (or $watch if using an isolate scope with '@'). Therefore, getting the values of these attributes is an asynchronous operation. (And this is why we need the $observe and $watch functions.)
Sometimes you don't need $observe or $watch. E.g., if your attribute contains a number or a boolean (not a string), just evaluate it once: attr1="22"
, then in, say, your linking function: var count = scope.$eval(attrs.attr1)
. If it is just a constant string – attr1="my string"
– then just use attrs.attr1
in your directive (no need for $eval()).
See also Vojta's google group post about $watch expressions.
You still have access to StreamWriter
:
using (System.IO.StreamWriter file = new System.IO.StreamWriter(@"\hereIam.txt"))
{
file.WriteLine(sb.ToString()); // "sb" is the StringBuilder
}
From the MSDN documentation: Writing to a Text File (Visual C#).
For newer versions of the .NET Framework (Version 2.0. onwards), this can be achieved with one line using the File.WriteAllText
method.
System.IO.File.WriteAllText(@"C:\TextFile.txt", stringBuilder.ToString());
My problem wasn't that the connection string I was providing was wrong, or that the connection string in the app.config I thought I was using was wrong, but that I was using the wrong app.config.
Connection object is for illustration only. The DataAdapter is the key bit:
Dim strSql As String = "SELECT EmpCode,EmpID,EmpName FROM dbo.Employee"
Dim dtb As New DataTable
Using cnn As New SqlConnection(connectionString)
cnn.Open()
Using dad As New SqlDataAdapter(strSql, cnn)
dad.Fill(dtb)
End Using
cnn.Close()
End Using
APScheduler might be what you are after.
from datetime import date
from apscheduler.scheduler import Scheduler
# Start the scheduler
sched = Scheduler()
sched.start()
# Define the function that is to be executed
def my_job(text):
print text
# The job will be executed on November 6th, 2009
exec_date = date(2009, 11, 6)
# Store the job in a variable in case we want to cancel it
job = sched.add_date_job(my_job, exec_date, ['text'])
# The job will be executed on November 6th, 2009 at 16:30:05
job = sched.add_date_job(my_job, datetime(2009, 11, 6, 16, 30, 5), ['text'])
https://apscheduler.readthedocs.io/en/latest/
You can just get it to schedule another run by building that into the function you are scheduling.
You can use this method for any minute / hour / period (aka am/pm) combination:
- (NSDate *)todayModifiedWithHours:(NSString *)hours
minutes:(NSString *)minutes
andPeriod:(NSString *)period
{
NSDate *todayModified = NSDate.date;
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *components = [calendar components:NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit|NSMinuteCalendarUnit fromDate:todayModified];
[components setMinute:minutes.intValue];
int hour = 0;
if ([period.uppercaseString isEqualToString:@"AM"]) {
if (hours.intValue == 12) {
hour = 0;
}
else {
hour = hours.intValue;
}
}
else if ([period.uppercaseString isEqualToString:@"PM"]) {
if (hours.intValue != 12) {
hour = hours.intValue + 12;
}
else {
hour = 12;
}
}
[components setHour:hour];
todayModified = [calendar dateFromComponents:components];
return todayModified;
}
Requested Example:
NSDate *todayAt10AM = [self todayModifiedWithHours:@"10"
minutes:@"00"
andPeriod:@"am"];
Here's a better version of the table, that also includes a column for modules.
A private member (i
) is only accessible within the same class as it is declared.
A member with no access modifier (j
) is only accessible within classes in the same package.
A protected member (k
) is accessible within all classes in the same package and within subclasses in other packages.
A public member (l
) is accessible to all classes (unless it resides in a module that does not export the package it is declared in).
Access modifiers is a tool to help you to prevent accidentally breaking encapsulation(*). Ask yourself if you intend the member to be something that's internal to the class, package, class hierarchy or not internal at all, and choose access level accordingly.
Examples:
long internalCounter
should probably be private since it's mutable and an implementation detail.void beforeRender()
method called right before rendering and used as a hook in subclasses should be protected.void saveGame(File dst)
method which is called from the GUI code should be public.Check with your bean class. Column data type and bean datatype must be same.
I have to agree with the comments above, that you can't call a file, but you could load a JS file like this, I'm unsure if it answers your question but it may help... oh and I've used a link instead of a button in my example...
<a href='linkhref.html' id='mylink'>click me</a>
<script type="text/javascript">
var myLink = document.getElementById('mylink');
myLink.onclick = function(){
var script = document.createElement("script");
script.type = "text/javascript";
script.src = "Public/Scripts/filename.js.";
document.getElementsByTagName("head")[0].appendChild(script);
return false;
}
</script>
__str__
must return string object whereas __repr__
can return any python expression.__str__
implementation is missing then __repr__
function is used as fallback. There is no fallback if __repr__
function implementation is missing.__repr__
function is returning String representation of the object, we can skip implementation of __str__
function.Source: https://www.journaldev.com/22460/python-str-repr-functions
For the current release of Go:
Click the link above to visit the Go project's downloads page and select the binary distribution that matches your operating system and processor architecture.
Official binary distributions are available for the FreeBSD, Linux, macOS, and Windows operating systems and the 32-bit (386) and 64-bit (amd64) x86 processor architectures.
If a binary distribution is not available for your combination of operating system and architecture you may want to try installing from source or installing gccgo instead of gc.
A fixed point number has a specific number of bits (or digits) reserved for the integer part (the part to the left of the decimal point) and a specific number of bits reserved for the fractional part (the part to the right of the decimal point). No matter how large or small your number is, it will always use the same number of bits for each portion. For example, if your fixed point format was in decimal IIIII.FFFFF
then the largest number you could represent would be 99999.99999
and the smallest non-zero number would be 00000.00001
. Every bit of code that processes such numbers has to have built-in knowledge of where the decimal point is.
A floating point number does not reserve a specific number of bits for the integer part or the fractional part. Instead it reserves a certain number of bits for the number (called the mantissa or significand) and a certain number of bits to say where within that number the decimal place sits (called the exponent). So a floating point number that took up 10 digits with 2 digits reserved for the exponent might represent a largest value of 9.9999999e+50
and a smallest non-zero value of 0.0000001e-49
.
The solution is
@RequestMapping(value = "processing", method = RequestMethod.GET)
public @ResponseBody ProcessResponse processData(@RequestParam("workflow") final String workflow,
@RequestParam("conf") final String value, @RequestParam("dc") final String dc, HttpServletRequest request) {
System.out.println(workflow);
System.out.println(value);
System.out.println(dc);
System.out.println(request.getRemoteAddr());
// some other code
}
Add HttpServletRequest request
to your method definition and then use the Servlet API
Spring Documentation here said in
15.3.2.3 Supported handler method arguments and return types
Handler methods that are annotated with @RequestMapping can have very flexible signatures.
Most of them can be used in arbitrary order (see below for more details).
Request or response objects (Servlet API). Choose any specific request or response type,
for example ServletRequest or HttpServletRequest
Okay, this question was a year ago but I recently got this problem as well.
So what I did :
When I did the first two steps it still doesn't remove the error so the last step is important. It didn't automatically change the build path for jre.
Try this method to get path of original
image captured by camera.
public String getOriginalImagePath() {
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = getActivity().managedQuery(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
projection, null, null, null);
int column_index_data = cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToLast();
return cursor.getString(column_index_data);
}
This method will return path of the last image captured by camera. So this path would be of original image not of thumbnail bitmap.
MySQL has a function called ADDTIME
for adding two times together - so you can do the whole thing in MySQL (provided you're using >= MySQL 4.1.3).
Something like (untested):
SELECT * FROM my_table WHERE ADDTIME(endTime + '0:30:00') < CONVERT_TZ(NOW(), @@global.time_zone, 'GMT')
Simple but powerful email validation for check email syntax :
var EmailId = document.getElementById('Email').value;
var emailfilter = /^[\w._-]+[+]?[\w._-]+@[\w.-]+\.[a-zA-Z]{2,6}$/;
if((EmailId != "") && (!(emailfilter.test(EmailId ) ) )) {
msg+= "Enter the valid email address!<br />";
}
It allows servlets to have multiple servlet mappings:
<servlet>
<servlet-name>Servlet1</servlet-name>
<servlet-path>foo.Servlet</servlet-path>
</servlet>
<servlet-mapping>
<servlet-name>Servlet1</servlet-name>
<url-pattern>/enroll</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>Servlet1</servlet-name>
<url-pattern>/pay</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>Servlet1</servlet-name>
<url-pattern>/bill</url-pattern>
</servlet-mapping>
It allows filters to be mapped on the particular servlet:
<filter-mapping>
<filter-name>Filter1</filter-name>
<servlet-name>Servlet1</servlet-name>
</filter-mapping>
Your proposal would support neither of them. Note that the web.xml
is read and parsed only once during application's startup, not on every HTTP request as you seem to think.
Since Servlet 3.0, there's the @WebServlet
annotation which minimizes this boilerplate:
@WebServlet("/enroll")
public class Servlet1 extends HttpServlet {
from collections import Counter
n = int(input())
data = sorted([int(i) for i in input().split()])
sorted(sorted(Counter(data).items()), key = lambda x: x[1], reverse = True)[0][0]
print(Mean)
The Counter(data)
counts the frequency and returns a defaultdict. sorted(Counter(data).items())
sorts using the keys, not the frequency. Finally, need to sorted the frequency using another sorted with key = lambda x: x[1]
. The reverse tells Python to sort the frequency from the largest to the smallest.
The problem with push command is that you your local and remote repository doesn't match. IF you initialize readme by default when creating new repository from git hub, then, master branch is automatically created. However, when you try to push that has no any branch. you cannot push... So, the best practice is to create repo without default readme initialization.
A StaticResource will be resolved and assigned to the property during the loading of the XAML which occurs before the application is actually run. It will only be assigned once and any changes to resource dictionary ignored.
A DynamicResource assigns an Expression object to the property during loading but does not actually lookup the resource until runtime when the Expression object is asked for the value. This defers looking up the resource until it is needed at runtime. A good example would be a forward reference to a resource defined later on in the XAML. Another example is a resource that will not even exist until runtime. It will update the target if the source resource dictionary is changed.
As elements are yet ordered, you don't have to build a map, there's a fast solution :
var newarr = [arr[0]];
for (var i=1; i<arr.length; i++) {
if (arr[i]!=arr[i-1]) newarr.push(arr[i]);
}
If your array weren't sorted, you would use a map :
var newarr = (function(arr){
var m = {}, newarr = []
for (var i=0; i<arr.length; i++) {
var v = arr[i];
if (!m[v]) {
newarr.push(v);
m[v]=true;
}
}
return newarr;
})(arr);
Note that this is, by far, much faster than the accepted answer.
If you need this procedure for variable fieldnames instead of id
this might be helpful:
DROP PROCEDURE IF EXISTS update_auto_increment;
DELIMITER //
CREATE PROCEDURE update_auto_increment (_table VARCHAR(128), _fieldname VARCHAR(128))
BEGIN
DECLARE _max_stmt VARCHAR(1024);
DECLARE _stmt VARCHAR(1024);
SET @inc := 0;
SET @MAX_SQL := CONCAT('SELECT IFNULL(MAX(',_fieldname,'), 0) + 1 INTO @inc FROM ', _table);
PREPARE _max_stmt FROM @MAX_SQL;
EXECUTE _max_stmt;
DEALLOCATE PREPARE _max_stmt;
SET @SQL := CONCAT('ALTER TABLE ', _table, ' AUTO_INCREMENT = ', @inc);
PREPARE _stmt FROM @SQL;
EXECUTE _stmt;
DEALLOCATE PREPARE _stmt;
END //
DELIMITER ;
CALL update_auto_increment('your_table_name', 'autoincrement_fieldname');
"System tray" application is just a regular win forms application, only difference is that it creates a icon in windows system tray area. In order to create sys.tray icon use NotifyIcon component , you can find it in Toolbox(Common controls), and modify it's properties: Icon, tool tip. Also it enables you to handle mouse click and double click messages.
And One more thing , in order to achieve look and feels or standard tray app. add followinf lines on your main form show event:
private void MainForm_Shown(object sender, EventArgs e)
{
WindowState = FormWindowState.Minimized;
Hide();
}
The short answer: no.
The long answer:
Fixed formats work better for HTML emails. In my experience you're best off pretending it's 1999 when it comes to HTML emails. Be explicit and use HTML attributes (width="650") where ever possible in your table definitions, not CSS (style="width:650px"). Use fixed widths, no percentages. A table width of 650 pixels wide is a safe bet. Use inline CSS to set text properties.
It's not a matter of what works in "HTML emails", but rather the plethora of email clients and their limited (and sometimes deliberately so in the case of Gmail, Hotmail etc) ability to render HTML.
use git bundle, or clone
copying the git directory is not a good solution because it is not atomic. If you have a large repository that takes a long time to copy and someone pushes to your repository, it will affect your back up. Cloning or making a bundle will not have this problem.
Why not:
public class MyClass
{
private Dictionary<string, int> _myCollection = new Dictionary<string, int>() { { "A", 1 }, { "B", 2 }, { "C", 3 } };
public IEnumerable<KeyValuePair<string,int>> MyCollection
{
get { return _myCollection.AsEnumerable<KeyValuePair<string, int>>(); }
}
}
I think this should work...
var query = from m in context.MyTable
where m.MyContainerId == '1' // or what ever the foreign key name is...
select m;
var count = query.Count();
As Uriel says, it is meant for a method in an abstract class that should be implemented in child class, but can be used to indicate a TODO as well.
There is an alternative for the first use case: Abstract Base Classes. Those help creating abstract classes.
Here's a Python 3 example:
class C(abc.ABC):
@abc.abstractmethod
def my_abstract_method(self, ...):
...
When instantiating C
, you'll get an error because my_abstract_method
is abstract. You need to implement it in a child class.
TypeError: Can't instantiate abstract class C with abstract methods my_abstract_method
Subclass C
and implement my_abstract_method
.
class D(C):
def my_abstract_method(self, ...):
...
Now you can instantiate D
.
C.my_abstract_method
does not have to be empty. It can be called from D
using super()
.
An advantage of this over NotImplementedError
is that you get an explicit Exception
at instantiation time, not at method call time.
Add it in your root build.gradle at the end of repositories:
allprojects {
repositories {
...
maven { url "https://jitpack.io" }
}}
and then add dependency
dependencies {
compile 'com.github.varunest:sparkbutton:1.0.5'
}
<com.varunest.sparkbutton.SparkButton
android:id="@+id/spark_button"
android:layout_width="40dp"
android:layout_height="40dp"
app:sparkbutton_activeImage="@drawable/active_image"
app:sparkbutton_inActiveImage="@drawable/inactive_image"
app:sparkbutton_iconSize="40dp"
app:sparkbutton_primaryColor="@color/primary_color"
app:sparkbutton_secondaryColor="@color/secondary_color" />
SparkButton button = new SparkButtonBuilder(context)
.setActiveImage(R.drawable.active_image)
.setInActiveImage(R.drawable.inactive_image)
.setDisabledImage(R.drawable.disabled_image)
.setImageSizePx(getResources().getDimensionPixelOffset(R.dimen.button_size))
.setPrimaryColor(ContextCompat.getColor(context, R.color.primary_color))
.setSecondaryColor(ContextCompat.getColor(context, R.color.secondary_color))
.build();
With my solution you're able to get something similar:
Here is bulletproff solution:
Your html:
<input class='calendarIcon'/>
Your SVG: i used fa-calendar-alt
(any IDE may open svg image as shown below)
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 448 512"><path d="M148 288h-40c-6.6 0-12-5.4-12-12v-40c0-6.6 5.4-12 12-12h40c6.6 0 12 5.4 12 12v40c0 6.6-5.4 12-12 12zm108-12v-40c0-6.6-5.4-12-12-12h-40c-6.6 0-12 5.4-12 12v40c0 6.6 5.4 12 12 12h40c6.6 0 12-5.4 12-12zm96 0v-40c0-6.6-5.4-12-12-12h-40c-6.6 0-12 5.4-12 12v40c0 6.6 5.4 12 12 12h40c6.6 0 12-5.4 12-12zm-96 96v-40c0-6.6-5.4-12-12-12h-40c-6.6 0-12 5.4-12 12v40c0 6.6 5.4 12 12 12h40c6.6 0 12-5.4 12-12zm-96 0v-40c0-6.6-5.4-12-12-12h-40c-6.6 0-12 5.4-12 12v40c0 6.6 5.4 12 12 12h40c6.6 0 12-5.4 12-12zm192 0v-40c0-6.6-5.4-12-12-12h-40c-6.6 0-12 5.4-12 12v40c0 6.6 5.4 12 12 12h40c6.6 0 12-5.4 12-12zm96-260v352c0 26.5-21.5 48-48 48H48c-26.5 0-48-21.5-48-48V112c0-26.5 21.5-48 48-48h48V12c0-6.6 5.4-12 12-12h40c6.6 0 12 5.4 12 12v52h128V12c0-6.6 5.4-12 12-12h40c6.6 0 12 5.4 12 12v52h48c26.5 0 48 21.5 48 48zm-48 346V160H48v298c0 3.3 2.7 6 6 6h340c3.3 0 6-2.7 6-6z"/></svg>
To use it at css background-image you gotta encode the svg to address valid string. I used this tool
As far as you got all stuff you need, you're coming to css
.calendarIcon{
//your url will be something like this:
background-image: url("data:image/svg+xml,***<here place encoded svg>***");
background-repeat: no-repeat;
}
Note: these styling wont have any effect on encoded svg image
.{
fill: #f00; //neither this
background-color: #f00; //nor this
}
because all changes over the image must be applied directly to its svg code
<svg xmlns="" path="" fill="#f00"/></svg>
To achive the location righthand i copied some Bootstrap spacing and my final css get the next look:
.calendarIcon{
background-image: url("data:image/svg+xml,%3Csvg...svg%3E");
background-repeat: no-repeat;
padding-right: calc(1.5em + 0.75rem);
background-position: center right calc(0.375em + 0.1875rem);
background-size: calc(0.75em + 0.375rem) calc(0.75em + 0.375rem);
}
The accepted answer does not work in Jupyter (at least when using some libraries).
The Javascript solutions here only hide warnings that are already showing but not warnings that would be shown in the future.
To hide/unhide warnings in Jupyter and JupyterLab I wrote the following script that essentially toggles css to hide/unhide warnings.
%%javascript
(function(on) {
const e=$( "<a>Setup failed</a>" );
const ns="js_jupyter_suppress_warnings";
var cssrules=$("#"+ns);
if(!cssrules.length) cssrules = $("<style id='"+ns+"' type='text/css'>div.output_stderr { } </style>").appendTo("head");
e.click(function() {
var s='Showing';
cssrules.empty()
if(on) {
s='Hiding';
cssrules.append("div.output_stderr, div[data-mime-type*='.stderr'] { display:none; }");
}
e.text(s+' warnings (click to toggle)');
on=!on;
}).click();
$(element).append(e);
})(true);
I've met same problem and fixed it changing connection string like below. Write
'DRIVER={ODBC Driver 13 for SQL Server}'
instead of
'DRIVER={SQL Server}'
Call the child activity Intent using the startActivityForResult() method call
There is an example of this here: http://developer.android.com/training/notepad/notepad-ex2.html
and in the "Returning a Result from a Screen" of this: http://developer.android.com/guide/faq/commontasks.html#opennewscreen
A basically full command is like git push <remote> <local_ref>:<remote_ref>
. If you run just git push
, git does not know what to do exactly unless you have made some config that helps git to make a decision. In a git repo, we can setup multiple remotes. Also we can push a local ref to any remote ref. The full command is the most straightforward way to make a push. If you want to type fewer words, you have to config first, like --set-upstream.
You can't. If you have a method called isBiggerThanMaxLong(long)
it should always return false
.
If you were to increment the bits of Long.MAX_VALUE
, the next value should be Long.MIN_VALUE
. Read up on twos-complement and that should tell you why.
The accepted answer (setting an explicit width in pixels) makes it hard to make changes, and breaks when your users use a different font size. Using CSS tables, on the other hand, works great:
form { display: table; }_x000D_
p { display: table-row; }_x000D_
label { display: table-cell; }_x000D_
input { display: table-cell; }
_x000D_
<form>_x000D_
<p>_x000D_
<label for="a">Short label:</label>_x000D_
<input id="a" type="text">_x000D_
</p>_x000D_
<p>_x000D_
<label for="b">Very very very long label:</label>_x000D_
<input id="b" type="text">_x000D_
</p>_x000D_
</form>
_x000D_
Here's a JSFiddle: http://jsfiddle.net/DaS39/1/
And if you need the labels right-aligned, just add text-align: right
to the labels: http://jsfiddle.net/DaS39/
EDIT: One more quick note: CSS tables also let you play with columns: for example, if you want to make the input fields take as much space as possible, you can add the following in your form
<div style="display: table-column;"></div>
<div style="display: table-column; width:100%;"></div>
you may want to add white-space: nowrap
to the labels
in that case.
MS provides the OpenXML SDK V 2.5 - see https://msdn.microsoft.com/en-us/library/bb448854(v=office.15).aspx
This can read+write MS Office files (including Excel)...
Another option see http://www.codeproject.com/KB/office/OpenXML.aspx
IF you need more like rendering, formulas etc. then there are different commercial libraries like Aspose and Flexcel...
For a Fragment you can simply add
getActivity().onBackPressed();
to your code
SDKMAN! is a great tool for using multiple versions of Java, Gradle, Groovy, Kotlin, and other JVM tools on Mac OS. Installation and usage doc are plainly on the main site.
(I have no affiliation, just a happy user).
As an example usage, if I type the following in a Terminal window, there is a list of available Java SDK versions (edited for brevity):
$ sdk list java
Available Java Versions
+ 9ea170
> + 8u131
7u141-zulu
Here +
denotes that the version is installed. >
denotes which version is currently in use. To install a version:
$ sdk install java 7u141-zulu
To use a version in this Terminal window:
$ sdk use java 9ea170
For this you would have to detect screen size. That is not possible with CSS or HTML; you need JavaScript. Here is the Mozilla Developer Center entry on window properties https://developer.mozilla.org/en/DOM/window#Properties
Detect the available height and position accordingly.
You could call this method
+(id)stringWithUTF8String:(const char *)bytes.
Also, another solution is ensuring your controls are created in UI thread, not by a background worker thread for example.
Basically Repartition allows you to increase or decrease the number of partitions. Repartition re-distributes the data from all the partitions and this leads to full shuffle which is very expensive operation.
Coalesce is the optimized version of Repartition where you can only reduce the number of partitions. As we are only able to reduce the number of partitions what it does is merge some of the partitions to be a single partition. By merging partitions, the movement of the data across the partition is lower compared to Repartition. So in Coalesce is minimum data movement but saying that coalesce does not do data movement is completely wrong statement.
Other thing is in repartition by providing the number of partitions, it tries to redistribute the data uniformly on all the partitions while in case of Coalesce we could still have skew data in some cases.
var interval = $interval(function() {
console.log('say hello');
}, 1000);
$interval.cancel(interval);
The form
object isn't changing, only the name
property is
updated fiddle
function MyController($scope) {
$scope.form = {
name: 'my name',
}
$scope.changeCount = 0;
$scope.$watch('form.name', function(newVal, oldVal){
console.log('changed');
$scope.changeCount++;
});
}
There you have it :)
public static void Main()
{
SetTimer();
Console.WriteLine("\nPress the Enter key to exit the application...\n");
Console.WriteLine("The application started at {0:HH:mm:ss.fff}", DateTime.Now);
Console.ReadLine();
aTimer.Stop();
aTimer.Dispose();
Console.WriteLine("Terminating the application...");
}
private static void SetTimer()
{
// Create a timer with a two second interval.
aTimer = new System.Timers.Timer(2000);
// Hook up the Elapsed event for the timer.
aTimer.Elapsed += OnTimedEvent;
aTimer.AutoReset = true;
aTimer.Enabled = true;
}
private static void OnTimedEvent(Object source, ElapsedEventArgs e)
{
Console.WriteLine("The Elapsed event was raised at {0:HH:mm:ss.fff}",
e.SignalTime);
}
set myPATH="C:\Users\DEB\Downloads\10.1.1.0.4"
cd %myPATH%
The single quotes do not indicate a string, they make it starts: 'C:\
instead of C:\
so
%name%
is the usual syntax for expanding a variable, the !name!
syntax needs to be enabled using the command setlocal ENABLEDELAYEDEXPANSION
first, or by running the command prompt with CMD /V:ON
.
Don't use PATH as your name, it is a system name that contains all the locations of executable programs. If you overwrite it, random bits of your script will stop working. If you intend to change it, you need to do set PATH=%PATH%;C:\Users\DEB\Downloads\10.1.1.0.4
to keep the current PATH content, and add something to the end.
I created a new AutomapperProfile class. It extends Profile. We have over 100 projects in our solution. Many projects have an AutomapperProfile class, but this one was new to this existing project. However, I did find what I had to do to fix this issue for us. There is a Binding project. Within the Initialization there is this code:
var mappingConfig = new List<Action<IConfiguration>>();
// Initialize the Automapper Configuration for all Known Assemblies
mappingConfig.AddRange( new List<Action<IConfiguration>>
{
ConfigureProfilesInAssemblyOfType<Application.Administration.AutomapperProfile>,
//...
I had to add ConfigureProfilesInAssemblyOfType<MyNewNamespace.AutomapperProfile>
Note that ConfigureProfilesInAssemblyOfType looks like this:
private static void ConfigureProfilesInAssemblyOfType<T>( IConfiguration configuration )
{
var log = LogProvider.Get( typeof (AutomapperConfiguration) );
// The Automapper Profile Type
var automapperProfileType = typeof (Profile);
// The Assembly containing the type
var assembly = typeof (T).Assembly;
log.Debug( "Scanning " + assembly.FullName );
// Configure any Profile classes found in the assembly containing the type.
assembly.GetTypes()
.Where( automapperProfileType.IsAssignableFrom ).ToList()
.ForEach( x =>
{
log.Debug( "Adding Profile '" + x.FullName + "'" );
configuration.AddProfile( Activator.CreateInstance( x ) as Profile );
} );
}
Best regards, -Jeff
This regex will split word by space like space, tab, line break:
String[] str = s.split("\\s+");
War -
distribute Java-based web applications. A WAR has the same file structure as a JAR file, which is a single compressed file that contains multiple files bundled inside it.
Jar -
The .jar files contain libraries, resources and accessories files like property files.
WAR files are used to combine JSPs, servlets, Java class files, XML files, javascript libraries, JAR libraries, static web pages, and any other resources needed to run the application.
"Attach debugger to Android process" icon shoud be used in case when you set custom "android:process" in your Manifest file.
In my case I should select suitable process and click OK button just after "Wait for debugger" dialog appears.
As of Firefox 12 they now support line breaks using the line feed HTML entity:
<span title="First line Second line">Test</span>
This works in IE and is the correct according to the HTML5 spec for the title attribute.
You can use both !=
or <>
.
However, note that !=
is preferred where <>
is deprecated.
Something like this?
if so, type the HTML ✔
And ✓
gives a lighter one:
✓
@karim79 has the right answer, but I had to rewrite his example to suit my purposes. His example assumes that the name of the submitted field is known and can be hard coded in. I took that a step further and made a function that will tell me if any files were uploaded without having to know the name of the upload field.
/**
* Tests all upload fields to determine whether any files were submitted.
*
* @return boolean
*/
function files_uploaded() {
// bail if there were no upload forms
if(empty($_FILES))
return false;
// check for uploaded files
$files = $_FILES['files']['tmp_name'];
foreach( $files as $field_title => $temp_name ){
if( !empty($temp_name) && is_uploaded_file( $temp_name )){
// found one!
return true;
}
}
// return false if no files were found
return false;
}
You can use the java.time
package (since Java8 and late) to get start/end of day/week/month.
The util class example below:
import org.junit.Test;
import java.time.DayOfWeek;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAdjusters;
import java.util.Date;
public class DateUtil {
private static final ZoneId DEFAULT_ZONE_ID = ZoneId.of("UTC");
public static LocalDateTime startOfDay() {
return LocalDateTime.now(DEFAULT_ZONE_ID).with(LocalTime.MIN);
}
public static LocalDateTime endOfDay() {
return LocalDateTime.now(DEFAULT_ZONE_ID).with(LocalTime.MAX);
}
public static boolean belongsToCurrentDay(final LocalDateTime localDateTime) {
return localDateTime.isAfter(startOfDay()) && localDateTime.isBefore(endOfDay());
}
//note that week starts with Monday
public static LocalDateTime startOfWeek() {
return LocalDateTime.now(DEFAULT_ZONE_ID)
.with(LocalTime.MIN)
.with(TemporalAdjusters.previousOrSame(DayOfWeek.MONDAY));
}
//note that week ends with Sunday
public static LocalDateTime endOfWeek() {
return LocalDateTime.now(DEFAULT_ZONE_ID)
.with(LocalTime.MAX)
.with(TemporalAdjusters.nextOrSame(DayOfWeek.SUNDAY));
}
public static boolean belongsToCurrentWeek(final LocalDateTime localDateTime) {
return localDateTime.isAfter(startOfWeek()) && localDateTime.isBefore(endOfWeek());
}
public static LocalDateTime startOfMonth() {
return LocalDateTime.now(DEFAULT_ZONE_ID)
.with(LocalTime.MIN)
.with(TemporalAdjusters.firstDayOfMonth());
}
public static LocalDateTime endOfMonth() {
return LocalDateTime.now(DEFAULT_ZONE_ID)
.with(LocalTime.MAX)
.with(TemporalAdjusters.lastDayOfMonth());
}
public static boolean belongsToCurrentMonth(final LocalDateTime localDateTime) {
return localDateTime.isAfter(startOfMonth()) && localDateTime.isBefore(endOfMonth());
}
public static long toMills(final LocalDateTime localDateTime) {
return localDateTime.atZone(DEFAULT_ZONE_ID).toInstant().toEpochMilli();
}
public static Date toDate(final LocalDateTime localDateTime) {
return Date.from(localDateTime.atZone(DEFAULT_ZONE_ID).toInstant());
}
public static String toString(final LocalDateTime localDateTime) {
return localDateTime.format(DateTimeFormatter.ISO_DATE_TIME);
}
@Test
public void test() {
//day
final LocalDateTime now = LocalDateTime.now();
System.out.println("Now: " + toString(now) + ", in mills: " + toMills(now));
System.out.println("Start of day: " + toString(startOfDay()));
System.out.println("End of day: " + toString(endOfDay()));
System.out.println("Does '" + toString(now) + "' belong to the current day? > " + belongsToCurrentDay(now));
final LocalDateTime yesterday = now.minusDays(1);
System.out.println("Does '" + toString(yesterday) + "' belong to the current day? > " + belongsToCurrentDay(yesterday));
final LocalDateTime tomorrow = now.plusDays(1);
System.out.println("Does '" + toString(tomorrow) + "' belong to the current day? > " + belongsToCurrentDay(tomorrow));
//week
System.out.println("Start of week: " + toString(startOfWeek()));
System.out.println("End of week: " + toString(endOfWeek()));
System.out.println("Does '" + toString(now) + "' belong to the current week? > " + belongsToCurrentWeek(now));
final LocalDateTime previousWeek = now.minusWeeks(1);
System.out.println("Does '" + toString(previousWeek) + "' belong to the current week? > " + belongsToCurrentWeek(previousWeek));
final LocalDateTime nextWeek = now.plusWeeks(1);
System.out.println("Does '" + toString(nextWeek) + "' belong to the current week? > " + belongsToCurrentWeek(nextWeek));
//month
System.out.println("Start of month: " + toString(startOfMonth()));
System.out.println("End of month: " + toString(endOfMonth()));
System.out.println("Does '" + toString(now) + "' belong to the current month? > " + belongsToCurrentMonth(now));
final LocalDateTime previousMonth = now.minusMonths(1);
System.out.println("Does '" + toString(previousMonth) + "' belong to the current month? > " + belongsToCurrentMonth(previousMonth));
final LocalDateTime nextMonth = now.plusMonths(1);
System.out.println("Does '" + toString(nextMonth) + "' belong to the current month? > " + belongsToCurrentMonth(nextMonth));
}
}
Test output:
Now: 2020-02-16T22:12:49.957, in mills: 1581891169957
Start of day: 2020-02-16T00:00:00
End of day: 2020-02-16T23:59:59.999999999
Does '2020-02-16T22:12:49.957' belong to the current day? > true
Does '2020-02-15T22:12:49.957' belong to the current day? > false
Does '2020-02-17T22:12:49.957' belong to the current day? > false
Start of week: 2020-02-10T00:00:00
End of week: 2020-02-16T23:59:59.999999999
Does '2020-02-16T22:12:49.957' belong to the current week? > true
Does '2020-02-09T22:12:49.957' belong to the current week? > false
Does '2020-02-23T22:12:49.957' belong to the current week? > false
Start of month: 2020-02-01T00:00:00
End of month: 2020-02-29T23:59:59.999999999
Does '2020-02-16T22:12:49.957' belong to the current month? > true
Does '2020-01-16T22:12:49.957' belong to the current month? > false
Does '2020-03-16T22:12:49.957' belong to the current month? > false
Follow the below
ng-click="anyFunction()"
anyFunction() {
// call another function here
anotherFunction();
}
When a clearfix is used in a parent container, it automatically wraps around all the child elements.
It is usually used after floating elements to clear the float layout.
When float layout is used, it will horizontally align the child elements. Clearfix clears this behaviour.
Example - Bootstrap Panels
In bootstrap, when the class panel is used, there are 3 child types: panel-header, panel-body, panel-footer. All of which have display:block layout but panel-body has a clearfix pre-applied. panel-body is a main container type whereas panel-header & panel-footer isn't intended to be a container, it is just intended to hold some basic text.
If floating elements are added, the parent container does not get wrapped around those elements because the height of floating elements is not inherited by the parent container.
So for panel-header & panel-footer, clearfix is needed to clear the float layout of elements: Clearfix class gives a visual appearance that the height of the parent container has been increased to accommodate all of its child elements.
<div class="container">
<div class="panel panel-default">
<div class="panel-footer">
<div class="col-xs-6">
<input type="button" class="btn btn-primary" value="Button1">
<input type="button" class="btn btn-primary" value="Button2">
<input type="button" class="btn btn-primary" value="Button3">
</div>
</div>
</div>
<div class="panel panel-default">
<div class="panel-footer">
<div class="col-xs-6">
<input type="button" class="btn btn-primary" value="Button1">
<input type="button" class="btn btn-primary" value="Button2">
<input type="button" class="btn btn-primary" value="Button3">
</div>
<div class="clearfix"/>
</div>
</div>
</div>
According the to Windows Dev Center WIN32_LEAN_AND_MEAN excludes APIs such as Cryptography, DDE, RPC, Shell, and Windows Sockets.
You can also check for bootstrap datatable plugin as well for above issue.
It will have a large column table scrollable feature with lot of other options
$(document).ready(function() {
$('#example').dataTable( {
"scrollX": true
} );
} );
for more info with example please check out this link
If you are not looking for a BarButtonItem but simple button on navigationBar then below code works:
UIButton *aButton = [UIButton buttonWithType:UIButtonTypeCustom];
[aButton setBackgroundImage:[UIImage imageNamed:@"NavBar.png"] forState:UIControlStateNormal];
[aButton addTarget:self
action:@selector(showButtonView:)
forControlEvents:UIControlEventTouchUpInside];
aButton.frame = CGRectMake(260.0, 10.0, 30.0, 30.0);
[self.navigationController.navigationBar addSubview:aButton];
You can do
var arrayOfNumbers = arrayOfStrings.map(Number);
For older browsers which do not support Array.map, you can use Underscore
var arrayOfNumbers = _.map(arrayOfStrings, Number);
Simply add your custom rule in .eslintrc which looks like that
"radix": "off"
and you will be free of this eslint unnesesery warning.
This is for the eslint linter.
Well, you could use nohup to run whatever you are running on 'non-blocking mode'. So you can just keep checking if whatever it was supposed to run, ran, otherwise exit.
nohup ./my-script-that-may-take-long-to-finish.sh & ./check-if-previous-script-ran-or-exit.sh
echo "Script ended on Feb 15, 2011, 9:20AM" > /tmp/done.txt
So in the second one you just check if the file exists.
For a binary number of n digits the maximum decimal value it can hold will be
2^n - 1, and 2^n is the total permutations that can be generated using these many digits.
Taking a case where you only want three digits, ie your case 1. We see that the requirements is,
2^n - 1 >= 999
Applying log to both sides,
log(2^n - 1) >= log(999)
log(2^n) - log(1) >= log(999)
n = 9.964 (approx).
Taking the ceil value of n since 9.964 can't be a valid number of digits, we get n = 10.
Based on Peter Ajtai answer, here is a small jquery plugin that may help others. I didn't test on Opera and IE9 but is should work on these browsers too.
$.fn.rotate = function(until, step, initial, elt) {
var _until = (!until)?360:until;
var _step = (!step)?1:step;
var _initial = (!initial)?0:initial;
var _elt = (!elt)?$(this):elt;
var deg = _initial + _step;
var browser_prefixes = ['-webkit', '-moz', '-o', '-ms'];
for (var i=0, l=browser_prefixes.length; i<l; i++) {
var pfx = browser_prefixes[i];
_elt.css(pfx+'-transform', 'rotate('+deg+'deg)');
}
if (deg < _until) {
setTimeout(function() {
$(this).rotate(_until, _step, deg, _elt); //recursive call
}, 5);
}
};
$('.my-elt').rotate()
I've heard good things about Eigen and NT2, but haven't personally used either. There's also Boost.UBLAS, which I believe is getting a bit long in the tooth. The developers of NT2 are building the next version with the intention of getting it into Boost, so that might count for somthing.
My lin. alg. needs don't exteed beyond the 4x4 matrix case, so I can't comment on advanced functionality; I'm just pointing out some options.
Compared to the first answer, I will recommend to use dt.strftime() first, then pd.to_datetime(). In this way, it will still result in the datetime data type.
For example,
import pandas as pd
df = pd.DataFrame({'DOB': {0: '26/1/2016 ', 1: '26/1/2016 '})
print(df.dtypes)
df['DOB1'] = df['DOB'].dt.strftime('%m/%d/%Y')
print(df.dtypes)
df['DOB1'] = pd.to_datetime(df['DOB1'])
print(df.dtypes)
This should help : http://www.w3.org/International/articles/language-tags/
The golden rule when creating language tags is to keep the tag as short as possible. Avoid region, script or other subtags except where they add useful distinguishing information. For instance, use ja for Japanese and not ja-JP, unless there is a particular reason that you need to say that this is Japanese as spoken in Japan, rather than elsewhere.
The list below shows the various types of subtag that are available. We will work our way through these and how they are used in the sections that follow.
language-extlang-script-region-variant-extension-privateuse
Additionally to being iterable in a well-defined order, and the ability to use arbitrary values as keys (except -0
), maps can be useful because of the following reasons:
The spec enforces map operations to be sublinear on average.
Any non-stupid implementation of object will use a hash table or similar, so property lookups will probably be constant on average. Then objects could be even faster than maps. But that is not required by the spec.
Objects can have nasty unexpected behaviors.
For example, let's say you didn't set any foo
property to a newly created object obj
, so you expect obj.foo
to return undefined. But foo
could be built-in property inherited from Object.prototype
. Or you attempt to create obj.foo
by using an assignment, but some setter in Object.prototype
runs instead of storing your value.
Maps prevent these kind of things. Well, unless some script messes up with Map.prototype
. And Object.create(null)
would work too, but then you lose the simple object initializer syntax.
If you are in a browser environment you can also use btoa.
btoa
is a function which takes a string as argument and produces a Base64 encoded ASCII string. Its supported by 97% of browsers.
Example:
> "Basic " + btoa("billy"+":"+"secretpassword")
< "Basic YmlsbHk6c2VjcmV0cGFzc3dvcmQ="
You can then add Basic YmlsbHk6c2VjcmV0cGFzc3dvcmQ=
to the authorization
header.
Note that the usual caveats about HTTP BASIC auth apply, most importantly if you do not send your traffic over https an eavesdropped can simply decode the Base64 encoded string thus obtaining your password.
This security.stackexchange.com answer gives a good overview of some of the downsides.
The problem is that you need to give #inner
a set width
(anything but auto
or inherit
). The margin: 0 auto;
trick only works if the inner element is narrower than its container element. Without being given a width
, #inner
is automatically expanding to the full width of #outer
, which causes its contents to be flush left.
Sometimes, converting string to Date in swift can result to return nil so that you should add "!" mark to format.date function!
let dateFormatterUK = DateFormatter()
dateFormatterUK.dateFormat = "dd-MM-yyyy"
let stringDate = "11-03-2018"
let date = dateFormatterUK.date(from: stringDate)!
When using WebAPI, you should just return the Object rather than specifically returning Json, as the API will either return JSON or XML depending on the request.
I am not sure why your WebAPI is returning an ActionResult, but I would change the code to something like;
public IEnumerable<ListItems> GetAllNotificationSettings()
{
var result = new List<ListItems>();
// Filling the list with data here...
// Then I return the list
return result;
}
This will result in JSON if you are calling it from some AJAX code.
P.S
WebAPI is supposed to be RESTful, so your Controller should be called ListItemController
and your Method should just be called Get
. But that is for another day.
There are multiple function to do this work that wrote in bottom based on priority.
Set one or more CSS properties for the set of matched elements.
$("div").css("display", "block")
// Or add multiple CSS properties
$("div").css({
display: "block",
color: "red",
...
})
Display the matched elements and is roughly equivalent to calling .css("display", "block")
You can display element using .show()
instead
$("div").show()
Set one or more attributes for the set of matched elements.
If target element hasn't style
attribute, you can use this method to add inline style to element.
$("div").attr("style", "display:block")
// Or add multiple CSS properties
$("div").attr("style", "display:block; color:red")
You can add specific CSS property to element using pure javascript, if you don't want to use jQuery.
var div = document.querySelector("div");
// One property
div.style.display = "block";
// Multiple properties
div.style.cssText = "display:block; color:red";
// Multiple properties
div.setAttribute("style", "display:block; color:red");
I uses below code,
override func viewDidLoad() {
super.viewDidLoad()
self.registerObservers()
}
func registerObservers(){
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillAppear(notification:)), name: UIResponder.keyboardWillShowNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide(notification:)), name: UIResponder.keyboardWillHideNotification, object: nil)
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
self.view.endEditing(true)
}
@objc func keyboardWillAppear(notification: Notification){
if let keyboardFrame: NSValue = notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue {
let keyboardRectangle = keyboardFrame.cgRectValue
let keyboardHeight = keyboardRectangle.height
self.view.transform = CGAffineTransform(translationX: 0, y: -keyboardHeight)
}
}
@objc func keyboardWillHide(notification: Notification){
self.view.transform = .identity
}
To write text (rather than raw bytes) to a file you should consider using FileWriter. You should also wrap it in a BufferedWriter which will then give you the newLine method.
To write each word on a new line, use String.split to break your text into an array of words.
So here's a simple test of your requirement:
public static void main(String[] args) throws Exception {
String nodeValue = "i am mostafa";
// you want to output to file
// BufferedWriter writer = new BufferedWriter(new FileWriter(file3, true));
// but let's print to console while debugging
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(System.out));
String[] words = nodeValue.split(" ");
for (String word: words) {
writer.write(word);
writer.newLine();
}
writer.close();
}
The output is:
i
am
mostafa
Here is how you can retrieve only directories with GLOB:
$directories = glob($somePath . '/*' , GLOB_ONLYDIR);
Use moment.js to parse dates:
var caseOne = moment("Jul 8, 2005", "MMM D, YYYY", true).toDate();
var caseTwo = moment("2005-07-08", "YYYY-MM-DD", true).toDate();
The 3rd argument determines strict parsing (available as of 2.3.0). Without it moment.js may also give incorrect results.
You can also use : mysql> select user,host from mysql.user;
+---------------+-------------------------------+
| user | host |
+---------------+-------------------------------+
| fkernel | % |
| nagios | % |
| readonly | % |
| replicant | % |
| reporting | % |
| reporting_ro | % |
| nagios | xx.xx.xx.xx |
| haproxy_root | xx.xx.xx.xx
| root | 127.0.0.1 |
| nagios | localhost |
| root | localhost |
+---------------+-------------------------------+
The awk is ok. I'm guessing the file is from a windows system and has a CR (^m ascii 0x0d) on the end of the line.
This will cause the cursor to go to the start of the line after $2.
Use dos2unix or vi with :se ff=unix
to get rid of the CRs.
If you don't want to use jquery, use this:
<script>
// without jquery
document.addEventListener("DOMContentLoaded", function() {
setTimeout(function() {
// run your open popup function after 5 sec = 5000
PopUp();
}, 5000)
});
</script>
OR With jquery
<script>
$(document).ready(function(){
setTimeout(function(){
// open popup after 5 seconds
PopUp();
},5000);
});
</script>
Another way to encode the message you intend is to add another field to track "set" fields:
syntax="proto3";
package qtprotobuf.examples;
message SparseMessage {
repeated uint32 fieldsUsed = 1;
bool attendedParty = 2;
uint32 numberOfKids = 3;
string nickName = 4;
}
message ExplicitMessage {
enum PARTY_STATUS {ATTENDED=0; DIDNT_ATTEND=1; DIDNT_ASK=2;};
PARTY_STATUS attendedParty = 1;
bool indicatedKids = 2;
uint32 numberOfKids = 3;
enum NO_NICK_STATUS {HAS_NO_NICKNAME=0; WOULD_NOT_ADMIT_TO_HAVING_HAD_NICKNAME=1;};
NO_NICK_STATUS noNickStatus = 4;
string nickName = 5;
}
This is especially appropriate if there is a large number of fields and only a small number of them have been assigned.
In python, usage would look like this:
import field_enum_example_pb2
m = field_enum_example_pb2.SparseMessage()
m.attendedParty = True
m.fieldsUsed.append(field_enum_example_pb2.SparseMessages.ATTENDEDPARTY_FIELD_NUMBER)
In my case i leave my .js file empty means i never write anything in my .js file after that i was using it in my route so make function component or class component and finally export it will work
but an actual alias for a dir is also possible, try
myScripts="~/Files/Scripts/Main"
alias myScripts="cd $myScripts"
This way you have a common naming convention (for each dir/alias pair), and if you need to copy something from the current dir to myScripts, you don't have to think about it.
IHTH
Remove MySQL completely
Open the Terminal
Use mysqldump
to backup your databases
Check for MySQL processes with:
ps -ax | grep mysql
Stop and kill any MySQL processes
Analyze MySQL on HomeBrew:
brew remove mysql
brew cleanup
Remove files:
sudo rm /usr/local/mysql
sudo rm -rf /usr/local/var/mysql
sudo rm -rf /usr/local/mysql*
sudo rm ~/Library/LaunchAgents/homebrew.mxcl.mysql.plist
sudo rm -rf /Library/StartupItems/MySQLCOM
sudo rm -rf /Library/PreferencePanes/My*
Unload previous MySQL Auto-Login:
launchctl unload -w ~/Library/LaunchAgents/homebrew.mxcl.mysql.plist
Remove previous MySQL Configuration:
subl /etc/hostconfig`
# Remove the line MYSQLCOM=-YES-
Remove previous MySQL Preferences:
rm -rf ~/Library/PreferencePanes/My*
sudo rm -rf /Library/Receipts/mysql*
sudo rm -rf /Library/Receipts/MySQL*
sudo rm -rf /private/var/db/receipts/*mysql*
Restart your computer just to ensure any MySQL processes are killed
Try to run mysql, it shouldn't work
DataSet ds = new DataSet();
ds.ReadXml(fileNamePath);
Centered on screen:
Column(
mainAxisAlignment: MainAxisAlignment.center,
mainAxisSize: MainAxisSize.max,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
mainAxisAlignment: MainAxisAlignment.center,
mainAxisSize: MainAxisSize.max,
children: [CircularProgressIndicator()])
])
I do the following:
from selenium import webdriver
browser = webdriver.Chrome('C:\chromedriver.exe')
browser.maximize_window()
There is no difference. The $_SERVER['PHP_SELF'] just makes the execution time slower by like 0.000001 second.
Update 2020 - Bootstrap 4
The modal markup has changed slightly for Bootstrap 4. Here's how you can open the modal on page load, and optionally delay display of the modal...
$(window).on('load',function(){
var delayMs = 1500; // delay in milliseconds
setTimeout(function(){
$('#myModal').modal('show');
}, delayMs);
});
<div class="modal fade" id="myModal">
<div class="modal-dialog modal-lg modal-dialog-centered" role="document">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title">My Modal</h4>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
...
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary mx-auto" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
You can just do this:
const char *text = "This is my string it is "
"very long";
if number%2==0
will tell you that it's even. So odd numbers would be the else statement there. The "%" is the mod sign which returns the remainder after dividing. So essentially we're saying if the number is divisible by two we can safely assume it's even. Otherwise it's odd (it's a perfect correlation!)
As for the asterisk placing you want to prepend the asterisks with the number of spaces correlated to the line it's on. In your example
***** line 0
*** line 1
* line 2
We'll want to space accordingly
0*****
01***
012*
Old topic, but I think I found another descent solution. Adding class="row"
to a div will result in this CSS configuration:
.row {
display: -webkit-box;
display: flex;
flex-wrap: wrap;
margin-right: -15px;
margin-left: -15px;
}
We want to keep the first 3 rules and we can do this with class="d-flex flex-wrap"
(see https://getbootstrap.com/docs/4.1/utilities/flex/):
.flex-wrap {
flex-wrap: wrap !important;
}
.d-flex {
display: -webkit-box !important;
display: flex !important;
}
It adds !important rules though but it shouldn't be a problem in most cases...
I found a GitHub project that successfully uses CommonCrypto in a Swift framework: SHA256-Swift. Also, this article about the same problem with sqlite3 was useful.
Based on the above, the steps are:
1) Create a CommonCrypto
directory inside the project directory. Within, create a module.map
file. The module map will allow us to use the CommonCrypto library as a module within Swift. Its contents are:
module CommonCrypto [system] {
header "/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator8.0.sdk/usr/include/CommonCrypto/CommonCrypto.h"
link "CommonCrypto"
export *
}
2) In Build Settings, within Swift Compiler - Search Paths, add the CommonCrypto
directory to Import Paths (SWIFT_INCLUDE_PATHS
).
3) Finally, import CommonCrypto inside your Swift files as any other modules. For example:
import CommonCrypto
extension String {
func hnk_MD5String() -> String {
if let data = self.dataUsingEncoding(NSUTF8StringEncoding)
{
let result = NSMutableData(length: Int(CC_MD5_DIGEST_LENGTH))
let resultBytes = UnsafeMutablePointer<CUnsignedChar>(result.mutableBytes)
CC_MD5(data.bytes, CC_LONG(data.length), resultBytes)
let resultEnumerator = UnsafeBufferPointer<CUnsignedChar>(start: resultBytes, length: result.length)
let MD5 = NSMutableString()
for c in resultEnumerator {
MD5.appendFormat("%02x", c)
}
return MD5
}
return ""
}
}
Using the custom framework in another project fails at compile time with the error missing required module 'CommonCrypto'
. This is because the CommonCrypto module does not appear to be included with the custom framework. A workaround is to repeat step 2 (setting Import Paths
) in the project that uses the framework.
The module map is not platform independent (it currently points to a specific platform, the iOS 8 Simulator). I don't know how to make the header path relative to the current platform.
Updates for iOS 8 <= We should remove the line link "CommonCrypto", to get the successful compilation.
UPDATE / EDIT
I kept getting the following build error:
ld: library not found for -lCommonCrypto for architecture x86_64 clang: error: linker command failed with exit code 1 (use -v to see invocation)
Unless I removed the line link "CommonCrypto"
from the module.map
file I created. Once I removed this line it built ok.
Where, I solved this problem by adding the visibility attribute to the CSS code, it works on my website
Original code:
#zo2-body-wrap .introText .images:before_x000D_
{_x000D_
background:rgba(136,136,136,0.7);_x000D_
width:100%;_x000D_
height:100%;_x000D_
content:"";_x000D_
position:absolute;_x000D_
top:0;_x000D_
opacity:0;_x000D_
transition:all 0.2s ease-in-out 0s;_x000D_
}
_x000D_
Fixed iOS touch code:
#zo2-body-wrap .introText .images:before_x000D_
{_x000D_
background:rgba(136,136,136,0.7);_x000D_
width:100%;_x000D_
height:100%;_x000D_
content:"";_x000D_
position:absolute;_x000D_
top:0;_x000D_
visibility:hidden;_x000D_
opacity:0;_x000D_
transition:all 0.2s ease-in-out 0s;_x000D_
}
_x000D_
My issue was, i am unable to create a view with my "scott" user in oracle 11g edition. So here is my solution for this
Error in my case
SQL>create view v1 as select * from books where id=10;
insufficient privileges.
Solution
1)open your cmd and change your directory to where you install your oracle database. in my case i was downloaded in E drive so my location is E:\app\B_Amar\product\11.2.0\dbhome_1\BIN> after reaching in the position you have to type sqlplus sys as sysdba
E:\app\B_Amar\product\11.2.0\dbhome_1\BIN>sqlplus sys as sysdba
2) Enter password: here you have to type that password that you give at the time of installation of oracle software.
3) Here in this step if you want create a new user then you can create otherwise give all the privileges to existing user.
for creating new user
SQL> create user abc identified by xyz;
here abc is user and xyz is password.
giving all the privileges to abc user
SQL> grant all privileges to abc;
grant succeeded.
if you are seen this message then all the privileges are giving to the abc user.
4) Now exit from cmd, go to your SQL PLUS and connect to the user i.e enter your username & password.Now you can happily create view.
In My case
in cmd E:\app\B_Amar\product\11.2.0\dbhome_1\BIN>sqlplus sys as sysdba
SQL> grant all privileges to SCOTT;
grant succeeded.
Now I can create views.
To get a prompt with the color depending on the last command’s exit status, you could use this:
PS1='%(?.%F{green}.%F{red})%n@%m:%~%# %f'
Just add this line to your ~/.zshrc
.
The documentation lists possible placeholders.
One way would be to define a suitable comparator with which to operate on the ordinary priority queue, such that its priority gets reversed:
#include <iostream>
#include <queue>
using namespace std;
struct compare
{
bool operator()(const int& l, const int& r)
{
return l > r;
}
};
int main()
{
priority_queue<int,vector<int>, compare > pq;
pq.push(3);
pq.push(5);
pq.push(1);
pq.push(8);
while ( !pq.empty() )
{
cout << pq.top() << endl;
pq.pop();
}
cin.get();
}
Which would output 1, 3, 5, 8 respectively.
Some examples of using priority queues via STL and Sedgewick's implementations are given here.
My situation was that I did not have a main function.
You need to identify the primary key in TableA in order to delete the correct record. The primary key may be a single column or a combination of several columns that uniquely identifies a row in the table. If there is no primary key, then the ROWID pseudo column may be used as the primary key.
DELETE FROM tableA
WHERE ROWID IN
( SELECT q.ROWID
FROM tableA q
INNER JOIN tableB u on (u.qlabel = q.entityrole AND u.fieldnum = q.fieldnum)
WHERE (LENGTH(q.memotext) NOT IN (8,9,10) OR q.memotext NOT LIKE '%/%/%')
AND (u.FldFormat = 'Date'));
If your list-style is inside
then you could remove the bullet and create your own ... e.g. (in scss!)
li {
list-style: none;
&:before {
content: '- ';
}
}
And if you list style is outside
then you could do something like this:
li {
padding-left: 10px;
list-style: none;
&:before {
content: '* '; /* use any character you fancy~! */
position: absolute;
margin-left: -10px;
}
}
Technically, the char*
is not an array, but a pointer to a char
.
Similarly, char**
is a pointer to a char*
. Making it a pointer to a pointer to a char
.
C and C++ both define arrays behind-the-scenes as pointer types, so yes, this structure, in all likelihood, is array of arrays of char
s, or an array of strings.
The simplest is to use replace:
"foo bar\t".replace(" ", "").replace("\t", "")
Alternatively, use a regular expression:
import re
re.sub(r"\s", "", "foo bar\t")
For Vb.Net Framework 4.0, U can use:
Alert("your message here", Boolean)
The Boolean here can be True or False. True If you want to close the window right after, False If you want to keep the window open.
As others have mentioned you need a users/show.json view, but there are options to consider for the templating language...
ERB
Works out of the box. Great for HTML, but you'll quickly find it's awful for JSON.
Good solution. Have to add a dependency and learn its DSL.
Same deal as RABL: Good solution. Have to add a dependency and learn its DSL.
Plain Ruby
Ruby is awesome at generating JSON and there's nothing new to learn as you can call to_json
on a Hash or an AR object. Simply register the .rb extension for templates (in an initializer):
ActionView::Template.register_template_handler(:rb, :source.to_proc)
Then create the view users/show.json.rb:
@user.to_json
For more info on this approach see http://railscasts.com/episodes/379-template-handlers
You can convert jar to exe using jar2exe. However you need to purchase the software. If you need a open source software i would suggest JSmooth.
While these answers are good, IMHO I don't think they fully address the question.
The target attribute in an anchor tag tells the browser the target of the destination of the anchor. They were initially created in order to manipulate and direct anchors to the frame system of document. This was well before CSS came to the aid of HTML developers.
While target="_self"
is default by browser and the most common target is target="_blank"
which opens the anchor in a new window(which has been redirected to tabs by browser settings usually). The "_parent"
, "_top"
and framename
tags are left a mystery to those that aren't familiar with the days of iframe site building as the trend.
target="_self"
This opens an anchor in the same frame. What is confusing is that because we generally don't write in frames anymore (and the frame
and frameset
tags are obsolete in HTML5) people assume this a same window function. Instead if this anchor was nested in frames it would open in a sandbox mode of sorts, meaning only in that frame.
target="_parent"
Will open the in the next level up of a frame if they were nested to inside one another
target="_top"
This breaks outside of all the frames it is nested in and opens the link as top document in the browser window.
target="framename
This was originally deprecated but brought back in HTML5. This will target the exact frame in question. While the name
was the proper method that method has been replaced with using the id
identifying tag.
<!--Example:-->
<html>
<head>
</head>
<body>
<iframe src="url1" name="A"><p> This my first iframe</p></iframe>
<iframe src="url2" name="B"><p> This my second iframe</p></iframe>
<iframe src="url3" name="C"><p> This my third iframe</p></iframe>
<a href="url4" target="B"></a>
</body>
</html>
Android Studio has a Database Inspector bundled since version 4.1.
But it has one limitation:
The Database Inspector only works with the SQLite library included in the Android operating system on API level 26 and higher. It doesn't work with other SQLite libraries that you bundle with your app.
Single Liner to Drop, Create and Seed from Package Manager Console:
update-database -TargetMigration:0 | update-database -force
Kaboom.
Solution that worked for me:
Run this script from SharePoint 2010 Management Shell as Administrator.
I think you are looking for ToText(CCur(@Price}/{ValuationReport.YestPrice}*100-100))
You can use CCur
to convert numbers or string to Curency formats. CCur(number)
or CCur(string)
I think this may be what you are looking for,
Replace (ToText(CCur({field})),"$" , "")
that will give the parentheses for negative numbers
It is a little hacky, but I'm not sure CR is very kind in the ways of formatting
Primitives can be converted to objects with @()
expression. So the shortest way is to transform int
to NSNumber
and pick up string representation with stringValue
method:
NSString *strValue = [@(myInt) stringValue];
or
NSString *strValue = @(myInt).stringValue;
Doing borders on tables with css is a bit more complicated (but not as much, see this jsfiddle as example):
table {_x000D_
border-collapse: collapse;_x000D_
border: 1px solid black;_x000D_
}_x000D_
_x000D_
table td {_x000D_
border: 1px solid black;_x000D_
}
_x000D_
<table>_x000D_
<tr>_x000D_
<td>test</td>_x000D_
<td>test</td>_x000D_
</tr>_x000D_
</table>
_x000D_
In addition to the accepted answer, there's a third option that can be useful in some cases:
You can make a hybrid between v1 & v4 by deliberately generating v1 UUIDs with a random broadcast MAC address (this is allowed by the v1 spec). The resulting v1 UUID is time dependant (like regular v1), but lacks all host-specific information (like v4). It's also much closer to v4 in it's collision-resistance: v1mc = 60 bits of time + 61 random bits = 121 unique bits; v4 = 122 random bits.
First place I encountered this was Postgres' uuid_generate_v1mc() function. I've since used the following python equivalent:
from os import urandom
from uuid import uuid1
_int_from_bytes = int.from_bytes # py3 only
def uuid1mc():
# NOTE: The constant here is required by the UUIDv1 spec...
return uuid1(_int_from_bytes(urandom(6), "big") | 0x010000000000)
(note: I've got a longer + faster version that creates the UUID object directly; can post if anyone wants)
In case of LARGE volumes of calls/second, this has the potential to exhaust system randomness. You could use the stdlib random
module instead (it will probably also be faster). But BE WARNED: it only takes a few hundred UUIDs before an attacker can determine the RNG state, and thus partially predict future UUIDs.
import random
from uuid import uuid1
def uuid1mc_insecure():
return uuid1(random.getrandbits(48) | 0x010000000000)
Use display:none
to not show the items, then with JQuery you can use fadeIn()
and fadeOut()
to hide/unhide the elements.
Multiprogramming: It means running several programs on computer.Here user cannot interact with the system,everything is decided by the OS.
Multitasking: It is a logical extension of multiprogramming.It means running several tasks on computer.Switching between the jobs is so fast that the user can interact with the system.
Multithreading: Basically seen when more number of clients access the server.
You are looking to see if a single value is in an array. Use in_array
.
However note that case is important, as are any leading or trailing spaces. Use var_dump
to find out the length of the strings too, and see if they fit.
I don't know about elegance, but this works:
import glob
import os
for f in glob.glob("file*.txt"):
os.system("cat "+f+" >> OutFile.txt")
A variation using a generator function (which I consider more pythonic):
def recvall(sock, buffer_size=4096):
buf = sock.recv(buffer_size)
while buf:
yield buf
if len(buf) < buffer_size: break
buf = sock.recv(buffer_size)
# ...
with socket.create_connection((host, port)) as sock:
sock.sendall(command)
response = b''.join(recvall(sock))
ArrayList
is randomly accessible, while LinkedList
is really cheap to expand and remove elements from. For most cases, ArrayList
is fine.
Unless you've created large lists and measured a bottleneck, you'll probably never need to worry about the difference.
I tried $count = $stmt->rowCount();
with Oracle 11.2 and it did not work.
I decided to used a for loop as show below.
$count = "";
$stmt = $conn->prepare($sql);
$stmt->execute();
echo "<table border='1'>\n";
while($row = $stmt->fetch(PDO::FETCH_OBJ)) {
$count++;
echo "<tr>\n";
foreach ($row as $item) {
echo "<td class='td2'>".($item !== null ? htmlentities($item, ENT_QUOTES):" ")."</td>\n";
} //foreach ends
}// while ends
echo "</table>\n";
//echo " no of rows : ". oci_num_rows($stmt);
//equivalent in pdo::prepare statement
echo "no.of rows :".$count;
Actually, there's a function that returns exactly what you want
import os
print(os.path.basename(your_path))
WARNING: When os.path.basename()
is used on a POSIX system to get the base name from a Windows styled path (e.g. "C:\\my\\file.txt"
), the entire path will be returned.
Example below from interactive python shell running on a Linux host:
Python 3.8.2 (default, Mar 13 2020, 10:14:16)
[GCC 9.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import os
>>> filepath = "C:\\my\\path\\to\\file.txt" # A Windows style file path.
>>> os.path.basename(filepath)
'C:\\my\\path\\to\\file.txt'
I know this is an old post but some further explanation might be useful for someone trying to upload multiple files... Here is what you need to do:
name="inputName[]"
multiple="multiple"
or just multiple
"$_FILES['inputName']['param'][index]"
array_filter()
before count.Here is a down and dirty example (showing just relevant code)
HTML:
<input name="upload[]" type="file" multiple="multiple" />
PHP:
//$files = array_filter($_FILES['upload']['name']); //something like that to be used before processing files.
// Count # of uploaded files in array
$total = count($_FILES['upload']['name']);
// Loop through each file
for( $i=0 ; $i < $total ; $i++ ) {
//Get the temp file path
$tmpFilePath = $_FILES['upload']['tmp_name'][$i];
//Make sure we have a file path
if ($tmpFilePath != ""){
//Setup our new file path
$newFilePath = "./uploadFiles/" . $_FILES['upload']['name'][$i];
//Upload the file into the temp dir
if(move_uploaded_file($tmpFilePath, $newFilePath)) {
//Handle other code here
}
}
}
Hope this helps out!
Well, when converting TO unix timestamp, python is basically assuming UTC, but while converting back it will give you a date converted to your local timezone.
See this question/answer; Get timezone used by datetime.datetime.fromtimestamp()
For images and other sources you can use that:
$(el).one('load', function(){
// completed
}).each(function() {
if (this.complete)
$(this).load();
});