` Please include either of these:
`#include<sstream>`
using std::istringstream;
Clean solution. Restore nuget packages.
In additional you should disable your antivirus or manage it to open 80 port on your system.
You can set GIT_SSL_NO_VERIFY
to true
:
GIT_SSL_NO_VERIFY=true git clone https://example.com/path/to/git
or alternatively configure Git not to verify the connection on the command line:
git -c http.sslVerify=false clone https://example.com/path/to/git
Note that if you don't verify SSL/TLS certificates, then you are susceptible to MitM attacks.
Forced reflow often happens when you have a function called multiple times before the end of execution.
For example, you may have the problem on a smartphone, but not on a classic browser.
I suggest using a setTimeout
to solve the problem.
This isn't very important, but I repeat, the problem arises when you call a function several times, and not when the function takes more than 50 ms. I think you are mistaken in your answers.
setTimeOut
based on the duration of the violation.this tutorial help me to integrate to android studio: http://wahidgazzah.olympe.in/integrating-zxing-in-your-android-app-as-standalone-scanner/ if down try THIS
just add to AndroidManifest.xml
<activity
android:name="com.google.zxing.client.android.CaptureActivity"
android:configChanges="orientation|keyboardHidden"
android:screenOrientation="landscape"
android:theme="@android:style/Theme.NoTitleBar.Fullscreen"
android:windowSoftInputMode="stateAlwaysHidden" >
<intent-filter>
<action android:name="com.google.zxing.client.android.SCAN" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
Hope this help!.
You can change the collation of your text field to UTF8_general_ci and the problem will be solved.
Notice, this cannot be done in Django.
You could use itertools's takewhile like this, it will stop once a condition is met that fails your statement. The opposite method would be dropwhile
for x in itertools.takewhile(lambda x: x[2] == 0, list)
print x
require
is part of the Asynchronous Module Definition (AMD) API.
A browser implementation can be found via require.js and native support can be found in node.js.
The documentation for the library you are using should tell you what you need to use it, I suspect that it is intended to run under Node.js and not in browsers.
You could wrapping the transaction over try..catch or even reverse them,
here my example code I used to in laravel 5,, if you look deep inside DB:transaction()
in Illuminate\Database\Connection
that the same like you write manual transaction.
Laravel Transaction
public function transaction(Closure $callback)
{
$this->beginTransaction();
try {
$result = $callback($this);
$this->commit();
}
catch (Exception $e) {
$this->rollBack();
throw $e;
} catch (Throwable $e) {
$this->rollBack();
throw $e;
}
return $result;
}
so you could write your code like this, and handle your exception like throw message back into your form via flash or redirect to another page. REMEMBER return inside closure is returned in transaction() so if you return redirect()->back()
it won't redirect immediately, because the it returned at variable which handle the transaction.
Wrap Transaction
$result = DB::transaction(function () use ($request, $message) {
try{
// execute query 1
// execute query 2
// ..
return redirect(route('account.article'));
} catch (\Exception $e) {
return redirect()->back()->withErrors(['error' => $e->getMessage()]);
}
});
// redirect the page
return $result;
then the alternative is throw boolean variable and handle redirect outside transaction function or if your need to retrieve why transaction failed you can get it from $e->getMessage()
inside catch(Exception $e){...}
You need to instantiate the MainViewModel and set it as datacontext. In your statement it just consider it as string value.
<Window x:Class="BuildAssistantUI.BuildAssistantWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:BuildAssistantUI.ViewModels">
<Window.DataContext>
<local:MainViewModel/>
</Window.DataContext>
One way around this problem is to use stored procedures with an output parameter.
exec sp_mysprocname @returnvalue output, @firstparam = 1, @secondparam=2
values you do not pass in default to the defaults set in the stored procedure itself. And you can get the results from your output variable.
Another spin on the same theme:
protected void OnWindowSizeChanged(object sender, SizeChangedEventArgs e)
{
dataGrid.Width = e.NewSize.Width - (e.NewSize.Width * .1);
foreach (var column in dataGrid.Columns)
{
column.Width = dataGrid.Width / dataGrid.Columns.Count;
}
}
The easiest/best supported method is to use <table cellspacing="10">
The css way: border-spacing (not supported by IE I don't think)
<!-- works in firefox, opera, safari, chrome -->_x000D_
<style type="text/css">_x000D_
_x000D_
table.foobar {_x000D_
border: solid black 1px;_x000D_
border-spacing: 10px;_x000D_
}_x000D_
table.foobar td {_x000D_
border: solid black 1px;_x000D_
}_x000D_
_x000D_
_x000D_
</style>_x000D_
_x000D_
<table class="foobar" cellpadding="0" cellspacing="0">_x000D_
<tr><td>foo</td><td>bar</td></tr>_x000D_
</table>
_x000D_
Edit: if you just want to pad the cell content, and not space them you can simply use
<table cellpadding="10">
OR
td {
padding: 10px;
}
I personally like to set up my analytics with the template URL instead of the current path. This is mainly because my application has many custom paths such as message/:id
or profile/:id
. If I were to send these paths, I'd have so many pages being viewed within analytics, it would be too difficult to check which page users are visiting most.
$rootScope.$on('$viewContentLoaded', function(event) {
$window.ga('send', 'pageview', {
page: $route.current.templateUrl.replace("views", "")
});
});
I now get clean page views within my analytics such as user-profile.html
and message.html
instead of many pages being profile/1
, profile/2
and profile/3
. I can now process reports to see how many people are viewing user profiles.
If anyone has any objection to why this is bad practise within analytics, I would be more than happy to hear about it. Quite new to using Google Analytics, so not too sure if this is the best approach or not.
sys.exit()
raises a SystemExit
exception which you are probably assuming as some error. If you want your program not to raise SystemExit but return gracefully, you can wrap your functionality in a function and return from places you are planning to use sys.exit
Use MarkDownLog library (you can find it on NuGet)
you can simply use the extension ToMarkdownTable() to any collection, it does all the formatting for you.
Console.WriteLine(
yourCollection.Select(s => new
{
column1 = s.col1,
column2 = s.col2,
column3 = s.col3,
StaticColumn = "X"
})
.ToMarkdownTable());
Output looks something like this:
Column1 | Column2 | Column3 | StaticColumn
--------:| ---------:| ---------:| --------------
| | | X
You can do this with make - with gnu make it is the -j flag (this will also help on a uniprocessor machine).
For example if you want 4 parallel jobs from make:
make -j 4
You can also run gcc in a pipe with
gcc -pipe
This will pipeline the compile stages, which will also help keep the cores busy.
If you have additional machines available too, you might check out distcc, which will farm compiles out to those as well.
In Xcode 8 and iOS 10 to determine the height of a web view. you can get height using
- (void)webViewDidFinishLoad:(UIWebView *)webView
{
CGFloat height = [[webView stringByEvaluatingJavaScriptFromString:@"document.body.scrollHeight"] floatValue];
NSLog(@"Webview height is:: %f", height);
}
OR for Swift
func webViewDidFinishLoad(aWebView:UIWebView){
let height: Float = (aWebView.stringByEvaluatingJavaScriptFromString("document.body.scrollHeight")?.toFloat())!
print("Webview height is::\(height)")
}
One way you can increase the number of mappers is to give your input in the form of split files [you can use linux split command]. Hadoop streaming usually assigns that many mappers as there are input files[if there are a large number of files] if not it will try to split the input into equal sized parts.
The Java runtime you try to execute your program with is an earlier version than Java 7 which was the target you compile your program for.
For Ubuntu use
apt-get install openjdk-7-jdk
to get Java 7 as default. You may have to uninstall openjdk-6 first.
This is perhaps a bit late, but may help someone. I come across similar issue with Iterable
in my codebase and solution was to use for each
without explicitly calling values.iterator();
.
int size = 0;
for(T value : values) {
size++;
}
You can use peek
to do that.
List<Fruit> newList = fruits.stream()
.peek(f -> f.setName(f.getName() + "s"))
.collect(Collectors.toList());
Instead of any Array
you can load your data in DataTable
like:
using System.Data;
DataTable dt = new DataTable();
using (var con = new SqlConnection("Data Source=local;Initial Catalog=Test;Integrated Security=True"))
{
using (var command = new SqlCommand("SELECT col1,col2" +
{
con.Open();
using (SqlDataReader dr = command.ExecuteReader())
{
dt.Load(dr);
}
}
}
You can also use SqlDataAdapater
to fill your DataTable like
SqlDataAdapter da = new SqlDataAdapter(command);
da.Fill(dt);
Later you can iterate each row and compare like:
foreach (DataRow dr in dt.Rows)
{
if (dr.Field<string>("col1") == "yourvalue") //your condition
{
}
}
To remove all columns after the one you want, below code should work. It will remove at index 10 (remember Columns are 0 based), until the Column count is 10 or less.
DataTable dt;
int desiredSize = 10;
while (dt.Columns.Count > desiredSize)
{
dt.Columns.RemoveAt(desiredSize);
}
I followed the answers here but when I tried to connect with my new user, I got an error message stating "The server principal 'newuser' is not able to access the database 'master' under the current security context"
.
I had to also create a new user in the master table to successfully log in with SSMS.
USE [master]
GO
CREATE LOGIN [newuser] WITH PASSWORD=N'blahpw'
GO
CREATE USER [newuser] FOR LOGIN [newuser] WITH DEFAULT_SCHEMA=[dbo]
GO
USE [MyDatabase]
CREATE USER newuser FOR LOGIN newuser WITH DEFAULT_SCHEMA = dbo
GO
EXEC sp_addrolemember N'db_owner', N'newuser'
GO
A const
object is always static
.
I think this should do it.
declare @x int;
select @x = max(id) from table_name;
select * from where id = @x;
The parentheses are poorly placed.
You need to use:
doThrow(new Exception()).when(mockedObject).methodReturningVoid(...);
^
and NOT use:
doThrow(new Exception()).when(mockedObject.methodReturningVoid(...));
^
This is explained in the documentation
Read this article for better insight. Note: Numpy reports the shape of 3D arrays in the order layers, rows, columns.
Meder Omuraliev suggested to use an event handler and set scrollTo(0,0). This is an example for Wassim-azirar. Bringing it all together, I assume this is the final solution.
We have 3 problems: the scrollbar, scrolling with mouse, and keyboard. This hides the scrollbar:
html, body{overflow:hidden;}
Unfortunally, you can still scroll with the keyboard: To prevent this, we can:
function keydownHandler(e) {
var evt = e ? e:event;
var keyCode = evt.keyCode;
if (keyCode==38 || keyCode==39 || keyCode==40 || keyCode==37){ //arrow keys
e.preventDefault()
scrollTo(0,0);
}
}
document.onkeydown=keydownHandler;
The scrolling with the mouse just naturally doesn't work after this code, so we have prevented the scrolling.
For example: https://jsfiddle.net/aL7pes70/1/
In MySQL if You don't want to change the collation and want to perform case sensitive search then just use binary keyword like this:
SELECT * FROM table_name WHERE binary username=@search_parameter and binary password=@search_parameter
Use command-line option -v
or --invert-match
,
ls -R |grep -v -E .*[\.exe]$\|.*[\.html]$
Use NULLIF(exp,0)
but in this way - NULLIF(ISNULL(exp,0),0)
NULLIF(exp,0)
breaks if exp is null
but NULLIF(ISNULL(exp,0),0)
will not break
I would strongly recommend business rules engines like Drools as open source or Commercial Rules Engine such as LiveRules.
var currentDate = moment('2015-10-30');
var futureMonth = moment(currentDate).add(1, 'M');
var futureMonthEnd = moment(futureMonth).endOf('month');
if(currentDate.date() != futureMonth.date() && futureMonth.isSame(futureMonthEnd.format('YYYY-MM-DD'))) {
futureMonth = futureMonth.add(1, 'd');
}
console.log(currentDate);
console.log(futureMonth);
EDIT
moment.addRealMonth = function addRealMonth(d) {
var fm = moment(d).add(1, 'M');
var fmEnd = moment(fm).endOf('month');
return d.date() != fm.date() && fm.isSame(fmEnd.format('YYYY-MM-DD')) ? fm.add(1, 'd') : fm;
}
var nextMonth = moment.addRealMonth(moment());
You shouldn't have to set height: 100%
at any point if you want your container to fill the page. Chances are, your problem is rooted in the fact that you haven't cleared the floats in the container's children. There are quite a few ways to solve this problem, mainly adding overflow: hidden
to the container.
#container { overflow: hidden; }
Should be enough to solve whatever height problem you're having.
While this doesn't affect single jobs, you can use this script to ignore certain steps if the latest commit did not contain any changes:
/*
* Check a folder if changed in the latest commit.
* Returns true if changed, or false if no changes.
*/
def checkFolderForDiffs(path) {
try {
// git diff will return 1 for changes (failure) which is caught in catch, or
// 0 meaning no changes
sh "git diff --quiet --exit-code HEAD~1..HEAD ${path}"
return false
} catch (err) {
return true
}
}
if ( checkFolderForDiffs('api/') ) {
//API folder changed, run steps here
}
Uri is wrong, there is a way to add parameters to main method in Eclipse directly, however the parameters won't be very flexible (some dynamic parameters are allowed). Here's what you need to do:
Run -> Run configurations...
Java Application
or by typing its name to filter box.Program arguments
box. Just in case it isn't clear, they're whitespace-separated so "a b c"
(without quotes) would mean you'd pass arguments a, b and c to your program.I do however recommend using JUnit/wrapper class just like Uri did say since that way you get a lot better control over the actual parameters than by doing this.
Recently I found a way around this. I wanted to create a method in the array class with an optional parameter, to keep or discard elements in the array.
The way I simulated this was by passing an array as the parameter, and then checking if the value at that index was nil or not.
class Array
def ascii_to_text(params)
param_len = params.length
if param_len > 3 or param_len < 2 then raise "Invalid number of arguments #{param_len} for 2 || 3." end
bottom = params[0]
top = params[1]
keep = params[2]
if keep.nil? == false
if keep == 1
self.map{|x| if x >= bottom and x <= top then x = x.chr else x = x.to_s end}
else
raise "Invalid option #{keep} at argument position 3 in #{p params}, must be 1 or nil"
end
else
self.map{|x| if x >= bottom and x <= top then x = x.chr end}.compact
end
end
end
Trying out our class method with different parameters:
array = [1, 2, 97, 98, 99]
p array.ascii_to_text([32, 126, 1]) # Convert all ASCII values of 32-126 to their chr value otherwise keep it the same (That's what the optional 1 is for)
output: ["1", "2", "a", "b", "c"]
Okay, cool that works as planned. Now let's check and see what happens if we don't pass in the the third parameter option (1) in the array.
array = [1, 2, 97, 98, 99]
p array.ascii_to_text([32, 126]) # Convert all ASCII values of 32-126 to their chr value else remove it (1 isn't a parameter option)
output: ["a", "b", "c"]
As you can see, the third option in the array has been removed, thus initiating a different section in the method and removing all ASCII values that are not in our range (32-126)
Alternatively, we could had issued the value as nil in the parameters. Which would look similar to the following code block:
def ascii_to_text(top, bottom, keep = nil)
if keep.nil?
self.map{|x| if x >= bottom and x <= top then x = x.chr end}.compact
else
self.map{|x| if x >= bottom and x <= top then x = x.chr else x = x.to_s end}
end
What do you mean by "initialize an array to zero"? Arrays don't contain "zero" -- they can contain "zero elements", which is the same as "an empty list". Or, you could have an array with one element, where that element is a zero: my @array = (0);
my @array = ();
should work just fine -- it allocates a new array called @array
, and then assigns it the empty list, ()
. Note that this is identical to simply saying my @array;
, since the initial value of a new array is the empty list anyway.
Are you sure you are getting an error from this line, and not somewhere else in your code? Ensure you have use strict; use warnings;
in your module or script, and check the line number of the error you get. (Posting some contextual code here might help, too.)
it is because view child require two argument try like this
@ViewChild('nameInput', { static: false, }) nameInputRef: ElementRef;
@ViewChild('amountInput', { static: false, }) amountInputRef: ElementRef;
You can do like this
$.datepicker.regional['fr'] = {clearText: 'Effacer', clearStatus: '',
closeText: 'Fermer', closeStatus: 'Fermer sans modifier',
prevText: '<Préc', prevStatus: 'Voir le mois précédent',
nextText: 'Suiv>', nextStatus: 'Voir le mois suivant',
currentText: 'Courant', currentStatus: 'Voir le mois courant',
monthNames: ['Janvier','Février','Mars','Avril','Mai','Juin',
'Juillet','Août','Septembre','Octobre','Novembre','Décembre'],
monthNamesShort: ['Jan','Fév','Mar','Avr','Mai','Jun',
'Jul','Aoû','Sep','Oct','Nov','Déc'],
monthStatus: 'Voir un autre mois', yearStatus: 'Voir un autre année',
weekHeader: 'Sm', weekStatus: '',
dayNames: ['Dimanche','Lundi','Mardi','Mercredi','Jeudi','Vendredi','Samedi'],
dayNamesShort: ['Dim','Lun','Mar','Mer','Jeu','Ven','Sam'],
dayNamesMin: ['Di','Lu','Ma','Me','Je','Ve','Sa'],
dayStatus: 'Utiliser DD comme premier jour de la semaine', dateStatus: 'Choisir le DD, MM d',
dateFormat: 'dd/mm/yy', firstDay: 0,
initStatus: 'Choisir la date', isRTL: false};
$.datepicker.setDefaults($.datepicker.regional['fr']);
Content that is floating does not influence the height of its container. The element contains no content that isn't floating (so nothing stops the height of the container being 0, as if it were empty).
Setting overflow: hidden
on the container will avoid that by establishing a new block formatting context. See methods for containing floats for other techniques and containing floats for an explanation about why CSS was designed this way.
1) This problem occure due to apk file .if your apk file
(output/apk/debug.apk) not generated in this format .
2) you should use always in gradle file .
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
Using the Call Stack Window
To open the Call Stack window in Visual Studio, from the Debug menu, choose Windows>Call Stack. To set the local context to a particular row in the stack trace display, double click the first column of the row.
http://msdn.microsoft.com/en-us/library/windows/hardware/hh439516(v=vs.85).aspx
You can also use Requestify, a really cool and very simple HTTP client I wrote for nodeJS + it supports caching.
Just do the following for executing a POST request:
var requestify = require('requestify');
requestify.post('http://example.com', {
hello: 'world'
})
.then(function(response) {
// Get the response body (JSON parsed or jQuery object for XMLs)
response.getBody();
});
Try below code :
Assign the path of the folder to variable FolderPath
before running the below code.
Sub sample()
Dim FolderPath As String, path As String, count As Integer
FolderPath = "C:\Documents and Settings\Santosh\Desktop"
path = FolderPath & "\*.xls"
Filename = Dir(path)
Do While Filename <> ""
count = count + 1
Filename = Dir()
Loop
Range("Q8").Value = count
'MsgBox count & " : files found in folder"
End Sub
None of the answers here were quite what I wanted. Here's what I came up with:
# Recursively revert any locally-changed files
svn revert -R .
# Delete any other files in the sandbox (including ignored files),
# being careful to handle files with spaces in the name
svn status --no-ignore | grep '^\?' | \
perl -ne 'print "$1\n" if $_ =~ /^\S+\s+(.*)$/' | \
tr '\n' '\0' | xargs -0 rm -rf
Tested on Linux; may work in Cygwin, but relies on (I believe) a GNU-specific extension which allows xargs to split based on '\0'
instead of whitespace.
The advantage to the above command is that it does not require any network activity to reset the sandbox. You get exactly what you had before, and you lose all your changes. (disclaimer before someone blames me for this code destroying their work) ;-)
I use this script on a continuous integration system where I want to make sure a clean build is performed after running some tests.
Edit: I'm not sure this works with all versions of Subversion. It's not clear if the svn status
command is always formatted consistently. Use at your own risk, as with any command that uses such a blanket rm
command.
Since you actually stored the previous LAST_INSERT_ID() into the second table, you can get it from there:
INSERT INTO table1 (title,userid) VALUES ('test',1);
INSERT INTO table2 (parentid,otherid,userid) VALUES (LAST_INSERT_ID(),4,1);
SELECT parentid FROM table2 WHERE id = LAST_INSERT_ID();
My vote is string.Join
No need for lambda evaluations and temporary functions to be created, fewer function calls, less stack pushing and popping.
You can use any one way
NSString *string=[NSString stringWithFormat:@"%@",url1];
or
NSString *str=[url1 absoluteString];
NSLog(@"string :: %@",string);
string :: file:///var/containers/Bundle/Application/E2D7570B-D5A6-45A0-8EAAA1F7476071FE/RemoDuplicateMedia.app/loading_circle_animation.gif
NSLog(@"str :: %@", str);
str :: file:///var/containers/Bundle/Application/E2D7570B-D5A6-45A0-8EAA-A1F7476071FE/RemoDuplicateMedia.app/loading_circle_animation.gif
One other simple option not suggested yet, to just count NaNs, would be adding in the shape to return the number of rows with NaN.
df[df['col_name'].isnull()]['col_name'].shape
This is usually happens when the remote is down/unavailable; or the remote machine doesn't have ssh installed; or a firewall doesn't allow a connection to be established to the remote host.
ssh
returns 255 when an error occurred or 255 is returned by the remote script:
EXIT STATUS
ssh exits with the exit status of the remote command or
with 255 if an error occurred.
Usually you would an error message something similar to:
ssh: connect to host host.domain.com port 22: No route to host
Or
ssh: connect to host HOSTNAME port 22: Connection refused
Check-list:
What happens if you run the ssh command directly from the command line?
Are you able to ping
that machine?
Does the remote has ssh installed?
If installed, then is the ssh service running?
On our servers it was a problem with the system path. After upgrading PHP runtime (using installation directory whose name includes version number) and updating the path in system variable PATH
we were getting status 0x1
. System restart corrected the issue. Restarting Task Manager
service might have done it, too.
I found the following simple solution for specifying a user in the HttpContext: https://forums.asp.net/post/5828182.aspx
Although factorials make a nice exercise for the beginning programmer, they're not very useful in most cases, and everyone knows how to write a factorial function, so they're typically not in the average library.
I found this on 456 Bera St. Man is it a lifesaver!!!
http://www.456bereastreet.com/archive/200704/how_to_prevent_html_tables_from_becoming_too_wide/
But - you don't have a lot of room to spare with your data.
CSS FTW:
<style>
table {
table-layout:fixed;
}
td{
overflow:hidden;
text-overflow: ellipsis;
}
</style>
HTML 5 with Webforms 2 provides an <input type="range">
which will make the browser generate a native slider for you. Unfortunately all browsers doesn't have support for this, however google has implemented all Webforms 2 controls with js. IIRC the js is intelligent enough to know if the browser has implemented the control, and triggers only if there is no native implementation.
From my point of view it should be considered best practice to use the browsers native controls when possible.
Note: As of 17.0 from_csv
is discouraged: use pd.read_csv
instead
The documentation lists a .from_csv function that appears to do what you want:
DataFrame.from_csv('c:/~/trainSetRel3.txt', sep='\t')
If you have a header, you can pass header=0
.
DataFrame.from_csv('c:/~/trainSetRel3.txt', sep='\t', header=0)
You can try ES6 Modules in Google Chrome Beta (61) / Chrome Canary.
Reference Implementation of ToDo MVC by Paul Irish - https://paulirish.github.io/es-modules-todomvc/
I've basic demo -
//app.js
import {sum} from './calc.js'
console.log(sum(2,3));
//calc.js
let sum = (a,b) => { return a + b; }
export {sum};
<html>
<head>
<meta charset="utf-8" />
</head>
<body>
<h1>ES6</h1>
<script src="app.js" type="module"></script>
</body>
</html>
Hope it helps!
find($id)
takes an id and returns a single model. If no matching model exist, it returns null
.
findOrFail($id)
takes an id and returns a single model. If no matching model exist, it throws an error1.
first()
returns the first record found in the database. If no matching model exist, it returns null
.
firstOrFail()
returns the first record found in the database. If no matching model exist, it throws an error1.
get()
returns a collection of models matching the query.
pluck($column)
returns a collection of just the values in the given column. In previous versions of Laravel this method was called lists
.
toArray()
converts the model/collection into a simple PHP array.
Note: a collection is a beefed up array. It functions similarly to an array, but has a lot of added functionality, as you can see in the docs.
Unfortunately, PHP doesn't let you use a collection object everywhere you can use an array. For example, using a collection in a foreach
loop is ok, put passing it to array_map
is not. Similarly, if you type-hint an argument as array
, PHP won't let you pass it a collection. Starting in PHP 7.1, there is the iterable
typehint, which can be used to accept both arrays and collections.
If you ever want to get a plain array from a collection, call its all()
method.
1 The error thrown by the findOrFail
and firstOrFail
methods is a ModelNotFoundException
. If you don't catch this exception yourself, Laravel will respond with a 404, which is what you want most of the time.
An obvious, but slow, mathematical approach is:
int firstDigit = (int)(i / Math.Pow(10, (int)Math.Log10(i))));
You should be able to do this by checking the value of $_SERVER['HTTPS']
(it should only be set when using https).
Eclipse 3.5 has an option to package required libraries into the runnable jar. File -> Export... Choose runnable jar and click next. The runnable jar export window has a radio button where you can choose to package the required libraries into the jar.
The packages at http://windows.php.net/download/ all contain the php\_intl.dll
which is located in the subdir ext/
.
All you have to do is to check if your extension_dir points to the right directory and add (or uncomment) the extension=php\_intl.dll
directive.
scrollView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
// Ready, move up
scrollView.fullScroll(View.FOCUS_UP);
}
});
I realize this is old, but maybe this function I created is useful to someone out there:
order_axis<-function(data, axis, column)
{
# for interactivity with ggplot2
arguments <- as.list(match.call())
col <- eval(arguments$column, data)
ax <- eval(arguments$axis, data)
# evaluated factors
a<-reorder(with(data, ax),
with(data, col))
#new_data
df<-cbind.data.frame(data)
# define new var
within(df,
do.call("<-",list(paste0(as.character(arguments$axis),"_o"), a)))
}
Now, with this function you can interactively plot with ggplot2, like this:
ggplot(order_axis(df, AXIS_X, COLUMN_Y),
aes(x = AXIS_X_o, y = COLUMN_Y)) +
geom_bar(stat = "identity")
As can be seen, the order_axis
function creates another dataframe with a new column named the same but with a _o
at the end. This new column has levels in ascending order, so ggplot2 automatically plots in that order.
This is somewhat limited (only works for character or factor and numeric combinations of columns and in ascending order) but I still find it very useful for plotting on the go.
Like bstpierre above, I use and recommend the use of explicitly naming output variables:
function some_func() # OUTVAR ARG1
{
local _outvar=$1
local _result # Use some naming convention to avoid OUTVARs to clash
... some processing ....
eval $_outvar=\$_result # Instead of just =$_result
}
Note the use of quoting the $. This will avoid interpreting content in $result
as shell special characters. I have found that this is an order of magnitude faster than the result=$(some_func "arg1")
idiom of capturing an echo. The speed difference seems even more notable using bash on MSYS where stdout capturing from function calls is almost catastrophic.
It's ok to send in a local variables since locals are dynamically scoped in bash:
function another_func() # ARG
{
local result
some_func result "$1"
echo result is $result
}
How about using StringUtils.countMatches from Apache Commons Lang?
String str = "helloslkhellodjladfjhello";
String findStr = "hello";
System.out.println(StringUtils.countMatches(str, findStr));
That outputs:
3
Here's another way to process command line args, using R CMD BATCH
. My approach, which builds on an earlier answer here, lets you specify arguments at the command line and, in your R script, give some or all of them default values.
Here's an R file, which I name test.R:
defaults <- list(a=1, b=c(1,1,1)) ## default values of any arguments we might pass
## parse each command arg, loading it into global environment
for (arg in commandArgs(TRUE))
eval(parse(text=arg))
## if any variable named in defaults doesn't exist, then create it
## with value from defaults
for (nm in names(defaults))
assign(nm, mget(nm, ifnotfound=list(defaults[[nm]]))[[1]])
print(a)
print(b)
At the command line, if I type
R CMD BATCH --no-save --no-restore '--args a=2 b=c(2,5,6)' test.R
then within R we'll have a
= 2
and b
= c(2,5,6)
. But I could, say, omit b
, and add in another argument c
:
R CMD BATCH --no-save --no-restore '--args a=2 c="hello"' test.R
Then in R we'll have a
= 2
, b
= c(1,1,1)
(the default), and c
= "hello"
.
Finally, for convenience we can wrap the R code in a function, as long as we're careful about the environment:
## defaults should be either NULL or a named list
parseCommandArgs <- function(defaults=NULL, envir=globalenv()) {
for (arg in commandArgs(TRUE))
eval(parse(text=arg), envir=envir)
for (nm in names(defaults))
assign(nm, mget(nm, ifnotfound=list(defaults[[nm]]), envir=envir)[[1]], pos=envir)
}
## example usage:
parseCommandArgs(list(a=1, b=c(1,1,1)))
Things are about to change on the "eol conversion" front, with the upcoming Git 1.7.2:
A new config setting core.eol
is being added/evolved:
This is a replacement for the 'Add "
core.eol
" config variable' commit that's currently inpu
(the last one in my series).
Instead of implying that "core.autocrlf=true
" is a replacement for "* text=auto
", it makes explicit the fact thatautocrlf
is only for users who want to work with CRLFs in their working directory on a repository that doesn't have text file normalization.
When it is enabled, "core.eol" is ignored.Introduce a new configuration variable, "
core.eol
", that allows the user to set which line endings to use for end-of-line-normalized files in the working directory.
It defaults to "native
", which means CRLF on Windows and LF everywhere else. Note that "core.autocrlf
" overridescore.eol
.
This means that:[core] autocrlf = true
puts CRLFs in the working directory even if
core.eol
is set to "lf
".core.eol:
Sets the line ending type to use in the working directory for files that have the
text
property set.
Alternatives are 'lf', 'crlf' and 'native', which uses the platform's native line ending.
The default value isnative
.
Other evolutions are being considered:
For 1.8, I would consider making
core.autocrlf
just turn on normalization and leave the working directory line ending decision to core.eol, but that will break people's setups.
git 2.8 (March 2016) improves the way core.autocrlf
influences the eol:
See commit 817a0c7 (23 Feb 2016), commit 6e336a5, commit df747b8, commit df747b8 (10 Feb 2016), commit df747b8, commit df747b8 (10 Feb 2016), and commit 4b4024f, commit bb211b4, commit 92cce13, commit 320d39c, commit 4b4024f, commit bb211b4, commit 92cce13, commit 320d39c (05 Feb 2016) by Torsten Bögershausen (tboegi
).
(Merged by Junio C Hamano -- gitster
-- in commit c6b94eb, 26 Feb 2016)
convert.c
: refactorcrlf_action
Refactor the determination and usage of
crlf_action
.
Today, when no "crlf
" attribute are set on a file,crlf_action
is set toCRLF_GUESS
. UseCRLF_UNDEFINED
instead, and search for "text
" or "eol
" as before.Replace the old
CRLF_GUESS
usage:
CRLF_GUESS && core.autocrlf=true -> CRLF_AUTO_CRLF
CRLF_GUESS && core.autocrlf=false -> CRLF_BINARY
CRLF_GUESS && core.autocrlf=input -> CRLF_AUTO_INPUT
Make more clear, what is what, by defining:
- CRLF_UNDEFINED : No attributes set. Temparally used, until core.autocrlf
and core.eol is evaluated and one of CRLF_BINARY,
CRLF_AUTO_INPUT or CRLF_AUTO_CRLF is selected
- CRLF_BINARY : No processing of line endings.
- CRLF_TEXT : attribute "text" is set, line endings are processed.
- CRLF_TEXT_INPUT: attribute "input" or "eol=lf" is set. This implies text.
- CRLF_TEXT_CRLF : attribute "eol=crlf" is set. This implies text.
- CRLF_AUTO : attribute "auto" is set.
- CRLF_AUTO_INPUT: core.autocrlf=input (no attributes)
- CRLF_AUTO_CRLF : core.autocrlf=true (no attributes)
As torek adds in the comments:
all these translations (any EOL conversion from
eol=
orautocrlf
settings, and "clean
" filters) are run when files move from work-tree to index, i.e., duringgit add
rather than atgit commit
time.
(Note thatgit commit -a
or--only
or--include
do add files to the index at that time, though.)
For more on that, see "What is difference between autocrlf and eol".
The docs give a fair indicator of what's required., however requests
allow us to skip a few steps:
You only need to install the security
package extras (thanks @admdrew for pointing it out)
$ pip install requests[security]
or, install them directly:
$ pip install pyopenssl ndg-httpsclient pyasn1
Requests will then automatically inject pyopenssl
into urllib3
If you're on ubuntu, you may run into trouble installing pyopenssl
, you'll need these dependencies:
$ apt-get install libffi-dev libssl-dev
However many years late this response may be, anyone coming across this might just want to try
li {
display: flex;
flex-direction: row;
align-items: center;
}
Browser support for flexbox is far better than it was when @scottjoudry posted his response above, but you may still want to consider prefixing or other options if you're trying to support much older browsers. caniuse: flex
Just hit on this when trying to solve this type of thing my self.
I did a selector that deals with the element after being something other than a p.
.here .is.the #selector h4 + * {...}
Hope this helps anyone who finds it :)
This worked for me in newer browsers:
autocomplete="new-password"
#define IS_IPHONE (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone)
#define IS_IPHONE_X (IS_IPHONE && [[UIScreen mainScreen] bounds].size.height == 812.0f)
You can remove public keyword from your functions, because, you have to define a class in order to declare public, private or protected function
Don't apply the orientation to the application element, instead you should apply the attribute to the activity element, and you must also set configChanges
as noted below.
Example:
<activity
android:screenOrientation="portrait"
android:configChanges="orientation|keyboardHidden">
</activity>
This is applied in the manifest file AndroidManifest.xml
.
You can create an Int Array like this:
val numbers = IntArray(5, { 10 * (it + 1) })
5 is the Int Array size. the lambda function is the element init function. 'it' range in [0,4], plus 1 make range in [1,5]
origin function is:
/**
* An array of ints. When targeting the JVM, instances of this class are
* represented as `int[]`.
* @constructor Creates a new array of the specified [size], with all elements
* initialized to zero.
*/
public class IntArray(size: Int) {
/**
* Creates a new array of the specified [size], where each element is
* calculated by calling the specified
* [init] function. The [init] function returns an array element given
* its index.
*/
public inline constructor(size: Int, init: (Int) -> Int)
...
}
IntArray class defined in the Arrays.kt
rows and cols are required attributes, so you should have them whether you really need them or not. They set the number of rows and number of columns respectively.
I'm just providing this as an answer, as Tomalak provided as a comment to meder's answer a long time ago
//div[contains(concat(' ', @class, ' '), ' Test ')]
You can make sure that the object in question is stringified before passing it to parse function by simply using JSON.stringify()
.
Updated your line below,
JSON.parse(JSON.stringify({"balance":0,"count":0,"time":1323973673061,"firstname":"howard","userId":5383,"localid":1,"freeExpiration":0,"status":false}));
or if you have JSON stored in some variable:
JSON.parse(JSON.stringify(yourJSONobject));
NOTE: Potentially outdated. ECMAScript 2017 includes
String.prototype.padStart
.
You'll have to convert the number to a string since numbers don't make sense with leading zeros. Something like this:
function pad(num, size) {
num = num.toString();
while (num.length < size) num = "0" + num;
return num;
}
Or, if you know you'd never be using more than X number of zeros, this might be better. This assumes you'd never want more than 10 digits.
function pad(num, size) {
var s = "000000000" + num;
return s.substr(s.length-size);
}
If you care about negative numbers you'll have to strip the -
and read it.
For anyone reading this post: Do yourself a favor and stay away of ng-grid. Is full of bugs (really..almost every part of the lib is broken somehow), the devs has abandoned the support of 2.0.x branch in order to work in 3.0 which is very far of being ready. Fixing the problems by yourself is not an easy task, ng-grid code is not small and is not simple, unless you have a lot of time and a deep knowledge of angular and js in general, its going to be a hard task.
Bottom Line: is full of bugs, and the last stable version has been abandoned.
The github is full of PRs, but they are being ignored. And if you report a bug in the 2.x branch, it's get closed.
I know is an open source proyect and the complains may sound a little bit out of place, but from the perspective of a developer looking for a library, that's my opinion. I spent many hours working with ng-grid in a large proyect and the headcaches are never ending
You can try it:
Dim Price As Integer
Int32.TryParse(txtPrice.Text, Price)
Sometimes things need a system restart (in my case).
If someone is looking for a reversed list, like I was:
stuff = [1, 2, 3, 4]
def reverse(bla, y):
for subset in itertools.combinations(bla, len(bla)-y):
print list(subset)
if y != len(bla):
y += 1
reverse(bla, y)
reverse(stuff, 1)
Without any external tool you can simply accomplish this on Windows 7 or 8, by opening up the Resource monitor and on the CPU or Overview tab right clicking on the process and selecting Suspend Process. The Resource monitor can be started from the Performance tab of the Task manager.
1) Put https://api-server.com/API/index.php/member/signin
in the url input box and choose POST
from the dropdown
2) In Headers tab, enter:
Content-Type: image/jpeg
Content-Transfer-Encoding: binary
3) In Body tab, select the raw
radio button and write:
{"description":"","phone":"","lastname":"","app_version":"2.6.2","firstname":"","password":"my_pass","city":"","apikey":"213","lang":"fr","platform":"1","email":"[email protected]","pseudo":"example"}
select form-data
radio button and write:
key = name Value = userfile Select Text
key = filename Select File
and upload your profil.jpg
You have to use escaping of characters. It's a solution of this chicken-and-egg problem: how do I write a ", if I need it to terminate a string literal? So, the C creators decided to use a special character that changes treatment of the next char:
printf("this is a \"quoted string\"");
Also you can use '\' to input special symbols like "\n", "\t", "\a", to input '\' itself: "\\" and so on.
I was wondering, if there is any difference between RemoveAll
and Except
and the pros of using HashSet
, so I have done quick performance check :)
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
namespace ListRemoveTest
{
class Program
{
private static Random random = new Random( (int)DateTime.Now.Ticks );
static void Main( string[] args )
{
Console.WriteLine( "Be patient, generating data..." );
List<string> list = new List<string>();
List<string> toRemove = new List<string>();
for( int x=0; x < 1000000; x++ )
{
string randString = RandomString( random.Next( 100 ) );
list.Add( randString );
if( random.Next( 1000 ) == 0 )
toRemove.Insert( 0, randString );
}
List<string> l1 = new List<string>( list );
List<string> l2 = new List<string>( list );
List<string> l3 = new List<string>( list );
List<string> l4 = new List<string>( list );
Console.WriteLine( "Be patient, testing..." );
Stopwatch sw1 = Stopwatch.StartNew();
l1.RemoveAll( toRemove.Contains );
sw1.Stop();
Stopwatch sw2 = Stopwatch.StartNew();
l2.RemoveAll( new HashSet<string>( toRemove ).Contains );
sw2.Stop();
Stopwatch sw3 = Stopwatch.StartNew();
l3 = l3.Except( toRemove ).ToList();
sw3.Stop();
Stopwatch sw4 = Stopwatch.StartNew();
l4 = l4.Except( new HashSet<string>( toRemove ) ).ToList();
sw3.Stop();
Console.WriteLine( "L1.Len = {0}, Time taken: {1}ms", l1.Count, sw1.Elapsed.TotalMilliseconds );
Console.WriteLine( "L2.Len = {0}, Time taken: {1}ms", l1.Count, sw2.Elapsed.TotalMilliseconds );
Console.WriteLine( "L3.Len = {0}, Time taken: {1}ms", l1.Count, sw3.Elapsed.TotalMilliseconds );
Console.WriteLine( "L4.Len = {0}, Time taken: {1}ms", l1.Count, sw3.Elapsed.TotalMilliseconds );
Console.ReadKey();
}
private static string RandomString( int size )
{
StringBuilder builder = new StringBuilder();
char ch;
for( int i = 0; i < size; i++ )
{
ch = Convert.ToChar( Convert.ToInt32( Math.Floor( 26 * random.NextDouble() + 65 ) ) );
builder.Append( ch );
}
return builder.ToString();
}
}
}
Results below:
Be patient, generating data...
Be patient, testing...
L1.Len = 985263, Time taken: 13411.8648ms
L2.Len = 985263, Time taken: 76.4042ms
L3.Len = 985263, Time taken: 340.6933ms
L4.Len = 985263, Time taken: 340.6933ms
As we can see, best option in that case is to use RemoveAll(HashSet)
Seems like the cleanest way in this example is to:
Example adapted from shamanland implementation, use whatever FAB you wish. Assume FAB is 64dp high including shadow:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<View
android:id="@+id/header"
android:layout_width="match_parent"
android:layout_height="120dp"
/>
<View
android:id="@+id/body"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="@id/header"
/>
<fully.qualified.name.FloatingActionButton
android:id="@+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignBottom="@id/header"
android:layout_marginBottom="-32dp"
android:layout_marginRight="20dp"
/>
</RelativeLayout>
Since I'm using Python 3.7 on Ubuntu I had to use:
sudo apt-get install python3.7-tk
I too prefer Joda Time, but here's an alternative:
long oneDay = 24 * 60 * 60 * 1000
long d1 = first.getTime() / oneDay
long d2 = second.getTime() / oneDay
d1 == d2
EDIT
I put the UTC thingy below in case you need to compare dates for a specific timezone other than UTC. If you do have such a need, though, then I really advise going for Joda.
long oneDay = 24 * 60 * 60 * 1000
long hoursFromUTC = -4 * 60 * 60 * 1000 // EST with Daylight Time Savings
long d1 = (first.getTime() + hoursFromUTC) / oneDay
long d2 = (second.getTime() + hoursFromUTC) / oneDay
d1 == d2
A connection timeout is the maximum amount of time that the program is willing to wait to setup a connection to another process. You aren't getting or posting any application data at this point, just establishing the connection, itself.
A socket timeout is the timeout when waiting for individual packets. It's a common misconception that a socket timeout is the timeout to receive the full response. So if you have a socket timeout of 1 second, and a response comprised of 3 IP packets, where each response packet takes 0.9 seconds to arrive, for a total response time of 2.7 seconds, then there will be no timeout.
Use -to instead of -t: -to specifies the end time, -t specifies the duration
No to compare anything, you can simply check that by this...,.
if(document.getElementById("url")){ alert('exit');}
if($("#url")){alert('exist');}
you can also use the html() function as well like
if($("#url).html()){alert('exist');}
The reason why you get your error is because a "1 by n" matrix is different from an array of length n.
I recommend using hstack()
and vstack()
instead.
Like this:
import numpy as np
a = np.arange(32).reshape(4,8) # 4 rows 8 columns matrix.
b = a[:,-1:] # last column of that matrix.
result = np.hstack((a,b)) # stack them horizontally like this:
#array([[ 0, 1, 2, 3, 4, 5, 6, 7, 7],
# [ 8, 9, 10, 11, 12, 13, 14, 15, 15],
# [16, 17, 18, 19, 20, 21, 22, 23, 23],
# [24, 25, 26, 27, 28, 29, 30, 31, 31]])
Notice the repeated "7, 15, 23, 31" column.
Also, notice that I used a[:,-1:]
instead of a[:,-1]
. My version generates a column:
array([[7],
[15],
[23],
[31]])
Instead of a row array([7,15,23,31])
Edit: append()
is much slower. Read this answer.
Using ES6 syntax in React does not bind this
to user-defined functions however it will bind this
to the component lifecycle methods.
So the function that you declared will not have the same context as the class and trying to access this
will not give you what you are expecting.
For getting the context of class you have to bind the context of class to the function or use arrow functions.
Method 1 to bind the context:
class MyContainer extends Component {
constructor(props) {
super(props);
this.onMove = this.onMove.bind(this);
this.testVarible= "this is a test";
}
onMove() {
console.log(this.testVarible);
}
}
Method 2 to bind the context:
class MyContainer extends Component {
constructor(props) {
super(props);
this.testVarible= "this is a test";
}
onMove = () => {
console.log(this.testVarible);
}
}
Method 2 is my preferred way but you are free to choose your own.
Update: You can also create the properties on class without constructor:
class MyContainer extends Component {
testVarible= "this is a test";
onMove = () => {
console.log(this.testVarible);
}
}
Note If you want to update the view as well, you should use state
and setState
method when you set or change the value.
Example:
class MyContainer extends Component {
state = { testVarible: "this is a test" };
onMove = () => {
console.log(this.state.testVarible);
this.setState({ testVarible: "new value" });
}
}
The problem is that you mapped your servlet to /register.html
and it expects POST method, because you implemented only doPost()
method. So when you open register.html
page, it will not open html page with the form but servlet that handles the form data.
Alternatively when you submit POST form to non-existing URL, web container will display 405 error (method not allowed) instead of 404 (not found).
To fix:
<servlet-mapping>
<servlet-name>Register</servlet-name>
<url-pattern>/Register</url-pattern>
</servlet-mapping>
put %JAVA_HOME%\bin at the begin of PATH.
.*
and.+
are for any chars except for new lines.
Just in case, you would wanted to include new lines, the following expressions might also work for those languages that double escaping is required such as Java or C++:
[\\s\\S]*
[\\d\\D]*
[\\w\\W]*
for zero or more times, or
[\\s\\S]+
[\\d\\D]+
[\\w\\W]+
for one or more times.
Double escaping is not required for some languages such as, C#, PHP, Ruby, PERL, Python, JavaScript:
[\s\S]*
[\d\D]*
[\w\W]*
[\s\S]+
[\d\D]+
[\w\W]+
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RegularExpression{
public static void main(String[] args){
final String regex_1 = "[\\s\\S]*";
final String regex_2 = "[\\d\\D]*";
final String regex_3 = "[\\w\\W]*";
final String string = "AAA123\n\t"
+ "ABCDEFGH123\n\t"
+ "XXXX123\n\t";
final Pattern pattern_1 = Pattern.compile(regex_1);
final Pattern pattern_2 = Pattern.compile(regex_2);
final Pattern pattern_3 = Pattern.compile(regex_3);
final Matcher matcher_1 = pattern_1.matcher(string);
final Matcher matcher_2 = pattern_2.matcher(string);
final Matcher matcher_3 = pattern_3.matcher(string);
if (matcher_1.find()) {
System.out.println("Full Match for Expression 1: " + matcher_1.group(0));
}
if (matcher_2.find()) {
System.out.println("Full Match for Expression 2: " + matcher_2.group(0));
}
if (matcher_3.find()) {
System.out.println("Full Match for Expression 3: " + matcher_3.group(0));
}
}
}
Full Match for Expression 1: AAA123
ABCDEFGH123
XXXX123
Full Match for Expression 2: AAA123
ABCDEFGH123
XXXX123
Full Match for Expression 3: AAA123
ABCDEFGH123
XXXX123
If you wish to explore the expression, it's been explained on the top right panel of regex101.com. If you'd like, you can also watch in this link, how it would match against some sample inputs.
jex.im visualizes regular expressions:
$_ is an variable which iterates over each object/element passed from the previous | (pipe).
I think that you only have to replace SHA1 function with SHA256 function with tatk code from link in Your post
http://api.jquery.com/jQuery.inArray/
if ($.inArray('example', myArray) != -1)
{
// found it
}
In this specific case, the ToString() will return the name of the object retruned by the SelectedCell Property.( a collection of the currently selected cells).
This behavior occurs when an object has no specific implenetation for the ToString() methods.
in our case, all you have to do is to iterate the collection of the cells and to accumulate its values to a string. then push this string to the TextBox.
have a look here how to implement the iteration:
I have created Django Simple Mail to have a simple, customizable and reusable template for every transactional email you would like to send.
Emails contents and templates can be edited directly from django's admin.
With your example, you would register your email :
from simple_mail.mailer import BaseSimpleMail, simple_mailer
class WelcomeMail(BaseSimpleMail):
email_key = 'welcome'
def set_context(self, user_id, welcome_link):
user = User.objects.get(id=user_id)
return {
'user': user,
'welcome_link': welcome_link
}
simple_mailer.register(WelcomeMail)
And send it this way :
welcome_mail = WelcomeMail()
welcome_mail.set_context(user_id, welcome_link)
welcome_mail.send(to, from_email=None, bcc=[], connection=None, attachments=[],
headers={}, cc=[], reply_to=[], fail_silently=False)
I would love to get any feedback.
Lambdageek correctly points out that because associativity does not hold for floating-point numbers, the "optimization" of a*a*a*a*a*a
to (a*a*a)*(a*a*a)
may change the value. This is why it is disallowed by C99 (unless specifically allowed by the user, via compiler flag or pragma). Generally, the assumption is that the programmer wrote what she did for a reason, and the compiler should respect that. If you want (a*a*a)*(a*a*a)
, write that.
That can be a pain to write, though; why can't the compiler just do [what you consider to be] the right thing when you use pow(a,6)
? Because it would be the wrong thing to do. On a platform with a good math library, pow(a,6)
is significantly more accurate than either a*a*a*a*a*a
or (a*a*a)*(a*a*a)
. Just to provide some data, I ran a small experiment on my Mac Pro, measuring the worst error in evaluating a^6 for all single-precision floating numbers between [1,2):
worst relative error using powf(a, 6.f): 5.96e-08
worst relative error using (a*a*a)*(a*a*a): 2.94e-07
worst relative error using a*a*a*a*a*a: 2.58e-07
Using pow
instead of a multiplication tree reduces the error bound by a factor of 4. Compilers should not (and generally do not) make "optimizations" that increase error unless licensed to do so by the user (e.g. via -ffast-math
).
Note that GCC provides __builtin_powi(x,n)
as an alternative to pow( )
, which should generate an inline multiplication tree. Use that if you want to trade off accuracy for performance, but do not want to enable fast-math.
If you have a version of find
(such as GNU find
) that supports -printf
then there's no need to call stat
repeatedly:
find /some/dir -printf "%T+\n" | sort -nr | head -n 1
or
find /some/dir -printf "%TY-%Tm-%Td %TT\n" | sort -nr | head -n 1
If you don't need recursion, though:
stat --printf="%y\n" *
Just make sure put single space before and after "and" Keyword..
Maybe not as clean or efficient as the already posted solutions, but how about the .each() function? E.g:
var mvar = "";
$(".mbox").each(function() {
console.log($(this).html());
mvar += $(this).html();
});
console.log(mvar);
If you are programming in PHP, it is useful to split lines by \n
and then trim()
each line (provided you don't care about whitespace) to give you a "clean" line regardless.
foreach($line in explode("\n", $data))
{
$line = trim($line);
...
}
Join the table with itself and give it two different aliases (A
and B
in the following example). This allows to compare different rows of the same table.
SELECT DISTINCT A.Id
FROM
Address A
INNER JOIN Address B
ON A.Id = B.Id AND A.[Adress Code] < B.[Adress Code]
WHERE
A.Address <> B.Address
The "less than" comparison <
ensures that you get 2 different addresses and you don't get the same 2 address codes twice. Using "not equal" <>
instead, would yield the codes as (1, 2) and (2, 1); each one of them for the A
alias and the B
alias in turn.
The join clause is responsible for the pairing of the rows where as the where-clause tests additional conditions.
The query above works with any address codes. If you want to compare addresses with specific address codes, you can change the query to
SELECT A.Id
FROM
Address A
INNER JOIN Address B
ON A.Id = B.Id
WHERE
A.[Adress Code] = 1 AND
B.[Adress Code] = 2 AND
A.Address <> B.Address
I imagine that this might be useful to find customers having a billing address (Adress Code = 1 as an example) differing from the delivery address (Adress Code = 2) .
<FORM NAME=frm1 ...>
Name: <input type=textbox name=txtName id=txtName>
<BR>
<input type=button value="Submit" onclick=Validate()>
<Script>
function Validate() {
Msg = ""
// Check fields
if(frm1.txtName.value fails this) {
Msg += "\n The Name Field is improper"
}
// Do the same for the rest of the form
if(Msg == "") {
frm1.submit()
} else {
alert("Your form has errors\n" + Msg)
}
}
</SCRIPT>
net stop <your service> && net start <your service>
No net restart
, unfortunately.
The python error says that wordInput
is not an iterable -> it is of NoneType.
If you print wordInput
before the offending line, you will see that wordInput
is None
.
Since wordInput
is None
, that means that the argument passed to the function is also None
. In this case word
. You assign the result of pickEasy
to word
.
The problem is that your pickEasy
function does not return anything. In Python, a method that didn't return anything returns a NoneType.
I think you wanted to return a word
, so this will suffice:
def pickEasy():
word = random.choice(easyWords)
word = str(word)
for i in range(1, len(word) + 1):
wordCount.append("_")
return word
I think you should count the results with FOUND_ROWS() and SQL_CALC_FOUND_ROWS. You'll need two queries: select
, group_by
, etc. You'll add a plus select: SQL_CALC_FOUND_ROWS user_id
. After this query run a query: SELECT FOUND_ROWS()
. This will return the desired number.
You can't have a link to SCSS File in your HTML page.You have to compile it down to CSS First. No there are lots of video tutorials you might want to check out. Lynda provides great video tutorials on SASS. there are also free screencasts you can google...
For official documentation visit this site http://sass-lang.com/documentation/file.SASS_REFERENCE.html And why have you chosen notepad to write Sass?? you can easily download some free text editors for better code handling.
Q:How to access name array text field
<input type="text" id="task" name="task[]" />
Answer - Using Input name array :
$('input[name="task\\[\\]"]').eq(0).val()
$('input[name="task\\[\\]"]').eq(index).val()
Dont know, but you could perhaps check the source of one of the Firefox download addons.
Here is the source for one that I use Download Statusbar.
Simply, you can use FormCollection
like:
[HttpPost]
public ActionResult SubmitAction(FormCollection collection)
{
// Get Post Params Here
string var1 = collection["var1"];
}
You can also use a class, that is mapped with Form values, and asp.net mvc engine automagically fills it:
//Defined in another file
class MyForm
{
public string var1 { get; set; }
}
[HttpPost]
public ActionResult SubmitAction(MyForm form)
{
string var1 = form1.Var1;
}
It may not be exactly what you want, but my workaround is to apply the autowidth styling to a wrapper div - then set your input to 100%.
$about = DB::where('page', 'about-me')->first();
in stead of get()
.
It works on my project. Thanks.
You can use Addressable::URI
gem for that:
require 'addressable/uri'
string = '\x12\x34\x56\x78\x9a\xbc\xde\xf1\x23\x45\x67\x89\xab\xcd\xef\x12\x34\x56\x78\x9a'
Addressable::URI.encode_component(string, Addressable::URI::CharacterClasses::QUERY)
# "%5Cx12%5Cx34%5Cx56%5Cx78%5Cx9a%5Cxbc%5Cxde%5Cxf1%5Cx23%5Cx45%5Cx67%5Cx89%5Cxab%5Cxcd%5Cxef%5Cx12%5Cx34%5Cx56%5Cx78%5Cx9a"
It uses more modern format, than CGI.escape
, for example, it properly encodes space as %20
and not as +
sign, you can read more in "The application/x-www-form-urlencoded type" on Wikipedia.
2.1.2 :008 > CGI.escape('Hello, this is me')
=> "Hello%2C+this+is+me"
2.1.2 :009 > Addressable::URI.encode_component('Hello, this is me', Addressable::URI::CharacterClasses::QUERY)
=> "Hello,%20this%20is%20me"
@ is used as a prefix denoting stored procedure and function parameter names, and also variable names
While the above answers work but in case you have multiple devices connected to your computer then the following command can be used to remove the app from one of them:
adb -s <device-serial> shell pm uninstall <app-package-name>
If you want to find out the device serial then use the following command:
adb devices -l
This will give you a list of devices attached. The left column shows the device serials.
The other way is to create Indexes
for your collection and make sure that they are unique.
You can find more on the following link
I actually find this pretty simple and easy to implement.
In Access 2007 you just need to use Application.FileDialog
.
Here is the example from the Access documentation:
' Requires reference to Microsoft Office 12.0 Object Library. '
Private Sub cmdFileDialog_Click()
Dim fDialog As Office.FileDialog
Dim varFile As Variant
' Clear listbox contents. '
Me.FileList.RowSource = ""
' Set up the File Dialog. '
Set fDialog = Application.FileDialog(msoFileDialogFilePicker)
With fDialog
' Allow user to make multiple selections in dialog box '
.AllowMultiSelect = True
' Set the title of the dialog box. '
.Title = "Please select one or more files"
' Clear out the current filters, and add our own.'
.Filters.Clear
.Filters.Add "Access Databases", "*.MDB"
.Filters.Add "Access Projects", "*.ADP"
.Filters.Add "All Files", "*.*"
' Show the dialog box. If the .Show method returns True, the '
' user picked at least one file. If the .Show method returns '
' False, the user clicked Cancel. '
If .Show = True Then
'Loop through each file selected and add it to our list box. '
For Each varFile In .SelectedItems
Me.FileList.AddItem varFile
Next
Else
MsgBox "You clicked Cancel in the file dialog box."
End If
End With
End Sub
As the sample says, just make sure you have a reference to the Microsoft Access 12.0 Object Library (under the VBE IDE > Tools > References menu).
You cannot use a variable to access a property via dot notation, instead use the array notation.
var obj= {
'name' : 'jroi'
};
var a = 'name';
alert(obj.a); //will not work
alert(obj[a]); //should work and alert jroi'
Try doing a nav
element with a ul
element. Mine has a main
above but I don't think you need it.
<main>
<nav>
<ul><li><a href="http//www.google.com">search</a>
<li><a href="http//www.google.com">search</a>
<li><a href="http//www.google.com">search</a>
The code is something like this.
When ever I put in the code it wouldn't work right so you need to fill in the blank,
then center it.
main
nav
ul> li> a>: href="link of choice":name of link:/a>
Ruby's bundled JSON is capable of exhibiting a bit of magic on its own.
If you have a string containing JSON serialized data that you want to parse:
JSON[string_to_parse]
JSON will look at the parameter, see it's a String and try decoding it.
Similarly, if you have a hash or array you want serialized, use:
JSON[array_of_values]
Or:
JSON[hash_of_values]
And JSON will serialize it. You can also use the to_json
method if you want to avoid the visual similarity of the []
method.
Here are some examples:
hash_of_values = {'foo' => 1, 'bar' => 2}
array_of_values = [hash_of_values]
JSON[hash_of_values]
# => "{\"foo\":1,\"bar\":2}"
JSON[array_of_values]
# => "[{\"foo\":1,\"bar\":2}]"
string_to_parse = array_of_values.to_json
JSON[string_to_parse]
# => [{"foo"=>1, "bar"=>2}]
If you root around in JSON you might notice it's a subset of YAML, and, actually the YAML parser is what's handling JSON. You can do this too:
require 'yaml'
YAML.load(string_to_parse)
# => [{"foo"=>1, "bar"=>2}]
If your app is parsing both YAML and JSON, you can let YAML handle both flavors of serialized data.
use this..
$(".content_box a:not('.button')")
In the TortoiseSVN context menu, select 'Update to Revision', enter the desired revision number, and voilà :)
Don't do relative import.
From PEP8:
Relative imports for intra-package imports are highly discouraged.
Put all your code into one super package (i.e. "myapp") and use subpackages for client, server and common code.
Update: "Python 2.6 and 3.x supports proper relative imports (...)". See Dave's answers for more details.
if ( ($name eq "tom" and $password eq "123!")
or ($name eq "frank" and $password eq "321!")) {
print "You have gained access.";
}
else {
print "Access denied!";
}
Here I would like to present another alternative to Flatten function. This may help to understand what is going on internally. The alternative method adds three more code lines. Instead of using
#==========================================Build a Model
model = tf.keras.models.Sequential()
model.add(keras.layers.Flatten(input_shape=(28, 28, 3)))#reshapes to (2352)=28x28x3
model.add(layers.experimental.preprocessing.Rescaling(1./255))#normalize
model.add(keras.layers.Dense(128,activation=tf.nn.relu))
model.add(keras.layers.Dense(2,activation=tf.nn.softmax))
model.build()
model.summary()# summary of the model
we can use
#==========================================Build a Model
tensor = tf.keras.backend.placeholder(dtype=tf.float32, shape=(None, 28, 28, 3))
model = tf.keras.models.Sequential()
model.add(keras.layers.InputLayer(input_tensor=tensor))
model.add(keras.layers.Reshape([2352]))
model.add(layers.experimental.preprocessing.Rescaling(1./255))#normalize
model.add(keras.layers.Dense(128,activation=tf.nn.relu))
model.add(keras.layers.Dense(2,activation=tf.nn.softmax))
model.build()
model.summary()# summary of the model
In the second case, we first create a tensor (using a placeholder) and then create an Input layer. After, we reshape the tensor to flat form. So basically,
Create tensor->Create InputLayer->Reshape == Flatten
Flatten is a convenient function, doing all this automatically. Of course both ways has its specific use cases. Keras provides enough flexibility to manipulate the way you want to create a model.
Just create a data frame of empty vectors:
collect1 <- data.frame(id = character(0), max1 = numeric(0), max2 = numeric(0))
But if you know how many rows you're going to have in advance, you should just create the data frame with that many rows to start with.
There is no “universal” documentation that javascript caters to; every browser that has javascript is really an implementation. However, there is a standard that most modern browsers tend to follow, and that’s the EMCAScript standard; the ECMAScript standard strings would take, minimally, a modified implementation of the ISO 8601 definition.
In addition to this, there is a second standard set forward by the IETF that browsers tend to follow as well, which is the definition for timestamps made in the RFC 2822. Actual documentation can be found in the references list at the bottom.
From this you can expect basic functionality, but what “ought” to be is not inherently what “is”. I’m going to go a little in depth with this procedurally though, as it appears only three people actually answered the question (Scott, goofballLogic, and peller namely) which, to me, suggests most people are unaware of what actually happens when you create a Date object.
Where is the documentation which lists the format specifiers supported by the Date() object?
To answer the question, or typically even look for the answer to this question, you need to know that javascript is not a novel language; it’s actually an implementation of ECMAScript, and follows the ECMAScript standards (but note, javascript also actually pre-dated those standards; EMCAScript standards are built off the early implementation of LiveScript/JavaScript). The current ECMAScript standard is 5.1 (2011); at the time that the question was originally asked (June ’09), the standard was 3 (4 was abandoned), but 5 was released shortly after the post at the end of 2009. This should outline one problem; what standard a javascript implementation may follow, may not reflect what is actually in place, because a) it’s an implementation of a given standard, b) not all implementations of a standard are puritan, and c) functionality is not released in synchronization with a new standard as d) an implementation is a constant work in progress
Essentially, when dealing with javascript, you’re dealing with a derivative (javascript specific to the browser) of an implementation (javascript itself). Google’s V8, for example, implements ECMAScript 5.0, but Internet Explorer’s JScript doesn’t attempt to conform to any ECMAScript standard, yet Internet Explorer 9 does conform to ECMAScript 5.0.
When a single argument is passed to new Date(), it casts this function prototype:
new Date(value)
When two or more arguments are passed to new Date(), it casts this function prototype:
new Date (year, month [, date [, hours [, minutes [, seconds [, ms ] ] ] ] ] )
Both of those functions should look familiar, but this does not immediately answer your question and what quantifies as an acceptable “date format” requires further explanation. When you pass a string to new Date(), it will call the prototype (note that I'm using the word prototype loosely; the versions may be individual functions, or it may be part of a conditional statement in a single function) for new Date(value) with your string as the argument for the “value” parameter. This function will first check whether it is a number or a string. The documentation for this function can be found here:
http://www.ecma-international.org/ecma-262/5.1/#sec-15.9.3.2
From this, we can deduce that to get the string formatting allowed for new Date(value), we have to look at the method Date.parse(string). The documentation for this method can be found here:
http://www.ecma-international.org/ecma-262/5.1/#sec-15.9.4.2
And we can further infer that dates are expected to be in a modified ISO 8601 Extended Format, as specified here:
http://www.ecma-international.org/ecma-262/5.1/#sec-15.9.1.15
However, we can recognize from experience that javascript’s Date object accepts other formats (enforced by the existence of this question in the first place), and this is okay because ECMAScript allows for implementation specific formats. However, that still doesn’t answer the question of what documentation is available on the available formats, nor what formats are actually allowed. We’re going to look at Google’s javascript implementation, V8; please note I’m not suggesting this is the “best” javascript engine (how can one define “best” or even “good”) and one cannot assume that the formats allowed in V8 represent all formats available today, but I think it’s fair to assume they do follow modern expectations.
Google’s V8, date.js, DateConstructor
https://code.google.com/p/v8/source/browse/trunk/src/date.js?r=18400#141
Looking at the DateConstructor function, we can deduce we need to find the DateParse function; however, note that “year” is not the actual year and is only a reference to the “year” parameter.
Google’s V8, date.js, DateParse
https://code.google.com/p/v8/source/browse/trunk/src/date.js?r=18400#270
This calls %DateParseString, which is actually a run-time function reference for a C++ function. It refers to the following code:
Google’s V8, runtime.cc, %DateParseString
https://code.google.com/p/v8/source/browse/trunk/src/runtime.cc?r=18400#9559
The function call we’re concerned with in this function is for DateParser::Parse(); ignore the logic surrounding those function calls, these are just checks to conform to the encoding type (ASCII and UC16). DateParser::Parse is defined here:
Google's V8, dateparser-inl.h, DateParser::Parse
https://code.google.com/p/v8/source/browse/trunk/src/dateparser-inl.h?r=18400#36
This is the function that actually defines what formats it accepts. Essentially, it checks for the EMCAScript 5.0 ISO 8601 standard and if it is not standards compliant, then it will attempt to build the date based on legacy formats. A few key points based on the comments:
So this should be enough to give you a basic idea of what to expect when it comes to passing a string into a Date object. You can further expand upon this by looking at the following specification that Mozilla points to on the Mozilla Developer Network (compliant to the IETF RFC 2822 timestamps):
The Microsoft Developer Network additionally mentions an additional standard for the Date object: ECMA-402, the ECMAScript Internationalization API Specification, which is complementary to the ECMAScript 5.1 standard (and future ones). That can be found here:
In any case, this should aid in highlighting that there is no "documentation" that universally represents all implementations of javascript, but there is still enough documentation available to make reasonable sense of what strings are acceptable for a Date object. Quite the loaded question when you think about it, yes? :P
References
http://www.ecma-international.org/ecma-262/5.1/#sec-15.9.3.2
http://www.ecma-international.org/ecma-262/5.1/#sec-15.9.4.2
http://www.ecma-international.org/ecma-262/5.1/#sec-15.9.1.15
http://tools.ietf.org/html/rfc2822#page-14
http://www.ecma-international.org/ecma-402/1.0/
https://code.google.com/p/v8/source/browse/trunk/src/date.js?r=18400#141
https://code.google.com/p/v8/source/browse/trunk/src/date.js?r=18400#270
https://code.google.com/p/v8/source/browse/trunk/src/runtime.cc?r=18400#9559
https://code.google.com/p/v8/source/browse/trunk/src/dateparser-inl.h?r=18400#36
Resources
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date
http://msdn.microsoft.com/en-us/library/ff743760(v=vs.94).aspx
Here is the right way to do imports in Java.
import Dan.Vik;
class Kab
{
public static void main(String args[])
{
Vik Sam = new Vik();
Sam.disp();
}
}
You don't import methods in java. There is an advanced usage of static imports but basically you just import packages and classes. If the function you are importing is a static function you can do a static import, but I don't think you are looking for static imports here.
I had the same problem but solved it in this way:
df = pd.read_csv('your-array.csv', skiprows=[0])
For android 2.2+ (api level8), you can use ScaleGestureDetector.
you need a member:
private ScaleGestureDetector mScaleDetector;
in your constructor (or onCreate()) you add:
mScaleDetector = new ScaleGestureDetector(context, new OnScaleGestureListener() {
@Override
public void onScaleEnd(ScaleGestureDetector detector) {
}
@Override
public boolean onScaleBegin(ScaleGestureDetector detector) {
return true;
}
@Override
public boolean onScale(ScaleGestureDetector detector) {
Log.d(LOG_KEY, "zoom ongoing, scale: " + detector.getScaleFactor());
return false;
}
});
You override onTouchEvent:
@Override
public boolean onTouchEvent(MotionEvent event) {
mScaleDetector.onTouchEvent(event);
return true;
}
If you draw your View by hand, in the onScale() you probably do store the scale factor in a member, then call invalidate() and use the scale factor when drawing in your onDraw(). Otherwise you can directly modify font sizes or things like that in the onScale().
You're looking for:
.is(':visible')
Although you should probably change your selector to use jQuery considering you're using it in other places anyway:
if($('#testElement').is(':visible')) {
// Code
}
It is important to note that if any one of a target element's parent elements are hidden, then .is(':visible')
on the child will return false
(which makes sense).
:visible
has had a reputation for being quite a slow selector as it has to traverse up the DOM tree inspecting a bunch of elements. There's good news for jQuery 3, however, as this post explains (Ctrl + F for :visible
):
Thanks to some detective work by Paul Irish at Google, we identified some cases where we could skip a bunch of extra work when custom selectors like :visible are used many times in the same document. That particular case is up to 17 times faster now!
Keep in mind that even with this improvement, selectors like :visible and :hidden can be expensive because they depend on the browser to determine whether elements are actually displaying on the page. That may require, in the worst case, a complete recalculation of CSS styles and page layout! While we don’t discourage their use in most cases, we recommend testing your pages to determine if these selectors are causing performance issues.
Expanding even further to your specific use case, there is a built in jQuery function called $.fadeToggle()
:
function toggleTestElement() {
$('#testElement').fadeToggle('fast');
}
In .cs file
grid.DataContext = table.DefaultView;
In xaml file
<DataGrid Name="grid" ItemsSource="{Binding}">
table {
border-collapse: collapse;
}
td {
padding-top: .5em;
padding-bottom: .5em;
}
The cells won't react to anything unless you set the border-collapse first. You can also add borders to TR elements once that's set (among other things.)
If this is for layout, I'd move to using DIVs and more up-to-date layout techniques, but if this is tabular data, knock yourself out. I still make heavy use of tables in my web applications for data.
great one... now i have stopped using % he he he... except for the main container as shown below:
<div id="divContainer">
<div id="divHeader">
</div>
<div id="divContentArea">
<div id="divContentLeft">
</div>
<div id="divContentRight">
</div>
</div>
<div id="divFooter">
</div>
</div>
and here is the css:
#divContainer {
width: 100%;
height: 100%;
}
#divHeader {
position: absolute;
left: 0px;
top: 0px;
right: 0px;
height: 28px;
}
#divContentArea {
position: absolute;
left: 0px;
top: 30px;
right: 0px;
bottom: 30px;
}
#divContentLeft {
position: absolute;
top: 0px;
left: 0px;
width: 250px;
bottom: 0px;
}
#divContentRight {
position: absolute;
top: 0px;
left: 254px;
right: 0px;
bottom: 0px;
}
#divFooter {
position: absolute;
height: 28px;
left: 0px;
bottom: 0px;
right: 0px;
}
i tested this in all known browsers and is working fine. Are there any drawbacks using this way?
The server_name
docs directive is used to identify virtual hosts, they're not used to set the binding.
netstat
tells you that nginx listens on 0.0.0.0:80
which means that it will accept connections from any IP.
If you want to change the IP nginx binds on, you have to change the listen
docs rule.
So, if you want to set nginx to bind to localhost
, you'd change that to:
listen 127.0.0.1:80;
In this way, requests that are not coming from localhost are discarded (they don't even hit nginx).
To accomplish the same thing as:
svn st | awk '{print $2}' | xargs rm
using only bash you can use:
svn st | while read a b; do rm "$b"; done
Granted, it's not shorter, but it's a bit more efficient and it handles whitespace in your filenames correctly.
Just use
composer require {package/packagename}
like
composer require phpmailer/phpmailer
if the package is not in the vendor folder.. composer installs it and if the package exists, composer update package to the latest version.
You could also use:
SELECT t.*
FROM
TABLENAME t
JOIN
( SELECT A, MAX(col_date) AS col_date
FROM TABLENAME
GROUP BY A
) m
ON m.A = t.A
AND m.col_date = t.col_date
Yes, struct
is exactly like class
except the default accessibility is public
for struct
(while it's private
for class
).
With Spring MVC 4.2.1.RELEASE, you need to use the new Jackson2 dependencies as below for the Deserializer to work.
Dont use this
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>1.9.12</version>
</dependency>
Use this instead.
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.2.2</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.2.2</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.2.2</version>
</dependency>
Also use com.fasterxml.jackson.databind.JsonDeserializer
and com.fasterxml.jackson.databind.annotation.JsonDeserialize
for the deserialization and not the classes from org.codehaus.jackson
You could also try CheckIO which is kind of a quest where you have to post solutions in Python 2.7 or 3.3 to move up in the game. Fun and has quite a big community for questions and support.
From their Main Wiki Page:
Welcome to CheckIO – a service that has united all levels of Python developers – from beginners up to the real experts!
Here you can learn Python coding, try yourself in solving various kinds of problems and share your ideas with others. Moreover, you can consider original solutions of other users, exchange opinions and find new friends.
If you are just starting with Python – CheckIO is a great chance for you to learn the basics and get a rich practice in solving different tasks. If you’re an experienced coder, here you’ll find an exciting opportunity to perfect your skills and learn new alternative logics from others. On CheckIO you can not only resolve the existing tasks, but also provide your own ones and even get points for them. Enjoy the possibility of playing logical games, participating in exciting competitions and share your success with friends in CheckIO.org!
You should place Scanner input = new Scanner (System.in);
into the main method rather than creating the input object outside.
You want
#content div:first-child {
/*css*/
}
The easiest way would be using Substring
string str = "AM0122200204";
string substr = str.Substring(str.Length - 3);
Using the overload with one int
as I put would get the substring
of a string
, starting from the index int
. In your case being str.Length - 3
, since you want to get the last three chars.
You can use a one-liner with DOCKER_HOST
variable:
docker save app:1.0 | gzip | DOCKER_HOST=ssh://user@remotehost docker load
var input_val=document.getElementById('my_variable');for (i=0; i<input_val.length; i++) {
xx = input_val[i];``
if (xx.name == "ans") {
new = xx.value;
alert(new); }}
I had the same problem but after deleting the old plugin for org.codehaus.mojo it worked.
I use this
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<version>1.2</version>
</plugin>
To populate the drop-down select box in laravel we have to follow the below steps.
From controller we have to get the value like this:
public function addCustomerLoyaltyCardDetails(){
$loyalityCardMaster = DB::table('loyality_cards')->pluck('loyality_card_id', 'loyalityCardNumber');
return view('admin.AddCustomerLoyaltyCardScreen')->with('loyalityCardMaster',$loyalityCardMaster);
}
And the same we can display in view:
<select class="form-control" id="loyalityCardNumber" name="loyalityCardNumber" >
@foreach ($loyalityCardMaster as $id => $name)
<option value="{{$name}}">{{$id}}</option>
@endforeach
</select>
This key value in drop down you can use as per your requirement. Hope it may help someone.
Hope this helps somebody!
<style> html { scroll-behavior: smooth;} </style>
<a id="top"></>
<!--content here-->
<a href="#top">Back to top..</a>
Fake IE10 to install Visual Studio 2013
Visual Studio 2013 requires Internet Explorer 10. If you try to install it on Windows 7 with IE8 you get the following error This version of Visual Studio requires Internet Explorer 10”. The value that the VS 2013 installer checks is svcVersion in the
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Internet Explorer
key on 32-bit Windows andHKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\Internet Explorer
on 64-bit Windows. Any value >= 10.0.0.0 makes the installer happy.
[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Internet Explorer]
"svcVersion"="10.0.0.0"
[HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\Internet Explorer]
"svcVersion"="10.0.0.0"
Utilizing/Copying Darin Dimitrov's great response, this is how to access a custom attribute on a property and not a class:
The decorated property [of class Foo
]:
[MyCustomAttribute(SomeProperty = "This is a custom property")]
public string MyProperty { get; set; }
Fetching it:
PropertyInfo propertyInfo = typeof(Foo).GetProperty(propertyToCheck);
object[] attribute = propertyInfo.GetCustomAttributes(typeof(MyCustomAttribute), true);
if (attribute.Length > 0)
{
MyCustomAttribute myAttribute = (MyCustomAttribute)attribute[0];
string propertyValue = myAttribute.SomeProperty;
}
You can throw this in a loop and use reflection to access this custom attribute on each property of class Foo
, as well:
foreach (PropertyInfo propertyInfo in Foo.GetType().GetProperties())
{
string propertyName = propertyInfo.Name;
object[] attribute = propertyInfo.GetCustomAttributes(typeof(MyCustomAttribute), true);
// Just in case you have a property without this annotation
if (attribute.Length > 0)
{
MyCustomAttribute myAttribute = (MyCustomAttribute)attribute[0];
string propertyValue = myAttribute.SomeProperty;
// TODO: whatever you need with this propertyValue
}
}
Major thanks to you, Darin!!
Typically with Angular you would be outputting these spans using the ngRepeat directive and (like in your case) each item would have an id. I know this is not true for all situations but it is typical if requesting data from a backend - objects in an array tend to have unique identifiers.
You can use this id to facilitate the toggling of classes on items in your list (see plunkr or code below).
Using the objects id's can also eliminate the undesirable effect when the $index (described in other answers) is messed up due to sorting in Angular.
Example Plunkr: http://plnkr.co/edit/na0gUec6cdMABK9L6drV
(basically apply the .active-selection class if the person.id is equal to $scope.activeClass - which we set when the user clicks an item.
Hope this helps someone, I've found expressions in ng-class to be very useful!
HTML
<ul>
<li ng-repeat="person in people"
data-ng-class="{'active-selection': person.id == activeClass}">
<a data-ng-click="selectPerson(person.id)">
{{person.name}}
</a>
</li>
</ul>
JS
app.controller('MainCtrl', function($scope) {
$scope.people = [{
id: "1",
name: "John",
}, {
id: "2",
name: "Lucy"
}, {
id: "3",
name: "Mark"
}, {
id: "4",
name: "Sam"
}];
$scope.selectPerson = function(id) {
$scope.activeClass = id;
console.log(id);
};
});
CSS:
.active-selection {
background-color: #eee;
}
Small update due to golang api change, please omit .UTC() :
time.Now().UTC().UnixNano() -> time.Now().UnixNano()
import (
"fmt"
"math/rand"
"time"
)
func main() {
rand.Seed(time.Now().UnixNano())
fmt.Println(randomInt(100, 1000))
}
func randInt(min int, max int) int {
return min + rand.Intn(max-min)
}
Hook onto your manager and make a new connection:
$manager = $this->getDoctrine()->getManager();
$conn = $manager->getConnection();
Create your query and fetchAll:
$result= $conn->query('select foobar from mytable')->fetchAll();
Get the data out of result like this:
$this->appendStringToFile("first row foobar is: " . $result[0]['foobar']);
The fancy new Java 8 way is Date.from(timestamp.toInstant())
. See my similar answer elsewhere.
This happened to me after I renamed a file. For some reason it was still looking for the file with the old name. What I did was create the file that it was complaining about and added to the project. Then I did a Project->clean, then Project->Build and verified the error was gone. Then I selected the newly added files and deleted them. This removed all references and I no longer see the error.
Maybe you are trying to do
string combindedString = string.Join( ",", myList.ToArray() );
You can replace "," with what you want to split the elements in the list by.
Edit: As mention in the comments you could also do
string combindedString = string.Join( ",", myList);
Reference:
Join<T>(String, IEnumerable<T>)
Concatenates the members of a collection, using the specified separator between each member.
Based on Piotr Migdals response I want to give an alternate solution enabling the possibility for a vector of strings:
myVectorOfStrings <- c("foo", "bar")
matchExpression <- paste(myVectorOfStrings, collapse = "|")
# [1] "foo|bar"
df %>% select(matches(matchExpression))
Making use of the regex OR
operator (|
)
ATTENTION: If you really have a plain vector of column names (and do not need the power of RegExpression), please see the comment below this answer (since it's the cleaner solution).
This will do what you want, uses an input file and is super fast
#!/bin/bash
IFS=$'\n'
file=/path/to/input.txt
lines=$(cat ${file})
for line in ${lines}; do
curl "${line}"
done
IFS=""
exit ${?}
one entry per line on your input file, it will follow the order of your input file
save it as whatever.sh and make it executable
var span_Text = document.getElementById("span_Id").innerText;_x000D_
_x000D_
console.log(span_Text)
_x000D_
<span id="span_Id">I am the Text </span>
_x000D_
To be short:
firstBigDecimal.compareTo(secondBigDecimal) < 0 // "<"
firstBigDecimal.compareTo(secondBigDecimal) > 0 // ">"
firstBigDecimal.compareTo(secondBigDecimal) == 0 // "=="
firstBigDecimal.compareTo(secondBigDecimal) >= 0 // ">="
If you want to get an integer for the enum value that is stored in a variable, for which the type would be Question
, to use for example in a method, you can simply do this I wrote in this example:
enum Talen
{
Engels = 1, Italiaans = 2, Portugees = 3, Nederlands = 4, Duits = 5, Dens = 6
}
Talen Geselecteerd;
public void Form1()
{
InitializeComponent()
Geselecteerd = Talen.Nederlands;
}
// You can use the Enum type as a parameter, so any enumeration from any enumerator can be used as parameter
void VeranderenTitel(Enum e)
{
this.Text = Convert.ToInt32(e).ToString();
}
This will change the window title to 4, because the variable Geselecteerd
is Talen.Nederlands
. If I change it to Talen.Portugees
and call the method again, the text will change to 3.
The symptoms perfectly describes the case when the found class doesn't have associated (or assigned) source.
But what if Eclipse still suggest that you attach source, even if I correctly set my classes and their sources:
This almost always means that Eclipse is finding the class from different place than you expect. Inspect your source lookup path to see where it might get the wrong class. Update the path accordingly to your findings.
Eclipse doesn't find anything at all, when breakpoint is hit:
This happens, when you are source lookup path doesn't contain the class, which is currently loaded in the runtime. Even if the class is in the workspace, it can be invisible to the launch configuration, because Eclipse follows the source lookup path strictly and attaches only the dependencies of the project, which is currently debugged.
An exception is the debugging bundles in PDE. In this case, because the runtime is composed from multiple projects, which doesn't have to declare dependencies on one another, Eclipse will automatically find the class in the workspace, even if it is not available in the source lookup path.
I cannot see the variables when I hit a breakpoint or it just opens the source, but doesn't select the breakpoint line:
This means that in the runtime, either the JVM or the classes themselves doesn't have the necessary debug information. Each time classes are compiled, debug information can be attached. To reduce the storage space of the classes, sometimes this information is omitted, which makes debugging such code a pain. Your only chance is to try and recompile with debug enabled.
Eclipse source viewer shows different lines than those that are actually executed:
It sometimes can show that empty space is executed as well. This means that your sources doesn't match your runtime version of the classes. Even if you think that this is not possible, it is, so make sure you setup the correct sources. Or your runtime match your latest changes, depending on what are you trying to do.
create_function
did not work for me inside a class. I had to use call_user_func
.
<?php
class Dispatcher {
//Added explicit callback declaration.
var $callback;
public function Dispatcher( $callback ){
$this->callback = $callback;
}
public function asynchronous_method(){
//do asynch stuff, like fwrite...then, fire callback.
if ( isset( $this->callback ) ) {
if (function_exists( $this->callback )) call_user_func( $this->callback, "File done!" );
}
}
}
Then, to use:
<?php
include_once('Dispatcher.php');
$d = new Dispatcher( 'do_callback' );
$d->asynchronous_method();
function do_callback( $data ){
print 'Data is: ' . $data . "\n";
}
?>
[Edit] Added a missing parenthesis. Also, added the callback declaration, I prefer it that way.
myWebView.loadData(myHtmlString, "text/html; charset=UTF-8", null);
This works flawlessly, especially on Android 4.0, which apparently ignores character encoding inside HTML.
Tested on 2.3 and 4.0.3.
In fact, I have no idea about what other values besides "base64" does the last parameter take. Some Google examples put null in there.
nodejs domains is the most up to date way of handling errors in nodejs. Domains can capture both error/other events as well as traditionally thrown objects. Domains also provide functionality for handling callbacks with an error passed as the first argument via the intercept method.
As with normal try/catch-style error handling, is is usually best to throw errors when they occur, and block out areas where you want to isolate errors from affecting the rest of the code. The way to "block out" these areas are to call domain.run with a function as a block of isolated code.
In synchronous code, the above is enough - when an error happens you either let it be thrown through, or you catch it and handle there, reverting any data you need to revert.
try {
//something
} catch(e) {
// handle data reversion
// probably log too
}
When the error happens in an asynchronous callback, you either need to be able to fully handle the rollback of data (shared state, external data like databases, etc). OR you have to set something to indicate that an exception has happened - where ever you care about that flag, you have to wait for the callback to complete.
var err = null;
var d = require('domain').create();
d.on('error', function(e) {
err = e;
// any additional error handling
}
d.run(function() { Fiber(function() {
// do stuff
var future = somethingAsynchronous();
// more stuff
future.wait(); // here we care about the error
if(err != null) {
// handle data reversion
// probably log too
}
})});
Some of that above code is ugly, but you can create patterns for yourself to make it prettier, eg:
var specialDomain = specialDomain(function() {
// do stuff
var future = somethingAsynchronous();
// more stuff
future.wait(); // here we care about the error
if(specialDomain.error()) {
// handle data reversion
// probably log too
}
}, function() { // "catch"
// any additional error handling
});
UPDATE (2013-09):
Above, I use a future that implies fibers semantics, which allow you to wait on futures in-line. This actually allows you to use traditional try-catch blocks for everything - which I find to be the best way to go. However, you can't always do this (ie in the browser)...
There are also futures that don't require fibers semantics (which then work with normal, browsery JavaScript). These can be called futures, promises, or deferreds (I'll just refer to futures from here on). Plain-old-JavaScript futures libraries allow errors to be propagated between futures. Only some of these libraries allow any thrown future to be correctly handled, so beware.
An example:
returnsAFuture().then(function() {
console.log('1')
return doSomething() // also returns a future
}).then(function() {
console.log('2')
throw Error("oops an error was thrown")
}).then(function() {
console.log('3')
}).catch(function(exception) {
console.log('handler')
// handle the exception
}).done()
This mimics a normal try-catch, even though the pieces are asynchronous. It would print:
1
2
handler
Note that it doesn't print '3' because an exception was thrown that interrupts that flow.
Take a look at bluebird promises:
Note that I haven't found many other libraries other than these that properly handle thrown exceptions. jQuery's deferred, for example, don't - the "fail" handler would never get the exception thrown an a 'then' handler, which in my opinion is a deal breaker.
var redBox = $(".post");
var greenBox = $(".post1");
var offset = redBox.offset();
$(".post1").css({'left': +offset.left});
$(".post1").html("Left :" +offset.left);
// **For multiple permission you can use this code :**
// **First:**
//Write down in onCreate method.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
requestPermissions(new String[]{
android.Manifest.permission.READ_EXTERNAL_STORAGE,
android.Manifest.permission.CAMERA},
MY_PERMISSIONS_REQUEST);
}
//**Second:**
//Write down in a activity.
@Override
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResults) {
switch (requestCode) {
case MY_PERMISSIONS_REQUEST:
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
progressBar.setVisibility(View.GONE);
Intent i = new Intent(SplashActivity.this,
HomeActivity.class);
startActivity(i);
finish();
}
}, SPLASH_DISPLAY_LENGTH);
} else {
finish();
}
return;
}
}
If you need different column width, do this:
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td colspan="9">
<table>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
</table>
</td>
</tr>
List
interface have several different classes - ArrayList
and LinkedList
. LinkedList
is used to create an indexed collections and ArrayList
- to create sorted lists. So, you can use any of it in your arguments, but you can allow others developers who use your code, library, etc. to use different types of lists, not only which you use, so, in this method
ArrayList<Object> myMethod (ArrayList<Object> input) {
// body
}
you can use it only with ArrayList
, not LinkedList
, but you can allow to use any of List
classes on other places where it method is using, it's just your choise, so using an interface can allow it:
List<Object> myMethod (List<Object> input) {
// body
}
In this method arguments you can use any of List
classes which you want to use:
List<Object> list = new ArrayList<Object> ();
list.add ("string");
myMethod (list);
CONCLUSION:
Use the interfaces everywhere when it possible, don't restrict you or others to use different methods which they want to use.
Actually I use _ method names when I need to differ between parent and child class names. I've read some codes that used this way of creating parent-child classes. As an example I can provide this code:
class ThreadableMixin:
def start_worker(self):
threading.Thread(target=self.worker).start()
def worker(self):
try:
self._worker()
except tornado.web.HTTPError, e:
self.set_status(e.status_code)
except:
logging.error("_worker problem", exc_info=True)
self.set_status(500)
tornado.ioloop.IOLoop.instance().add_callback(self.async_callback(self.results))
...
and the child that have a _worker method
class Handler(tornado.web.RequestHandler, ThreadableMixin):
def _worker(self):
self.res = self.render_string("template.html",
title = _("Title"),
data = self.application.db.query("select ... where object_id=%s", self.object_id)
)
...
Don't think of css classes as object oriented classes, think of them as merely a tool among other selectors to specify which attribute classes an html element is styled by. Think of everything between the braces as the attribute class, and selectors on the left-hand side tell the elements they select to inherit attributes from the attribute class. Example:
.foo, .bar { font-weight : bold; font-size : 2em; /* attribute class A */}
.foo { color : green; /* attribute class B */}
When an element is given the attribute class="foo"
, it is useful to think of it not as inheriting attributes from class .foo
, but from attribute class A and attribute class B. I.e., the inheritance graph is one level deep, with elements deriving from attribute classes, and the selectors specifying where the edges go, and determining precedence when there are competing attributes (similar to method resolution order).
The practical implication for programming is this. Say you have the style sheet given above, and want to add a new class .baz
, where it should have the same font-size
as .foo
. The naive solution would be this:
.foo, .bar { font-weight : bold; font-size : 2em; /* attribute class A */}
.foo { color : green; /* attribute class B */}
.baz { font-size : 2em; /* attribute class C, hidden dependency! */}
Any time I have to type something twice I get so mad! Not only do I have to write it twice, now I have no way of programatically indicating that .foo
and .baz
should have the same font-size
, and I've created a hidden dependency! My above paradigm would suggest that I should abstract out the font-size
attribute from attribute class A:
.foo, .bar, .baz { font-size : 2em; /* attribute base class for A */}
.foo, .bar { font-weight : bold; /* attribute class A */}
.foo { color : green; /* attribute class B */}
The main complaint here is that now I have to retype every selector from attribute class A again to specify that the elements they should select should also inherit attributes from attribute base class A. Still, the alternatives are to have to remember to edit every attribute class where there are hidden dependencies each time something changes, or to use a third party tool. The first option makes god laugh, the second makes me want to kill myself.
Use SelectionChangeCommitted(object sender, EventArgs e)
event
here
Try this code it is already built in c#
int lastDay = DateTime.DaysInMonth (2014, 2);
and the first day is always 1.
Good Luck!
Default text size vary from device to devices
Type Dimension Micro 12 sp Small 14 sp Medium 18 sp Large 22 sp
Here's another alternative if, for any reason, you can't or don't want to use HttpUtility.ParseQueryString()
.
This is built to be somewhat tolerant to "malformed" query strings, i.e. http://test/test.html?empty=
becomes a parameter with an empty value. The caller can verify the parameters if needed.
public static class UriHelper
{
public static Dictionary<string, string> DecodeQueryParameters(this Uri uri)
{
if (uri == null)
throw new ArgumentNullException("uri");
if (uri.Query.Length == 0)
return new Dictionary<string, string>();
return uri.Query.TrimStart('?')
.Split(new[] { '&', ';' }, StringSplitOptions.RemoveEmptyEntries)
.Select(parameter => parameter.Split(new[] { '=' }, StringSplitOptions.RemoveEmptyEntries))
.GroupBy(parts => parts[0],
parts => parts.Length > 2 ? string.Join("=", parts, 1, parts.Length - 1) : (parts.Length > 1 ? parts[1] : ""))
.ToDictionary(grouping => grouping.Key,
grouping => string.Join(",", grouping));
}
}
Test
[TestClass]
public class UriHelperTest
{
[TestMethod]
public void DecodeQueryParameters()
{
DecodeQueryParametersTest("http://test/test.html", new Dictionary<string, string>());
DecodeQueryParametersTest("http://test/test.html?", new Dictionary<string, string>());
DecodeQueryParametersTest("http://test/test.html?key=bla/blub.xml", new Dictionary<string, string> { { "key", "bla/blub.xml" } });
DecodeQueryParametersTest("http://test/test.html?eins=1&zwei=2", new Dictionary<string, string> { { "eins", "1" }, { "zwei", "2" } });
DecodeQueryParametersTest("http://test/test.html?empty", new Dictionary<string, string> { { "empty", "" } });
DecodeQueryParametersTest("http://test/test.html?empty=", new Dictionary<string, string> { { "empty", "" } });
DecodeQueryParametersTest("http://test/test.html?key=1&", new Dictionary<string, string> { { "key", "1" } });
DecodeQueryParametersTest("http://test/test.html?key=value?&b=c", new Dictionary<string, string> { { "key", "value?" }, { "b", "c" } });
DecodeQueryParametersTest("http://test/test.html?key=value=what", new Dictionary<string, string> { { "key", "value=what" } });
DecodeQueryParametersTest("http://www.google.com/search?q=energy+edge&rls=com.microsoft:en-au&ie=UTF-8&oe=UTF-8&startIndex=&startPage=1%22",
new Dictionary<string, string>
{
{ "q", "energy+edge" },
{ "rls", "com.microsoft:en-au" },
{ "ie", "UTF-8" },
{ "oe", "UTF-8" },
{ "startIndex", "" },
{ "startPage", "1%22" },
});
DecodeQueryParametersTest("http://test/test.html?key=value;key=anotherValue", new Dictionary<string, string> { { "key", "value,anotherValue" } });
}
private static void DecodeQueryParametersTest(string uri, Dictionary<string, string> expected)
{
Dictionary<string, string> parameters = new Uri(uri).DecodeQueryParameters();
Assert.AreEqual(expected.Count, parameters.Count, "Wrong parameter count. Uri: {0}", uri);
foreach (var key in expected.Keys)
{
Assert.IsTrue(parameters.ContainsKey(key), "Missing parameter key {0}. Uri: {1}", key, uri);
Assert.AreEqual(expected[key], parameters[key], "Wrong parameter value for {0}. Uri: {1}", parameters[key], uri);
}
}
}
cURL > 7.18.0 has an option --data-urlencode
which solves this problem. Using this, I can simply send a POST request as
curl -d name=john --data-urlencode passwd=@31&3*J https://www.mysite.com
class expression can be used for simplicity.
// Foo.js
'use strict';
// export default class Foo {}
module.exports = class Foo {}
-
// main.js
'use strict';
const Foo = require('./Foo.js');
let Bar = new class extends Foo {
constructor() {
super();
this.name = 'bar';
}
}
console.log(Bar.name);
http://joda-time.sourceforge.net/quickstart.html
Each datetime class provides a variety of constructors. These include the Object constructor. This allows you to construct, for example, DateTime from the following objects:
* Date - a JDK instant
* Calendar - a JDK calendar
* String - in ISO8601 format
* Long - in milliseconds
* any Joda-Time datetime class
Be careful when using Application.Transpose with a huge number of values. If you transpose values to a column, excel will assume you are assuming you transposed them from rows.
Max Column Limit < Max Row Limit, and it will only display the first (Max Column Limit) values, and anithing after that will be "N/A"
Install the readr
package, then use library(readr)
.
1) Your cron is wrong. If you want to run job every 15 mins on Jenkins use this:
H/15 * * * *
2) Warning from Jenkins Spread load evenly by using ‘...’ rather than ‘...’
came with JENKINS-17311:
To allow periodically scheduled tasks to produce even load on the system, the symbol H (for “hash”) should be used wherever possible. For example, using 0 0 * * * for a dozen daily jobs will cause a large spike at midnight. In contrast, using H H * * * would still execute each job once a day, but not all at the same time, better using limited resources.
Examples:
H/15 * * * *
- every fifteen minutes (perhaps at :07, :22, :37, :52):H(0-29)/10 * * * *
- every ten minutes in the first half of every hour (three times, perhaps at :04, :14, :24)H 9-16/2 * * 1-5
- once every two hours every weekday (perhaps at 10:38 AM, 12:38 PM, 2:38 PM, 4:38 PM)H H 1,15 1-11 *
- once a day on the 1st and 15th of every month except DecemberHow about using sort
?
dir /b /s | sort
Here's an example I tested with:
dir /s /b /o:gn
d:\root0
d:\root0\root1
d:\root0\root1\folderA
d:\root0\root1\folderB
d:\root0\root1\file00.txt
d:\root0\root1\file01.txt
d:\root0\root1\folderA\fileA00.txt
d:\root0\root1\folderA\fileA01.txt
d:\root0\root1\folderB\fileB00.txt
d:\root0\root1\folderB\fileB01.txt
dir /s /b | sort
d:\root0
d:\root0\root1
d:\root0\root1\file00.txt
d:\root0\root1\file01.txt
d:\root0\root1\folderA
d:\root0\root1\folderA\fileA00.txt
d:\root0\root1\folderA\fileA01.txt
d:\root0\root1\folderB
d:\root0\root1\folderB\fileB00.txt
d:\root0\root1\folderB\fileB01.txt
To just get directories, use the /A:D
parameter:
dir /a:d /s /b | sort
Try to remove the constructor and destructors, it's working for me....
configure static ip on the raspberry pi:
sudo nano /etc/network/interfaces
and then add:
iface eth0 inet static
address 169.254.0.2
netmask 255.255.255.0
broadcast 169.254.0.255
then you can acces your raspberry via ssh
ssh [email protected]
I have come across other similar question here. Both of above answers are perfect, but here trying to add additional information for someone looking for SOAP1.1, and not SOAP1.2.
Just change one line code provided by @acdcjunior, use SOAPMessageFactory1_1Impl
implementation, it will change namespace to xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/", which is SOAP1.1 implementation.
Change callSoapWebService
method first line to following.
SOAPMessage soapMessage = SOAPMessageFactory1_1Impl.newInstance().createMessage();
I hope it will be helpful to others.
If you're hoping to use background-image: url(...);
, I don't think you can. However, if you want to play with layering, you can do something like this:
<img class="bg" src="..." />
And then some CSS:
.bg
{
width: 100%;
z-index: 0;
}
You can now layer content above the stretched image by playing with z-indexes and such. One quick note, the image can't be contained in any other elements for the width: 100%;
to apply to the whole page.
Here's a quick demo if you can't rely on background-size
: http://jsfiddle.net/bB3Uc/