if you are using vs code just try using background:url("img/bimg.jpg") instead of background:url('img/bimg.jpg') Mine worked at it Nothing much I replaced ' with "
Unless you want to loop through the string and do it "manually" you could solve it like this:
yourString.replace("", " ").trim()
This replaces all "empty substrings" with a space, and then trims off the leading / trailing spaces.
An alternative solution using regular expressions:
yourString.replaceAll(".(?=.)", "$0 ")
Basically it says "Replace all characters (except the last one) with with the character itself followed by a space".
Documentation of...
String.replaceAll
(including the $0
syntax)(?=.)
syntax)As far as I know, there isn't a cross-JPA-Provider way to specify indexes. However, you can always create them by hand directly in the database, most databases will pick them up automatically during query planning.
So for everyone starting out with XAMPP cgi
change the extension from pl to cgi
change the permissions to 755
mv test.pl test.cgi
chmod 755 test.cgi
It fixed mine as well.
I found a jfiddle that might help here: http://jsfiddle.net/jaredwilli/SfJ8c/
Ive refactored the code to make it simpler for this.
// In your controller
var w = angular.element($window);
$scope.$watch(
function () {
return $window.innerWidth;
},
function (value) {
$scope.windowWidth = value;
},
true
);
w.bind('resize', function(){
$scope.$apply();
});
You can then reference to windowWidth from the html
<span ng-bind="windowWidth"></span>
Since you're accessing a web.config
you should probably use
using System.Web.Configuration;
WebConfigurationManager.AppSettings["configFile"]
flexbox
approach:The easiest way how to center a single element vertically and horizontally is to make it a flex item and set its margin to auto
:
If you apply auto margins to a flex item, that item will automatically extend its specified margin to occupy the extra space in the flex container...
.flex-container {_x000D_
height: 150px;_x000D_
display: flex;_x000D_
}_x000D_
_x000D_
.flex-item {_x000D_
margin: auto;_x000D_
}
_x000D_
<div class="flex-container">_x000D_
<div class="flex-item">_x000D_
This should be centered!_x000D_
</div>_x000D_
</div>
_x000D_
This extension of margins in each direction will push the element exactly to the middle of its container.
Among all the valid points made on both sides I haven't found my main reason to avoid the wildcard: I like to be able to read the code and know directly what every class is, or if it's definition isn't in the language or the file, where to find it. If more than one package is imported with * I have to go search every one of them to find a class I don't recognize. Readability is supreme, and I agree code should not require an IDE for reading it.
The tag in web.config is based on paths, whereas MVC works with controller actions and routes.
It is an architectural decision that might not make a lot of difference if you just want to prevent users that aren't logged in but makes a lot of difference when you try to apply authorization based in Roles and in cases that you want custom handling of types of Unauthorized.
The first case is covered from the answer of BobRock.
The user should have at least one of the following Roles to access the Controller or the Action
[Authorize(Roles = "Admin, Super User")]
The user should have both these roles in order to be able to access the Controller or Action
[Authorize(Roles = "Super User")]
[Authorize(Roles = "Admin")]
The users that can access the Controller or the Action are Betty and Johnny
[Authorize(Users = "Betty, Johnny")]
In ASP.NET Core you can use Claims and Policy principles for authorization through [Authorize]
.
options.AddPolicy("ElevatedRights", policy =>
policy.RequireRole("Administrator", "PowerUser", "BackupAdministrator"));
[Authorize(Policy = "ElevatedRights")]
The second comes very handy in bigger applications where Authorization might need to be implemented with different restrictions, process and handling according to the case. For this reason we can Extend the AuthorizeAttribute and implement different authorization alternatives for our project.
public class CustomAuthorizeAttribute: AuthorizeAttribute
{
public override void OnAuthorization(AuthorizationContext filterContext)
{ }
}
The "correct-completed" way to do authorization in ASP.NET MVC is using the [Authorize]
attribute.
using std::string;
string string_replace( string src, string const& target, string const& repl)
{
// handle error situations/trivial cases
if (target.length() == 0) {
// searching for a match to the empty string will result in
// an infinite loop
// it might make sense to throw an exception for this case
return src;
}
if (src.length() == 0) {
return src; // nothing to match against
}
size_t idx = 0;
for (;;) {
idx = src.find( target, idx);
if (idx == string::npos) break;
src.replace( idx, target.length(), repl);
idx += repl.length();
}
return src;
}
Since it's not a member of the string
class, it doesn't allow quite as nice a syntax as in your example, but the following will do the equivalent:
test = string_replace( string_replace( test, "abc", "hij"), "def", "klm")
I had a similar issue with Pandas, you need to use the iterrows() function to iterate through a Pandas dataset Pandas documentation for iterrows
data = pd.read_csv('foo.csv')
for index,item in data.iterrows():
print('{} {}'.format(item["gravatar_id"], item["position"]))
note that you need to handle the index in the dataset that is also returned by the function.
A simple and intuitive way would be to use shuf
.
Example:
Assume words.txt
as:
the
an
linux
ubuntu
life
good
breeze
To shuffle the lines, do:
$ shuf words.txt
which would throws the shuffled lines to standard output; So, you've to pipe it to an output file like:
$ shuf words.txt > shuffled_words.txt
One such shuffle run could yield:
breeze
the
linux
an
ubuntu
good
life
If you run a batch file calling PowerShell as a administrator, you better run it like this, saving you all the trouble:
powershell.exe -ExecutionPolicy Bypass -Command "Path\xxx.ps1"
It is better to use Bypass
...
Similarly to other languages, the fastest "modulo 2" (odd/even) operation is done using the bitwise and
operator:
if x & 1:
return 'odd'
else:
return 'even'
&
(bitwise AND) of the Number by 1 will be 1, because the last bit would already be set. Otherwise it will give 0 as output.Take a look at Pollard's rho algorithm. It's not quite the same problem, but maybe you'll understand the logic from it, and apply it for linked lists.
(if you're lazy, you can just check out cycle detection -- check the part about the tortoise and hare.)
This only requires linear time, and 2 extra pointers.
In Java:
boolean hasLoop( Node first ) {
if ( first == null ) return false;
Node turtle = first;
Node hare = first;
while ( hare.next != null && hare.next.next != null ) {
turtle = turtle.next;
hare = hare.next.next;
if ( turtle == hare ) return true;
}
return false;
}
(Most of the solution do not check for both next
and next.next
for nulls. Also, since the turtle is always behind, you don't have to check it for null -- the hare did that already.)
You can create an html page with a form, having method="post" and action="yourdesiredurl" and open it with your browser.
As an alternative, there are some browser plugins for developers that allow you to do that, like Web Developer Toolbar for Firefox
You need to do something like this:
// instantiate XmlDocument and load XML from file
XmlDocument doc = new XmlDocument();
doc.Load(@"D:\test.xml");
// get a list of nodes - in this case, I'm selecting all <AID> nodes under
// the <GroupAIDs> node - change to suit your needs
XmlNodeList aNodes = doc.SelectNodes("/Equipment/DataCollections/GroupAIDs/AID");
// loop through all AID nodes
foreach (XmlNode aNode in aNodes)
{
// grab the "id" attribute
XmlAttribute idAttribute = aNode.Attributes["id"];
// check if that attribute even exists...
if (idAttribute != null)
{
// if yes - read its current value
string currentValue = idAttribute.Value;
// here, you can now decide what to do - for demo purposes,
// I just set the ID value to a fixed value if it was empty before
if (string.IsNullOrEmpty(currentValue))
{
idAttribute.Value = "515";
}
}
}
// save the XmlDocument back to disk
doc.Save(@"D:\test2.xml");
Try this.
// Directory
$directory = "/dir";
// Returns array of files
$files = scandir($directory);
// Count number of files and store them to variable..
$num_files = count($files)-2;
Not counting the '.' and '..'.
This is actually tricky, especially if you plan on returning an image url for use cases where you need to concatenate strings with the onerror
condition image URL, e.g. you might want to programatically set the url
parameter in CSS.
The trick is that image loading is asynchronous by nature so the onerror
doesn't happen sunchronously, i.e. if you call returnPhotoURL
it immediately returns undefined
bcs the asynchronous method of loading/handling the image load just began.
So, you really need to wrap your script in a Promise then call it like below. NOTE: my sample script does some other things but shows the general concept:
returnPhotoURL().then(function(value){
doc.getElementById("account-section-image").style.backgroundImage = "url('" + value + "')";
});
function returnPhotoURL(){
return new Promise(function(resolve, reject){
var img = new Image();
//if the user does not have a photoURL let's try and get one from gravatar
if (!firebase.auth().currentUser.photoURL) {
//first we have to see if user han an email
if(firebase.auth().currentUser.email){
//set sign-in-button background image to gravatar url
img.addEventListener('load', function() {
resolve (getGravatar(firebase.auth().currentUser.email, 48));
}, false);
img.addEventListener('error', function() {
resolve ('//rack.pub/media/fallbackImage.png');
}, false);
img.src = getGravatar(firebase.auth().currentUser.email, 48);
} else {
resolve ('//rack.pub/media/fallbackImage.png');
}
} else {
img.addEventListener('load', function() {
resolve (firebase.auth().currentUser.photoURL);
}, false);
img.addEventListener('error', function() {
resolve ('https://rack.pub/media/fallbackImage.png');
}, false);
img.src = firebase.auth().currentUser.photoURL;
}
});
}
I believe you can use:
$('#yourLink').bind('click', function() {
//Do something over here
});
$('#yourLink').trigger('click');
This will easily trigger the click function, without actually clicking on it.
Isnull() syntax is built in for this kind of thing.
declare @Int int = null;
declare @Values table ( id int, def varchar(8) )
insert into @Values values (8, 'I am 8');
-- fails
select *
from @Values
where id = @Int
-- works fine
select *
from @Values
where id = isnull(@Int, 8);
For your example keep in mind you can change scope to be yet another where predicate off of a different variable for complex boolean logic. Only caveat is you need to cast it differently if you need to examine for a different data type. So if I add another row but wish to specify int of 8 AND also the reference of text similar to 'repeat' I can do that with a reference again back to the 'isnull' of the first variable yet return an entirely different result data type for a different reference to a different field.
declare @Int int = null;
declare @Values table ( id int, def varchar(16) )
insert into @Values values (8, 'I am 8'), (8, 'I am 8 repeat');
select *
from @Values
where id = isnull(@Int, 8)
and def like isnull(cast(@Int as varchar), '%repeat%')
You have to select and send the form data as well:
$("#post-btn").click(function(){
$.post("process.php", $("#reg-form").serialize(), function(data) {
alert(data);
});
});
Take a look at the documentation for the jQuery serialize
method, which encodes the data from the form fields into a data-string to be sent to the server.
for displaying variables only in playground, just mention the variable name without anything
let stat = 100
stat // this outputs the value of stat on playground right window
Agree with HTML5 LocaStorage. This is example code
Try this code. You can change the height and width percentages with app:layout_constraintHeight_percent and app:layout_constraintWidth_percent.
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="0dp"
android:layout_height="0dp"
android:background="#FF00FF"
android:orientation="vertical"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintHeight_percent=".6"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintWidth_percent=".4"></LinearLayout>
</android.support.constraint.ConstraintLayout>
Gradle:
dependencies {
...
implementation 'com.android.support.constraint:constraint-layout:1.1.3'
}
You can see some reports in SSMS:
Right-click the instance name / reports / standard / top sessions
You can see top CPU consuming sessions. This may shed some light on what SQL processes are using resources. There are a few other CPU related reports if you look around. I was going to point to some more DMVs but if you've looked into that already I'll skip it.
You can use sp_BlitzCache to find the top CPU consuming queries. You can also sort by IO and other things as well. This is using DMV info which accumulates between restarts.
This article looks promising.
Some stackoverflow goodness from Mr. Ozar.
edit: A little more advice... A query running for 'only' 5 seconds can be a problem. It could be using all your cores and really running 8 cores times 5 seconds - 40 seconds of 'virtual' time. I like to use some DMVs to see how many executions have happened for that code to see what that 5 seconds adds up to.
Use:
<?php
$image_src = wp_get_attachment_image_src(get_post_thumbnail_id($post->ID), 'thumbnail_size');
$feature_image_url = $image_src[0];
?>
You can change the thumbnail_size
value as per your required size.
/"(?:[^"\\]|\\.)*"/
Works in The Regex Coach and PCRE Workbench.
Example of test in JavaScript:
var s = ' function(){ return " Is big \\"problem\\", \\no? "; }';_x000D_
var m = s.match(/"(?:[^"\\]|\\.)*"/);_x000D_
if (m != null)_x000D_
alert(m);
_x000D_
I have created the following class and used across the application wherever required in place of GridView
:
/// <summary>
/// Represents a view mode that displays data items in columns for a System.Windows.Controls.ListView control with auto sized columns based on the column content
/// </summary>
public class AutoSizedGridView : GridView
{
protected override void PrepareItem(ListViewItem item)
{
foreach (GridViewColumn column in Columns)
{
// Setting NaN for the column width automatically determines the required
// width enough to hold the content completely.
// If the width is NaN, first set it to ActualWidth temporarily.
if (double.IsNaN(column.Width))
column.Width = column.ActualWidth;
// Finally, set the column with to NaN. This raises the property change
// event and re computes the width.
column.Width = double.NaN;
}
base.PrepareItem(item);
}
}
Simply If you getting this error on SQL server then run this query-
SET IDENTITY_INSERT tableName ON
This is working only for a single table of database
e.g If the table name is student
then query look like this:
SET IDENTITY_INSERT student ON
If you getting this error on your web application or you using entity framework then first run this query on SQL server and Update your entity model (
.edmx file
) and build your project and this error will be resolved
The php_flag and php_value inside a .htaccess file are technically correct - but for PHP installed as an Apache module only. On a shared host you'll almost never find such a setup; PHP is run as a CGI instead, for reasons related to security (keeping your server neighbours out of your files) and the way phpsuexec runs scripts as 'you' instead of the apache user.
Apache is thus correct giving you a server error: it doesn't know about the meaning of php_flag unless the PHP module is loaded. A CGI binary is to Apache an external program instead, and you can't configure it from within Apache.
Now for the good news: you can set up per-directory configuration putting there a file named 'php.ini' and setting there your instructions using the same syntax as in the system's main php.ini. The PHP manual lists all settable directives: you can set those marked with PHP_INI_PERDIR or PHP_INI_ALL, while only the system administrator can set those marked PHP_INI_SYSTEM in the server-wide php.ini.
Note that such php.ini directives are not inherited by subdirectories, you'll have to give them their own php.ini.
1 char s[100];
2 s = "hello";
In the example you provided, s is actually initialized at line 1, not line 2. Even though you didn't assign it a value explicitly at this point, the compiler did.
At line 2, you're performing an assignment operation, and you cannot assign one array of characters to another array of characters like this. You'll have to use strcpy()
or some kind of loop to assign each element of the array.
here is how you can perform simply, make a drawable resource file in drawable.xml. Say round_button.xml and then paste the following code.
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item>
<shape
android:shape="oval">
<solid
android:color="@color/button_start_gradient_color"/>
</shape>
</item>
<item
android:drawable="@drawable/microphone"/>
</layer-list>
Note:- use your own color and drawable resource as i have used @drawable/microphone
Following is the result [1]: https://i.stack.imgur.com/QyhdJ.png
I see this being possible using either some regex, or a few substr calls (assuming the input is always of that format, and doesn't change length etc.)
something like
$in = "+11234567890"; $output = substr($in,2,3)."-".substr($in,6,3)."-".substr($in,10,4);
should do it.
You have a misplaced closing brace before the return
statement.
The above query returns the list of Object[]. So if you want to get the u.name and s.something from the list then you need to iterate and cast that values for the corresponding classes.
I am using Intellij Idea 2017 and I got into the same problem. What solved the problem for me was to simply
df.loc will do the job :
>>> df = pd.DataFrame(np.random.randn(3, 2), columns=['A','B'])
>>> df
A B
0 -0.269036 0.534991
1 0.069915 -1.173594
2 -1.177792 0.018381
>>> df.loc[13] = df.loc[1]
>>> df
A B
0 -0.269036 0.534991
1 0.069915 -1.173594
2 -1.177792 0.018381
13 0.069915 -1.173594
Truth be told there are many, many resources explaining how to do this already out on the web:
Git: how to reverse-merge a commit?
Git: how to reverse-merge a commit?
Undoing Merges, from Git's blog (retrieved from archive.org's Wayback Machine)
So I guess I'll just summarize some of these:
git revert <merge commit hash>
This creates an extra "revert" commit saying you undid a merge
git reset --hard <commit hash *before* the merge>
This reset history to before you did the merge. If you have commits after the merge you will need to cherry-pick
them on to afterwards.
But honestly this guide here is better than anything I can explain, with diagrams! :)
When calling the function, follow it by return false
example:
<input type="submit" value="Add" onclick="addNewPayment();return false;">
Important - Answer work only for REACT-NATIVE VS CODE Terminal
In VisualStudio code, you have to run like below then that warning will be omitted.
react-native run-android warning-mode=all
If you run below then you will get the error in terminal When running react-native run-android --warning-mode all I get error: unknown option --warning-mode'
I have started writing one tutorial for everyone on this topic, see making gadgets for Windows 7.
Technically, Node.js isn't proper JavaScript as we know it, since there isn't a Document Object Model (DOM). For instance, JavaScript scripts that run in the browser will not work. At all. The solution would be to run JavaScript with a headless browser. Fortunately there is a project still active: Mozilla Firefox has a headless mode.
https://developer.mozilla.org/en-US/docs/Mozilla/Firefox/Headless_mode
$ /Applications/Firefox.app/Contents/MacOS/firefox -headless index.html
*** You are running in headless mode.
Each directive's compile
function is only called once, when Angular bootstraps.
Officially, this is the place to perform (source) template manipulations that do not involve scope or data binding.
Primarily, this is done for optimisation purposes; consider the following markup:
<tr ng-repeat="raw in raws">
<my-raw></my-raw>
</tr>
The <my-raw>
directive will render a particular set of DOM markup. So we can either:
ng-repeat
to duplicate the source template (<my-raw>
), and then modify the markup of each instance template (outside the compile
function).compile
function), and then allow ng-repeat
to duplicate it.If there are 1000 items in the raws
collection, the latter option may be faster than the former one.
The pop
method of dicts (like self.data
, i.e. {'a':'aaa','b':'bbb','c':'ccc'}
, here) takes two arguments -- see the docs
The second argument, default
, is what pop
returns if the first argument, key
, is absent.
(If you call pop
with just one argument, key
, it raises an exception if that key's absent).
In your example, print b.pop('a',{'b':'bbb'})
, this is irrelevant because 'a'
is a key in b.data
. But if you repeat that line...:
b=a()
print b.pop('a',{'b':'bbb'})
print b.pop('a',{'b':'bbb'})
print b.data
you'll see it makes a difference: the first pop
removes the 'a'
key, so in the second pop
the default
argument is actually returned (since 'a'
is now absent from b.data
).
$ du -h -d=1 ~/Library/Developer/Xcode/*
shows at least two folders are huge:
1.5G /Users/horace/Library/Developer/Xcode/DerivedData
9.4G /Users/horace/Library/Developer/Xcode/iOS DeviceSupport
Feel free to remove stuff in the folders:
rm -rf ~/Library/Developer/Xcode/DerivedData/*
and some in:
open ~/Library/Developer/Xcode/iOS\ DeviceSupport/
I had this exact problem today and the problem was that the version I was trying to release:perform was already in the Nexus repo.
In my case this was likely due to a network disconnect during an earlier invocation of release:perform. Even though I lost my connection, it appears the release succeeded.
**old_list = [[0,1,'f'], [4,2,'t'],[9,4,'afsd']]
#let's assume we want to sort lists by last value ( old_list[2] )
new_list = sorted(old_list, key=lambda x: x[2])**
correct me if i'm wrong but isnt the 'x[2]' calling the 3rd item in the list, not the 3rd item in the nested list? should it be x[2][2]?
You need to apply following changes:
Update php.ini
(Find right ini file from phpinfo();
) and increase post_max_size
and upload_max_filesize
to size you want:
sed -i "s/post_max_size =.*/post_max_size = 200M/g" /etc/php5/fpm/php.ini
sed -i "s/upload_max_filesize =.*/upload_max_filesize = 200M/g" /etc/php5/fpm/php.ini```
Update NginX settings for your website and add client_max_body_size
value in your location
, http
, or server
context.
location / {
client_max_body_size 200m;
...
}
Restart NginX and PHP-FPM:
service nginx restart
service php5-fpm restart
NOTE: Sometime (In my case almost every time) you need to kill php-fpm
process if it didn't refresh by service command properly. To do that you can get list of processes (ps -elf | grep php-fpm
) and kill one by one (kill -9 12345
) or use following command to do it for you:
ps -elf | grep php-fpm | grep -v grep | awk '{ print $4 }' | xargs kill -9
This was happening for me when I was trying to call a function using parens, e.g.
run() {
echo hello
}
run()
should be:
run() {
echo hello
}
run
android:maxLength="10"
Vibrating in Patterns/Waves:
import android.os.Vibrator;
...
// Vibrate for 500ms, pause for 500ms, then start again
private static final long[] VIBRATE_PATTERN = { 500, 500 };
mVibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
// API 26 and above
mVibrator.vibrate(VibrationEffect.createWaveform(VIBRATE_PATTERN, 0));
} else {
// Below API 26
mVibrator.vibrate(VIBRATE_PATTERN, 0);
}
Plus
The necessary permission in AndroidManifest.xml
:
<uses-permission android:name="android.permission.VIBRATE"/>
MD5 is a bit old, SHA-1 is a better algorithm, there is a example here.
(Also as they note in that post, Java handles this on it's own, no Android specific code.)
Your angular module needs to be initialized properly. The global object app
needs to be defined and initialized correctly to inject the service.
Please see below sample code for reference:
app.js
var app = angular.module('SampleApp',['ngRoute']); //You can inject the dependencies within the square bracket
app.config(['$routeProvider', '$locationProvider', function($routeProvider, $locationProvider) {
$routeProvider
.when('/', {
templateUrl:"partials/login.html",
controller:"login"
});
$locationProvider
.html5Mode(true);
}]);
app.factory('getSettings', ['$http', '$q', function($http, $q) {
return {
//Code edited to create a function as when you require service it returns object by default so you can't return function directly. That's what understand...
getSetting: function (type) {
var q = $q.defer();
$http.get('models/settings.json').success(function (data) {
q.resolve(function() {
var settings = jQuery.parseJSON(data);
return settings[type];
});
});
return q.promise;
}
}
}]);
app.controller("globalControl", ['$scope','getSettings', function ($scope,getSettings) {
//Modified the function call for updated service
var loadSettings = getSettings.getSetting('global');
loadSettings.then(function(val) {
$scope.settings = val;
});
}]);
Sample HTML code should be like this:
<!DOCTYPE html>
<html>
<head lang="en">
<title>Sample Application</title>
</head>
<body ng-app="SampleApp" ng-controller="globalControl">
<div>
Your UI elements go here
</div>
<script src="app.js"></script>
</body>
</html>
Please note that the controller is not binding to an HTML tag but to the body tag. Also, please try to include your custom scripts at end of the HTML page as this is a standard practice to follow for performance reasons.
I hope this will solve your basic injection issue.
To untrack a single file that has already been added/initialized to your repository, i.e., stop tracking the file but not delete it from your system use: git rm --cached filename
To untrack every file that is now in your .gitignore
:
First commit any outstanding code changes, and then, run this command:
git rm -r --cached .
This removes any changed files from the index(staging area), then just run:
git add .
Commit it:
git commit -m ".gitignore is now working"
On Windows
, you can run the systeminfo
command and retrieves its output for instance with the following code:
private static class WindowsSystemInformation
{
static String get() throws IOException
{
Runtime runtime = Runtime.getRuntime();
Process process = runtime.exec("systeminfo");
BufferedReader systemInformationReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
StringBuilder stringBuilder = new StringBuilder();
String line;
while ((line = systemInformationReader.readLine()) != null)
{
stringBuilder.append(line);
stringBuilder.append(System.lineSeparator());
}
return stringBuilder.toString().trim();
}
}
Here is a sample shell script (make sure you replace the MATH name with the name of the your application):
#!/bin/bash
### BEGIN INIT INFO
# Provides: MATH
# Required-Start: $java
# Required-Stop: $java
# Short-Description: Start and stop MATH service.
# Description: -
# Date-Creation: -
# Date-Last-Modification: -
# Author: -
### END INIT INFO
# Variables
PGREP=/usr/bin/pgrep
JAVA=/usr/bin/java
ZERO=0
# Start the MATH
start() {
echo "Starting MATH..."
#Verify if the service is running
$PGREP -f MATH > /dev/null
VERIFIER=$?
if [ $ZERO = $VERIFIER ]
then
echo "The service is already running"
else
#Run the jar file MATH service
$JAVA -jar /opt/MATH/MATH.jar > /dev/null 2>&1 &
#sleep time before the service verification
sleep 10
#Verify if the service is running
$PGREP -f MATH > /dev/null
VERIFIER=$?
if [ $ZERO = $VERIFIER ]
then
echo "Service was successfully started"
else
echo "Failed to start service"
fi
fi
echo
}
# Stop the MATH
stop() {
echo "Stopping MATH..."
#Verify if the service is running
$PGREP -f MATH > /dev/null
VERIFIER=$?
if [ $ZERO = $VERIFIER ]
then
#Kill the pid of java with the service name
kill -9 $($PGREP -f MATH)
#Sleep time before the service verification
sleep 10
#Verify if the service is running
$PGREP -f MATH > /dev/null
VERIFIER=$?
if [ $ZERO = $VERIFIER ]
then
echo "Failed to stop service"
else
echo "Service was successfully stopped"
fi
else
echo "The service is already stopped"
fi
echo
}
# Verify the status of MATH
status() {
echo "Checking status of MATH..."
#Verify if the service is running
$PGREP -f MATH > /dev/null
VERIFIER=$?
if [ $ZERO = $VERIFIER ]
then
echo "Service is running"
else
echo "Service is stopped"
fi
echo
}
# Main logic
case "$1" in
start)
start
;;
stop)
stop
;;
status)
status
;;
restart|reload)
stop
start
;;
*)
echo $"Usage: $0 {start|stop|status|restart|reload}"
exit 1
esac
exit 0
I had mysterious SIGTERM shutdowns in our L.A.M.P. server, and it turned out to be an error in a custom PHP module, which was caused by mismatched versions. It was found by looking in the apache access/error logs at the time of malfunction. Don't forget to turn error logging on.
foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces())
{
if (nic.OperationalStatus == OperationalStatus.Up)
{
PhysicalAddress Mac = nic.GetPhysicalAddress();
}
}
As @Travis Solution works but in some cases
var millisecondsSince1970:Int
WILL CAUSE CRASH APPLICATION ,
with error
Double value cannot be converted to Int because the result would be greater than Int.max if it occurs Please update your answer with Int64
Here is Updated Answer
extension Date {
var millisecondsSince1970:Int64 {
return Int64((self.timeIntervalSince1970 * 1000.0).rounded())
//RESOLVED CRASH HERE
}
init(milliseconds:Int) {
self = Date(timeIntervalSince1970: TimeInterval(milliseconds / 1000))
}
}
On 32-bit platforms, Int is the same size as Int32, and on 64-bit platforms, Int is the same size as Int64.
Generally, I encounter this problem in iPhone 5
, which runs in 32-bit env. New devices run 64-bit env now. Their Int
will be Int64
.
Hope it is helpful to someone who also has same problem
Modulus operator gives the remainder. Modulus operator in c usually takes the sign of the numerator
Also modulus(remainder) operator can only be used with integer type and cannot be used with floating point.
To get size of viewport on load and on resize (based on SimaWB response):
function getViewport() {
var viewportWidth = $(window).width();
var viewportHeight = $(window).height();
$('#viewport').html('Viewport: '+viewportWidth+' x '+viewportHeight+' px');
}
getViewport();
$(window).resize(function() {
getViewport()
});
If you want to apply some condition on form submit then you can use this method
<form onsubmit="return checkEmpData();" method="post" action="process.html">
<input type="text" border="0" name="submit" />
<button value="submit">submit</button>
</form>
One thing always keep in mind that method and action attribute write after onsubmit attributes
javascript code
function checkEmpData()
{
var a = 0;
if(a != 0)
{
return confirm("Do you want to generate attendance?");
}
else
{
alert('Please Select Employee First');
return false;
}
}
Just append a div
with that class to body
, then remove it when you're done:
// Show the backdrop
$('<div class="modal-backdrop"></div>').appendTo(document.body);
// Remove it (later)
$(".modal-backdrop").remove();
Live Example:
$("input").click(function() {_x000D_
var bd = $('<div class="modal-backdrop"></div>');_x000D_
bd.appendTo(document.body);_x000D_
setTimeout(function() {_x000D_
bd.remove();_x000D_
}, 2000);_x000D_
});
_x000D_
<link href="//netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/css/bootstrap-combined.min.css" rel="stylesheet" type="text/css" />_x000D_
<script src="//code.jquery.com/jquery.min.js"></script>_x000D_
<script src="//netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/js/bootstrap.min.js"></script>_x000D_
<p>Click the button to get the backdrop for two seconds.</p>_x000D_
<input type="button" value="Click Me">
_x000D_
I just figured. You need to add a shared folder using VirtualBox before you access it with the guest.
Click "Device" in the menu bar--->Shared File--->add a directory and name it
then in the guest terminal, use:
sudo mount -t vboxsf myFileName ~/destination
Dont directly refer to the host directory
By regex i think this is java, the method replaceAll()
returns a new String with the substrings replaced, so try this:
String teste = "abcd=0; efgh=1";
String teste2 = teste.replaceAll("abcd", "dddd");
System.out.println(teste2);
Output:
dddd=0; efgh=1
Try this one for current selection:
Sub A_SelectAllMakeTable2()
Dim tbl As ListObject
Set tbl = ActiveSheet.ListObjects.Add(xlSrcRange, Selection, , xlYes)
tbl.TableStyle = "TableStyleMedium15"
End Sub
or equivalent of your macro (for Ctrl+Shift+End range selection):
Sub A_SelectAllMakeTable()
Dim tbl As ListObject
Dim rng As Range
Set rng = Range(Range("A1"), Range("A1").SpecialCells(xlLastCell))
Set tbl = ActiveSheet.ListObjects.Add(xlSrcRange, rng, , xlYes)
tbl.TableStyle = "TableStyleMedium15"
End Sub
If you want first 2 letters and last 2 letters of a string then you can use the following code:
name = "India"
name[0:2]="In"
names[-2:]="ia"
NumberFormatException invoke when you ll try to convert inavlid String for eg:"abc"
value to integer..
this is valid string is eg"123"
. in your case split by space..
split(" ");
will split line by " "
by space..
If your application is in foreground state, it means you are currently using the same app. So there is no need to show notification on the top generally.
But still if you want to show notification in that case you have to create your custom Alert View or Custom View like Toast or something else to show to the user that you have got a notification.
You can also show a badge on the top if you have such kind of feature in your app.
It's also possible that you have accidentally put the IDE into Full Screen Mode
. On occasion, you may be inadertently pressing F11 to set FullScreen mode to On.
If this is the case, the Accepted Answer above will not work. Instead, you must disable Full Screen mode (View > Appearance > Full Screen).
Please see the attached screenshot.
You can access the iterator methods directly:
std::vector<int> *intVec;
std::vector<int>::iterator it;
for( it = intVec->begin(); it != intVec->end(); ++it )
{
}
If you want the array-access operator, you'd have to de-reference the pointer. For example:
std::vector<int> *intVec;
int val = (*intVec)[0];
you are almost there; you just need to give the reference to master; since you want to get the file from the master branch:
git checkout master -- filename
Note that the differences will be cached; so if you want to see the differences you obtained; use
git diff --cached
Steve's solution does not work. When calling this.Close(), current form is disposed together with form2. Therefore you need to hide it and set form2.Closed event to call this.Close().
private void OnButton1Click(object sender, EventArgs e)
{
this.Hide();
var form2 = new Form2();
form2.Closed += (s, args) => this.Close();
form2.Show();
}
An alternative way would be to create a new temporary table with same structure.
CREATE TABLE temp_table AS SELECT * FROM original_table LIMIT 0
Then create the primary key in the table.
ALTER TABLE temp_table ADD PRIMARY KEY (primary-key-field)
Finally copy all records from the original table while ignoring the duplicate records.
INSERT IGNORE INTO temp_table AS SELECT * FROM original_table
Now you can delete the original table and rename the new table.
DROP TABLE original_table
RENAME TABLE temp_table TO original_table
<div id="map" style="width:100%;height:500px"></div>
<script>
function myMap() {
var myCenter = new google.maps.LatLng(51.508742,-0.120850);
var mapCanvas = document.getElementById("map");
var mapOptions = {center: myCenter, zoom: 5};
var map = new google.maps.Map(mapCanvas, mapOptions);
var marker = new google.maps.Marker({position:myCenter});
marker.setMap(map);
}
</script>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyBu-916DdpKAjTmJNIgngS6HL_kDIKU0aU&callback=myMap"></script>
I had this issue start happening when debugging from one web project to a web service in the same solution. The web service was returning responses that the web project couldnt understand. It would kind of work again at some points, then stop again.
It was because there was not an explicit reference between these projects, so the web service was not getting built when hitting F5 to start debugging. Once I added that, the errors went away.
Regular expression for the IP address format:
/^(\d\d?)|(1\d\d)|(0\d\d)|(2[0-4]\d)|(2[0-5])\.(\d\d?)|(1\d\d)|(0\d\d)|(2[0-4]\d)|(2[0-5])\.(\d\d?)|(1\d\d)|(0\d\d)|(2[0-4]\d)|(2[0-5])$/;
If you are testing a logic class and it is calling some internal void methods the doNothing is perfect.
image
has a shape of (64,64,3)
.
Your input placeholder _x
have a shape of (?, 64,64,3)
.
The problem is that you're feeding the placeholder with a value of a different shape.
You have to feed it with a value of (1, 64, 64, 3)
= a batch of 1 image.
Just reshape your image
value to a batch with size one.
image = array(img).reshape(1, 64,64,3)
P.S: the fact that the input placeholder accepts a batch of images, means that you can run predicions for a batch of images in parallel.
You can try to read more than 1 image (N images) and than build a batch of N image, using a tensor with shape (N, 64,64,3)
-> it works like pointer u don't have to use *
for( list<student>::iterator iter= data.begin(); iter != data.end(); iter++ )
cout<<iter->name; //'iter' not 'it'
Using aggregate
:
aggregate(x$Frequency, by=list(Category=x$Category), FUN=sum)
Category x
1 First 30
2 Second 5
3 Third 34
In the example above, multiple dimensions can be specified in the list
. Multiple aggregated metrics of the same data type can be incorporated via cbind
:
aggregate(cbind(x$Frequency, x$Metric2, x$Metric3) ...
(embedding @thelatemail comment), aggregate
has a formula interface too
aggregate(Frequency ~ Category, x, sum)
Or if you want to aggregate multiple columns, you could use the .
notation (works for one column too)
aggregate(. ~ Category, x, sum)
or tapply
:
tapply(x$Frequency, x$Category, FUN=sum)
First Second Third
30 5 34
Using this data:
x <- data.frame(Category=factor(c("First", "First", "First", "Second",
"Third", "Third", "Second")),
Frequency=c(10,15,5,2,14,20,3))
The following example builds on MARTIN DE LA FUENTE SAAVEDRA's excellent work and accepted answer. In particular, two enumerations are introduced. The first allows for easy specification of how an elevated program is to be opened, and the second helps when errors need to be easily identified. Please note that if you want all command line arguments passed to the new process, sys.argv[0]
should probably be replaced with a function call: subprocess.list2cmdline(sys.argv)
.
#! /usr/bin/env python3
import ctypes
import enum
import subprocess
import sys
# Reference:
# msdn.microsoft.com/en-us/library/windows/desktop/bb762153(v=vs.85).aspx
# noinspection SpellCheckingInspection
class SW(enum.IntEnum):
HIDE = 0
MAXIMIZE = 3
MINIMIZE = 6
RESTORE = 9
SHOW = 5
SHOWDEFAULT = 10
SHOWMAXIMIZED = 3
SHOWMINIMIZED = 2
SHOWMINNOACTIVE = 7
SHOWNA = 8
SHOWNOACTIVATE = 4
SHOWNORMAL = 1
class ERROR(enum.IntEnum):
ZERO = 0
FILE_NOT_FOUND = 2
PATH_NOT_FOUND = 3
BAD_FORMAT = 11
ACCESS_DENIED = 5
ASSOC_INCOMPLETE = 27
DDE_BUSY = 30
DDE_FAIL = 29
DDE_TIMEOUT = 28
DLL_NOT_FOUND = 32
NO_ASSOC = 31
OOM = 8
SHARE = 26
def bootstrap():
if ctypes.windll.shell32.IsUserAnAdmin():
main()
else:
# noinspection SpellCheckingInspection
hinstance = ctypes.windll.shell32.ShellExecuteW(
None,
'runas',
sys.executable,
subprocess.list2cmdline(sys.argv),
None,
SW.SHOWNORMAL
)
if hinstance <= 32:
raise RuntimeError(ERROR(hinstance))
def main():
# Your Code Here
print(input('Echo: '))
if __name__ == '__main__':
bootstrap()
I have tried many solutions. If it works in modern browsers, it won't in Internet Explorer. If it works in Internet Explorer, it won't on iOS. I finally groomed them all and arrived at the below fix that works in all the browsers, iOS, webview, and Android.
Note: I also covered the scenario where the user denies permission to the clipboard. Additionally, the message "link copied" will be displayed even if the user copies manually.
<div class="form-group col-md-12">
<div class="input-group col-md-9">
<input name="copyurl"
type="text"
class="form-control br-0 no-focus"
id="invite-url"
placeholder="http://www.invitelink.com/example"
readonly>
<span class="input-group-addon" id="copy-link" title="Click here to copy the invite link">
<i class="fa fa-clone txt-18 text-success" aria-hidden="true"></i>
</span>
</div>
<span class="text-success copy-success hidden">Link copied.</span>
</div>
Script:
var addEvent = window.attachEvent || window.addEventListener;
var event = 'copy';
var $inviteUrl = $('#invite-url');
$('#copy-link').on('click', function(e) {
if ($inviteUrl.val()) {
if (navigator.userAgent.match(/ipad|ipod|iphone/i)) {
var el = $inviteUrl.get(0);
var editable = el.contentEditable;
var readOnly = el.readOnly;
el.contentEditable = true;
el.readOnly = false;
var range = document.createRange();
range.selectNodeContents(el);
var sel = window.getSelection();
sel.removeAllRanges();
sel.addRange(range);
el.setSelectionRange(0, 999999);
el.contentEditable = editable;
el.readOnly = readOnly;
document.execCommand('copy');
$inviteUrl.blur();
}
else {
$inviteUrl.select();
document.execCommand("copy");
}
}
});
addEvent(event, function(event) {
if ($inviteUrl.val() && event.target.id == 'invite-url') {
var $copyLink = $('#copy-link i');
$copyLink.removeClass('fa-clone');
$copyLink.addClass('fa-check');
$('.copy-success').removeClass('hidden');
setTimeout(function() {
$copyLink.removeClass('fa-check');
$copyLink.addClass('fa-clone');
$('.copy-success').addClass('hidden');
}, 2000);
}
});
mikej's answer was very precise and helpful, but the the thing i also wanted to know was how to get current method name in rails.
found out it's possible with self.current_method
easily found at http://www.ruby-forum.com/topic/75258
You can find all the HTML Special Characters in this page http://www.degraeve.com/reference/specialcharacters.php Just replace the code where you want to put that character. :-)
If you have GNU find you can also say
find . -newermt '1 minute ago'
The t
options makes the reference "file" for newer
become a reference date string of the sort that you could pass to GNU date -d
, which understands complex date specifications like the one given above.
For arrays you can use:
Array.FindIndex<T>
:
int keyIndex = Array.FindIndex(words, w => w.IsKey);
For lists you can use List<T>.FindIndex
:
int keyIndex = words.FindIndex(w => w.IsKey);
You can also write a generic extension method that works for any Enumerable<T>
:
///<summary>Finds the index of the first item matching an expression in an enumerable.</summary>
///<param name="items">The enumerable to search.</param>
///<param name="predicate">The expression to test the items against.</param>
///<returns>The index of the first matching item, or -1 if no items match.</returns>
public static int FindIndex<T>(this IEnumerable<T> items, Func<T, bool> predicate) {
if (items == null) throw new ArgumentNullException("items");
if (predicate == null) throw new ArgumentNullException("predicate");
int retVal = 0;
foreach (var item in items) {
if (predicate(item)) return retVal;
retVal++;
}
return -1;
}
And you can use LINQ as well:
int keyIndex = words
.Select((v, i) => new {Word = v, Index = i})
.FirstOrDefault(x => x.Word.IsKey)?.Index ?? -1;
This problem occurs because while creating the AVD manager in the "Create new Android virtual device(AVD)" dialog window ,"Snapshot" was marked as "Enabled" by me.
Create a new AVD manager with the "Enabled" checkbox not checked and then try running the project with the newly created AVD manager as "Target" , the problem will not occur anymore
For Linux Mint 18: edit ~/.bashrc and add this line to it at the bottom:
export PATH="$PATH:$HOME/.config/composer/vendor/bin"
then resource .bashrc (type in console):
source ~/.bashrc (or close and reopen the terminal)
test it by typing in the console:
echo $PATH
or type in console:
laravel
Something that just happened to me and caused me some headaches:
I have set up a new Linux RabbitMQ server and used a shell script to set up my own custom users (not guest!).
The script had several of those "code" blocks:
rabbitmqctl add_user test test
rabbitmqctl set_user_tags test administrator
rabbitmqctl set_permissions -p / test ".*" ".*" ".*"
Very similar to the one in Gabriele's answer, so I take his code and don't need to redact passwords.
Still I was not able to log in in the management console. Then I noticed that I had created the setup script in Windows (CR+LF line ending) and converted the file to Linux (LF only), then reran the setup script on my Linux server.
... and was still not able to log in, because it took another 15 minutes until I realized that calling add_user over and over again would not fix the broken passwords (which probably ended with a CR character). I had to call change_password for every user to fix my earlier mistake:
rabbitmqctl change_password test test
(Another solution would have been to delete all users and then call the script again)
Set these style code in style
<style name="Theme.Transparent" parent="android:Theme">
<item name="android:windowIsTranslucent">true</item>
<item name="android:windowBackground">@android:color/transparent</item>
<item name="android:windowContentOverlay">@null</item>
<item name="android:windowNoTitle">true</item>
<item name="android:windowIsFloating">true</item>
<item name="android:backgroundDimEnabled">false</item>
</style>
And simply change false to true below line
<item name="android:backgroundDimEnabled">true</item>
It will dim your background.
I got the resources on C# (Desktop WPF W/ .NET Framework 4.8) using the code below
{DefaultNamespace}.Properties.Resources.{ResourceName}
Why do you really need your own code to download it? How about just passing your URI to Download manager?
public void downloadFile(String uRl) {
File direct = new File(Environment.getExternalStorageDirectory()
+ "/AnhsirkDasarp");
if (!direct.exists()) {
direct.mkdirs();
}
DownloadManager mgr = (DownloadManager) getActivity().getSystemService(Context.DOWNLOAD_SERVICE);
Uri downloadUri = Uri.parse(uRl);
DownloadManager.Request request = new DownloadManager.Request(
downloadUri);
request.setAllowedNetworkTypes(
DownloadManager.Request.NETWORK_WIFI
| DownloadManager.Request.NETWORK_MOBILE)
.setAllowedOverRoaming(false).setTitle("Demo")
.setDescription("Something useful. No, really.")
.setDestinationInExternalPublicDir("/AnhsirkDasarp", "fileName.jpg");
mgr.enqueue(request);
}
Since you declare sample
inside the anonymous function you pass to ready
, it is scoped to that function.
You then pass a string to setTimeout
which is eval
ed after 2 seconds. This takes place outside the current scope, so it can't find the function.
Only pass functions to setTimeout
, using eval is inefficient and hard to debug.
setTimeout(sample,2000)
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);
I'd usually do:
use sourcedatabase;
var docs=db.sourcetable.find();
use targetdatabase;
docs.forEach(function(doc) { db.targettable.insert(doc); });
I change css style in Javascript function.
But Uncaught TypeError: bild is null .
If I run it in a normal html file it work.
CODE:
var text = document.getElementById("text");
var bild = document.getElementById("bild");
var container = document.getElementById("container");
bild.style["background-image"] = "url('stock-bild-portrait-of-confident-senior-business-woman-standing-in-office-with-her-arms-crossed-mature-female-1156978234.jpg')";
//bild.style.background-image = "url('stock-bild-portrait-of-confident-senior-business-woman-standing-in-office-with-her-arms-crossed-mature-female-1156978234.jpg')";
// bild.style["background-image"] = "url('" + defaultpic + "')";
alert (bild.style["background-image"]) ;
bild.style["background-size"] = "300px";
bild.style["background-repeat"] = "no-repeat";
bild.style["background-position"] = "center";
bild.style["border-radius"] = "50%";
bild.style["background-clip"] = "border-box";
bild.style["transition"] = "background-size 0.2s";
bild.style["transition-timing-function"] = "cubic-bezier(.07,1.41,.82,1.41)";
bild.style["display"] = "block";
bild.style["width"] = "100px";
bild.style["height"] = "100px";
bild.style["text-decoration"] = "none";
bild.style["cursor"] = "pointer";
bild.style["overflow"] = "hidden";
bild.style["text-indent"] = "100%";
bild.style["white-space"] = "nowrap";
container.style["position"] = "relative";
container.style["font-family"] = "Arial";
text.style["position"] = "center";
text.style["bottom"] = "5px";
text.style["left"] = "1px";
text.style["color"] = "white";
You should use this:
>mysql -u user -h 192.168.1.2 -P 3306 -ppassword
or this:
>mysql -u user -h 192.168.1.2 -ppassword
...because 3306 is a default port number.
Made an improvement code by @Ipsita - for use asynchronous read\write file I/O
readonly string logPath = @"FilePath";
...
public async Task WriteToLogAsync(string dataToWrite)
{
TextReader tr = new StreamReader(logPath);
string data = await tr.ReadLineAsync();
tr.Close();
TextWriter tw = new StreamWriter(logPath);
await tw.WriteLineAsync(data + dataToWrite);
tw.Close();
}
...
await WriteToLogAsync("Write this to file");
You can use the _contains function from the underscore.js library to achieve this:
if (_.contains(haystack, needle)) {
console.log("Needle found.");
};
To Hide the Action Bar add the below code in Values/Styles
<style name="CustomActivityThemeNoActionBar" parent="@android:style/Theme.Holo.Light">
<item name="android:windowActionBar">false</item>
<item name="android:windowNoTitle">true</item>
</style>
Then in your AndroidManifest.xml file add the below code in the required activity
<activity
android:name="com.newbelievers.android.NBMenu"
android:label="@string/title_activity_nbmenu"
android:theme="@style/CustomActivityThemeNoActionBar">
</activity>
This was asked on the www-style list, and Tab Atkins (spec editor) provided an answer explaining why. I'll elaborate on that a bit here.
To start out, let's initially assume our flex container is single-line (flex-wrap: nowrap
). In this case, there's clearly an alignment difference between the main axis and the cross axis -- there are multiple items stacked in the main axis, but only one item stacked in the cross axis. So it makes sense to have a customizeable-per-item "align-self" in the cross axis (since each item is aligned separately, on its own), whereas it doesn't make sense in the main axis (since there, the items are aligned collectively).
For multi-line flexbox, the same logic applies to each "flex line". In a given line, items are aligned individually in the cross axis (since there's only one item per line, in the cross axis), vs. collectively in the main axis.
Here's another way of phrasing it: so, all of the *-self
and *-content
properties are about how to distribute extra space around things. But the key difference is that the *-self
versions are for cases where there's only a single thing in that axis, and the *-content
versions are for when there are potentially many things in that axis. The one-thing vs. many-things scenarios are different types of problems, and so they have different types of options available -- for example, the space-around
/ space-between
values make sense for *-content
, but not for *-self
.
SO: In a flexbox's main axis, there are many things to distribute space around. So a *-content
property makes sense there, but not a *-self
property.
In contrast, in the cross axis, we have both a *-self
and a *-content
property. One determines how we'll distribute space around the many flex lines (align-content
), whereas the other (align-self
) determines how to distribute space around individual flex items in the cross axis, within a given flex line.
(I'm ignoring *-items
properties here, since they simply establish defaults for *-self
.)
#if defined(CONDITION1) || defined(CONDITION2)
should work. :)
#ifdef
is a bit less typing, but doesn't work well with more complex conditions
Yeah, it is quite vague.
You should use it whenever for readers of the documentation of your method it may be useful to also look at some other method. If the documentation of your methodA says "Works like methodB but ...", then you surely should put a link.
An alternative to @see
would be the inline {@link ...}
tag:
/**
* ...
* Works like {@link #methodB}, but ...
*/
When the fact that methodA calls methodB is an implementation detail and there is no real relation from the outside, you don't need a link here.
We have an extension method to do exactly this in MoreLINQ. You can look at the implementation there, but basically it's a case of iterating through the data, remembering the maximum element we've seen so far and the maximum value it produced under the projection.
In your case you'd do something like:
var item = items.MaxBy(x => x.Height);
This is better (IMO) than any of the solutions presented here other than Mehrdad's second solution (which is basically the same as MaxBy
):
Max
value and then finding the first element with that value is O(n), but iterates over the sequence twice. Where possible, you should use LINQ in a single-pass fashion.This can be done in a single line without the use of library. Please check java.text.MessageFormat
class.
Example
String stringWithPlaceHolder = "test String with placeholders {0} {1} {2} {3}";
String formattedStrin = java.text.MessageFormat.format(stringWithPlaceHolder, "place-holder-1", "place-holder-2", "place-holder-3", "place-holder-4");
Output will be
test String with placeholders place-holder-1 place-holder-2 place-holder-3 place-holder-4
As another poster said, it's typically preferable to have interfaces define capabilities not types. I would tend not to "implement" something like a "User," and this is why "IUser" often isn't really necessary in the way described here. I often see classes as nouns and interfaces as adjectives:
class Number implements Comparable{...}
class MyThread implements Runnable{...}
class SessionData implements Serializable{....}
Sometimes an Adjective doesn't make sense, but I'd still generally be using interfaces to model behavior, actions, capabilities, properties, etc,... not types.
Also, If you were really only going to make one User and call it User then what's the point of also having an IUser interface? And if you are going to have a few different types of users that need to implement a common interface, what does appending an "I" to the interface save you in choosing names of the implementations?
I think a more realistic example would be that some types of users need to be able to login to a particular API. We could define a Login interface, and then have a "User" parent class with SuperUser, DefaultUser, AdminUser, AdministrativeContact, etc suclasses, some of which will or won't implement the Login (Loginable?) interface as necessary.
Using Bootstrap 4.4.1, I was able to set the number of cards per deck using simple classes by adding some scss into the mix.
<div class="card-deck deck-1 deck-md-2 deck-lg-3">
<div class="card">
<h2 class="card-header">Card 1</h3>
<div class="card-body">
Card body
</div>
<div class="card-footer">
Card footer
</div>
</div>
<div class="card">
<h2 class="card-header">Card 2</h3>
<div class="card-body">
Card body
</div>
<div class="card-footer">
Card footer
</div>
</div>
<div class="card">
<h2 class="card-header">Card 3</h3>
<div class="card-body">
Card body
</div>
<div class="card-footer">
Card footer
</div>
</div>
</div>
// _card_deck_columns.scss
// add deck-X and deck-BP-X classes to select the number of cards per line
@for $i from 1 through $grid-columns {
.deck-#{$i} > .card {
$percentage: percentage(1 / $i);
@if $i == 1 {
$width: $percentage;
flex-basis: $width;
max-width: $width;
margin-left: 0;
margin-right: 0;
} @else {
$width: unquote("calc(#{$percentage} - #{$grid-gutter-width})");
flex-basis: $width;
max-width: $width;
}
}
}
@each $breakpoint in map-keys($grid-breakpoints) {
$infix: breakpoint-infix($breakpoint, $grid-breakpoints);
@include media-breakpoint-up($breakpoint) {
@for $i from 1 through $grid-columns {
.deck#{$infix}-#{$i} > .card {
$percentage: percentage(1 / $i);
@if $i == 1 {
$width: $percentage;
flex-basis: $width;
max-width: $width;
margin-left: 0;
margin-right: 0;
} @else {
$width: unquote("calc(#{$percentage} - #{$grid-gutter-width})");
flex-basis: $width;
max-width: $width;
margin-left: $grid-gutter-width / 2;
margin-right: $grid-gutter-width / 2;
}
}
}
}
}
.deck-1 > .card {
flex-basis: 100%;
max-width: 100%;
margin-left: 0;
margin-right: 0; }
.deck-2 > .card {
flex-basis: calc(50% - 30px);
max-width: calc(50% - 30px); }
.deck-3 > .card {
flex-basis: calc(33.3333333333% - 30px);
max-width: calc(33.3333333333% - 30px); }
.deck-4 > .card {
flex-basis: calc(25% - 30px);
max-width: calc(25% - 30px); }
.deck-5 > .card {
flex-basis: calc(20% - 30px);
max-width: calc(20% - 30px); }
.deck-6 > .card {
flex-basis: calc(16.6666666667% - 30px);
max-width: calc(16.6666666667% - 30px); }
.deck-7 > .card {
flex-basis: calc(14.2857142857% - 30px);
max-width: calc(14.2857142857% - 30px); }
.deck-8 > .card {
flex-basis: calc(12.5% - 30px);
max-width: calc(12.5% - 30px); }
.deck-9 > .card {
flex-basis: calc(11.1111111111% - 30px);
max-width: calc(11.1111111111% - 30px); }
.deck-10 > .card {
flex-basis: calc(10% - 30px);
max-width: calc(10% - 30px); }
.deck-11 > .card {
flex-basis: calc(9.0909090909% - 30px);
max-width: calc(9.0909090909% - 30px); }
.deck-12 > .card {
flex-basis: calc(8.3333333333% - 30px);
max-width: calc(8.3333333333% - 30px); }
.deck-1 > .card {
flex-basis: 100%;
max-width: 100%;
margin-left: 0;
margin-right: 0; }
.deck-2 > .card {
flex-basis: calc(50% - 30px);
max-width: calc(50% - 30px);
margin-left: 15px;
margin-right: 15px; }
.deck-3 > .card {
flex-basis: calc(33.3333333333% - 30px);
max-width: calc(33.3333333333% - 30px);
margin-left: 15px;
margin-right: 15px; }
.deck-4 > .card {
flex-basis: calc(25% - 30px);
max-width: calc(25% - 30px);
margin-left: 15px;
margin-right: 15px; }
.deck-5 > .card {
flex-basis: calc(20% - 30px);
max-width: calc(20% - 30px);
margin-left: 15px;
margin-right: 15px; }
.deck-6 > .card {
flex-basis: calc(16.6666666667% - 30px);
max-width: calc(16.6666666667% - 30px);
margin-left: 15px;
margin-right: 15px; }
.deck-7 > .card {
flex-basis: calc(14.2857142857% - 30px);
max-width: calc(14.2857142857% - 30px);
margin-left: 15px;
margin-right: 15px; }
.deck-8 > .card {
flex-basis: calc(12.5% - 30px);
max-width: calc(12.5% - 30px);
margin-left: 15px;
margin-right: 15px; }
.deck-9 > .card {
flex-basis: calc(11.1111111111% - 30px);
max-width: calc(11.1111111111% - 30px);
margin-left: 15px;
margin-right: 15px; }
.deck-10 > .card {
flex-basis: calc(10% - 30px);
max-width: calc(10% - 30px);
margin-left: 15px;
margin-right: 15px; }
.deck-11 > .card {
flex-basis: calc(9.0909090909% - 30px);
max-width: calc(9.0909090909% - 30px);
margin-left: 15px;
margin-right: 15px; }
.deck-12 > .card {
flex-basis: calc(8.3333333333% - 30px);
max-width: calc(8.3333333333% - 30px);
margin-left: 15px;
margin-right: 15px; }
@media (min-width: 576px) {
.deck-sm-1 > .card {
flex-basis: 100%;
max-width: 100%;
margin-left: 0;
margin-right: 0; }
.deck-sm-2 > .card {
flex-basis: calc(50% - 30px);
max-width: calc(50% - 30px);
margin-left: 15px;
margin-right: 15px; }
.deck-sm-3 > .card {
flex-basis: calc(33.3333333333% - 30px);
max-width: calc(33.3333333333% - 30px);
margin-left: 15px;
margin-right: 15px; }
.deck-sm-4 > .card {
flex-basis: calc(25% - 30px);
max-width: calc(25% - 30px);
margin-left: 15px;
margin-right: 15px; }
.deck-sm-5 > .card {
flex-basis: calc(20% - 30px);
max-width: calc(20% - 30px);
margin-left: 15px;
margin-right: 15px; }
.deck-sm-6 > .card {
flex-basis: calc(16.6666666667% - 30px);
max-width: calc(16.6666666667% - 30px);
margin-left: 15px;
margin-right: 15px; }
.deck-sm-7 > .card {
flex-basis: calc(14.2857142857% - 30px);
max-width: calc(14.2857142857% - 30px);
margin-left: 15px;
margin-right: 15px; }
.deck-sm-8 > .card {
flex-basis: calc(12.5% - 30px);
max-width: calc(12.5% - 30px);
margin-left: 15px;
margin-right: 15px; }
.deck-sm-9 > .card {
flex-basis: calc(11.1111111111% - 30px);
max-width: calc(11.1111111111% - 30px);
margin-left: 15px;
margin-right: 15px; }
.deck-sm-10 > .card {
flex-basis: calc(10% - 30px);
max-width: calc(10% - 30px);
margin-left: 15px;
margin-right: 15px; }
.deck-sm-11 > .card {
flex-basis: calc(9.0909090909% - 30px);
max-width: calc(9.0909090909% - 30px);
margin-left: 15px;
margin-right: 15px; }
.deck-sm-12 > .card {
flex-basis: calc(8.3333333333% - 30px);
max-width: calc(8.3333333333% - 30px);
margin-left: 15px;
margin-right: 15px; } }
@media (min-width: 768px) {
.deck-md-1 > .card {
flex-basis: 100%;
max-width: 100%;
margin-left: 0;
margin-right: 0; }
.deck-md-2 > .card {
flex-basis: calc(50% - 30px);
max-width: calc(50% - 30px);
margin-left: 15px;
margin-right: 15px; }
.deck-md-3 > .card {
flex-basis: calc(33.3333333333% - 30px);
max-width: calc(33.3333333333% - 30px);
margin-left: 15px;
margin-right: 15px; }
.deck-md-4 > .card {
flex-basis: calc(25% - 30px);
max-width: calc(25% - 30px);
margin-left: 15px;
margin-right: 15px; }
.deck-md-5 > .card {
flex-basis: calc(20% - 30px);
max-width: calc(20% - 30px);
margin-left: 15px;
margin-right: 15px; }
.deck-md-6 > .card {
flex-basis: calc(16.6666666667% - 30px);
max-width: calc(16.6666666667% - 30px);
margin-left: 15px;
margin-right: 15px; }
.deck-md-7 > .card {
flex-basis: calc(14.2857142857% - 30px);
max-width: calc(14.2857142857% - 30px);
margin-left: 15px;
margin-right: 15px; }
.deck-md-8 > .card {
flex-basis: calc(12.5% - 30px);
max-width: calc(12.5% - 30px);
margin-left: 15px;
margin-right: 15px; }
.deck-md-9 > .card {
flex-basis: calc(11.1111111111% - 30px);
max-width: calc(11.1111111111% - 30px);
margin-left: 15px;
margin-right: 15px; }
.deck-md-10 > .card {
flex-basis: calc(10% - 30px);
max-width: calc(10% - 30px);
margin-left: 15px;
margin-right: 15px; }
.deck-md-11 > .card {
flex-basis: calc(9.0909090909% - 30px);
max-width: calc(9.0909090909% - 30px);
margin-left: 15px;
margin-right: 15px; }
.deck-md-12 > .card {
flex-basis: calc(8.3333333333% - 30px);
max-width: calc(8.3333333333% - 30px);
margin-left: 15px;
margin-right: 15px; } }
@media (min-width: 992px) {
.deck-lg-1 > .card {
flex-basis: 100%;
max-width: 100%;
margin-left: 0;
margin-right: 0; }
.deck-lg-2 > .card {
flex-basis: calc(50% - 30px);
max-width: calc(50% - 30px);
margin-left: 15px;
margin-right: 15px; }
.deck-lg-3 > .card {
flex-basis: calc(33.3333333333% - 30px);
max-width: calc(33.3333333333% - 30px);
margin-left: 15px;
margin-right: 15px; }
.deck-lg-4 > .card {
flex-basis: calc(25% - 30px);
max-width: calc(25% - 30px);
margin-left: 15px;
margin-right: 15px; }
.deck-lg-5 > .card {
flex-basis: calc(20% - 30px);
max-width: calc(20% - 30px);
margin-left: 15px;
margin-right: 15px; }
.deck-lg-6 > .card {
flex-basis: calc(16.6666666667% - 30px);
max-width: calc(16.6666666667% - 30px);
margin-left: 15px;
margin-right: 15px; }
.deck-lg-7 > .card {
flex-basis: calc(14.2857142857% - 30px);
max-width: calc(14.2857142857% - 30px);
margin-left: 15px;
margin-right: 15px; }
.deck-lg-8 > .card {
flex-basis: calc(12.5% - 30px);
max-width: calc(12.5% - 30px);
margin-left: 15px;
margin-right: 15px; }
.deck-lg-9 > .card {
flex-basis: calc(11.1111111111% - 30px);
max-width: calc(11.1111111111% - 30px);
margin-left: 15px;
margin-right: 15px; }
.deck-lg-10 > .card {
flex-basis: calc(10% - 30px);
max-width: calc(10% - 30px);
margin-left: 15px;
margin-right: 15px; }
.deck-lg-11 > .card {
flex-basis: calc(9.0909090909% - 30px);
max-width: calc(9.0909090909% - 30px);
margin-left: 15px;
margin-right: 15px; }
.deck-lg-12 > .card {
flex-basis: calc(8.3333333333% - 30px);
max-width: calc(8.3333333333% - 30px);
margin-left: 15px;
margin-right: 15px; } }
@media (min-width: 1200px) {
.deck-xl-1 > .card {
flex-basis: 100%;
max-width: 100%;
margin-left: 0;
margin-right: 0; }
.deck-xl-2 > .card {
flex-basis: calc(50% - 30px);
max-width: calc(50% - 30px);
margin-left: 15px;
margin-right: 15px; }
.deck-xl-3 > .card {
flex-basis: calc(33.3333333333% - 30px);
max-width: calc(33.3333333333% - 30px);
margin-left: 15px;
margin-right: 15px; }
.deck-xl-4 > .card {
flex-basis: calc(25% - 30px);
max-width: calc(25% - 30px);
margin-left: 15px;
margin-right: 15px; }
.deck-xl-5 > .card {
flex-basis: calc(20% - 30px);
max-width: calc(20% - 30px);
margin-left: 15px;
margin-right: 15px; }
.deck-xl-6 > .card {
flex-basis: calc(16.6666666667% - 30px);
max-width: calc(16.6666666667% - 30px);
margin-left: 15px;
margin-right: 15px; }
.deck-xl-7 > .card {
flex-basis: calc(14.2857142857% - 30px);
max-width: calc(14.2857142857% - 30px);
margin-left: 15px;
margin-right: 15px; }
.deck-xl-8 > .card {
flex-basis: calc(12.5% - 30px);
max-width: calc(12.5% - 30px);
margin-left: 15px;
margin-right: 15px; }
.deck-xl-9 > .card {
flex-basis: calc(11.1111111111% - 30px);
max-width: calc(11.1111111111% - 30px);
margin-left: 15px;
margin-right: 15px; }
.deck-xl-10 > .card {
flex-basis: calc(10% - 30px);
max-width: calc(10% - 30px);
margin-left: 15px;
margin-right: 15px; }
.deck-xl-11 > .card {
flex-basis: calc(9.0909090909% - 30px);
max-width: calc(9.0909090909% - 30px);
margin-left: 15px;
margin-right: 15px; }
.deck-xl-12 > .card {
flex-basis: calc(8.3333333333% - 30px);
max-width: calc(8.3333333333% - 30px);
margin-left: 15px;
margin-right: 15px; } }
An array "decays" into a pointer to its first element, so scanf("%s", string)
is equivalent to scanf("%s", &string[0])
. On the other hand, scanf("%s", &string)
passes a pointer-to-char[256]
, but it points to the same place.
Then scanf
, when processing the tail of its argument list, will try to pull out a char *
. That's the Right Thing when you've passed in string
or &string[0]
, but when you've passed in &string
you're depending on something that the language standard doesn't guarantee, namely that the pointers &string
and &string[0]
-- pointers to objects of different types and sizes that start at the same place -- are represented the same way.
I don't believe I've ever encountered a system on which that doesn't work, and in practice you're probably safe. None the less, it's wrong, and it could fail on some platforms. (Hypothetical example: a "debugging" implementation that includes type information with every pointer. I think the C implementation on the Symbolics "Lisp Machines" did something like this.)
This might not work in all situations, but here is what I did: I extended the FilterInputStream class and do the required processing of the bytes as the external lib reads the data.
public class StreamBytesWithExtraProcessingInputStream extends FilterInputStream {
protected StreamBytesWithExtraProcessingInputStream(InputStream in) {
super(in);
}
@Override
public int read() throws IOException {
int readByte = super.read();
processByte(readByte);
return readByte;
}
@Override
public int read(byte[] buffer, int offset, int count) throws IOException {
int readBytes = super.read(buffer, offset, count);
processBytes(buffer, offset, readBytes);
return readBytes;
}
private void processBytes(byte[] buffer, int offset, int readBytes) {
for (int i = 0; i < readBytes; i++) {
processByte(buffer[i + offset]);
}
}
private void processByte(int readByte) {
// TODO do processing here
}
}
Then you simply pass an instance of StreamBytesWithExtraProcessingInputStream
where you would have passed in the input stream. With the original input stream as constructor parameter.
It should be noted that this works byte for byte, so don't use this if high performance is a requirement.
Array has no indexOf()
method.
Maybe this Apache Commons Lang ArrayUtils
method is what you are looking for
import org.apache.commons.lang3.ArrayUtils;
String[] colours = { "Red", "Orange", "Yellow", "Green" };
int indexOfYellow = ArrayUtils.indexOf(colours, "Yellow");
Its possible using pseudo element (after).
I have added to the original code a
position:relativeand some margin.
#content{
width: 100px;
min-height: 100px;
margin: 20px auto;
border-style: ridge;
border-color: #567498;
border-spacing:10px;
position:relative;
background:#000;
}
#content:after {
content: '';
position: absolute;
top: -15px;
left: -15px;
right: -15px;
bottom: -15px;
border: red 2px solid;
}
Below are the steps to create a branch from trunk using TortoiseSVN in windows machine. This obviously needs TortoiseSVN client to be installed.
I faced the same issue, spent too much calories searching for the right fix until I decided to settle down with file reading:
Properties configProps = new Properties();
InputStream iStream = new ClassPathResource("myapp-test.properties").getInputStream();
InputStream iStream = getConfigFile();
configProps.load(iStream);
Yet Another Option:
>>> [re.split(r'(\d+)', s) for s in ('foofo21', 'bar432', 'foobar12345')]
[['foofo', '21', ''], ['bar', '432', ''], ['foobar', '12345', '']]
Life span of java Thread is over after completion of run()
method. Same thread can't be started again.
Looper transforms normal Thread
into a message loop. Key methods of Looper
are :
void prepare ()
Initialize the current thread as a looper. This gives you a chance to create handlers that then reference this looper, before actually starting the loop. Be sure to call loop() after calling this method, and end it by calling quit().
void loop ()
Run the message queue in this thread. Be sure to call quit() to end the loop.
void quit()
Quits the looper.
Causes the loop() method to terminate without processing any more messages in the message queue.
This mindorks article by Janishar explains the core concepts in nice way.
Looper
is associated with a Thread. If you need Looper
on UI thread, Looper.getMainLooper()
will return associated thread.
You need Looper
to be associated with a Handler.
Looper
, Handler
, and HandlerThread
are the Android’s way of solving the problems of asynchronous programming.
Once you have Handler
, you can call below APIs.
post (Runnable r)
Causes the Runnable r to be added to the message queue. The runnable will be run on the thread to which this handler is attached.
boolean sendMessage (Message msg)
Pushes a message onto the end of the message queue after all pending messages before the current time. It will be received in handleMessage(Message), in the thread attached to this handler.
HandlerThread is handy class for starting a new thread that has a looper. The looper can then be used to create handler classes
In some scenarios, you can't run Runnable
tasks on UI Thread.
e.g. Network operations : Send message on a socket, open an URL and get content by reading InputStream
In these cases, HandlerThread
is useful. You can get Looper
object from HandlerThread
and create a Handler
on HandlerThread
instead of main thread.
The HandlerThread code will be like this:
@Override
public void run() {
mTid = Process.myTid();
Looper.prepare();
synchronized (this) {
mLooper = Looper.myLooper();
notifyAll();
}
Process.setThreadPriority(mPriority);
onLooperPrepared();
Looper.loop();
mTid = -1;
}
Refer to below post for example code:
Being specific to Angular2 to 5, we can bind image path using property binding as below. Image path is enclosed by the single quotation marks.
Sample example
<img [src]="'assets/img/klogo.png'" alt="image">
This will require Node.js 7 or later with a support for Promises and Async/Await.
Create a wrapper function that leverage promises to control the behavior of the child_process.exec
command.
Using promises and an asynchronous function, you can mimic the behavior of a shell returning the output, without falling into a callback hell and with a pretty neat API. Using the await
keyword, you can create a script that reads easily, while still be able to get the work of child_process.exec
done.
const childProcess = require("child_process");
/**
* @param {string} command A shell command to execute
* @return {Promise<string>} A promise that resolve to the output of the shell command, or an error
* @example const output = await execute("ls -alh");
*/
function execute(command) {
/**
* @param {Function} resolve A function that resolves the promise
* @param {Function} reject A function that fails the promise
* @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise
*/
return new Promise(function(resolve, reject) {
/**
* @param {Error} error An error triggered during the execution of the childProcess.exec command
* @param {string|Buffer} standardOutput The result of the shell command execution
* @param {string|Buffer} standardError The error resulting of the shell command execution
* @see https://nodejs.org/api/child_process.html#child_process_child_process_exec_command_options_callback
*/
childProcess.exec(command, function(error, standardOutput, standardError) {
if (error) {
reject();
return;
}
if (standardError) {
reject(standardError);
return;
}
resolve(standardOutput);
});
});
}
async function main() {
try {
const passwdContent = await execute("cat /etc/passwd");
console.log(passwdContent);
} catch (error) {
console.error(error.toString());
}
try {
const shadowContent = await execute("cat /etc/shadow");
console.log(shadowContent);
} catch (error) {
console.error(error.toString());
}
}
main();
root:x:0:0::/root:/bin/bash
[output trimmed, bottom line it succeeded]
Error: Command failed: cat /etc/shadow
cat: /etc/shadow: Permission denied
Besides being a bitwise complement operator, ~
can also help revert a boolean value, though it is not the conventional bool
type here, rather you should use numpy.bool_
.
This is explained in,
import numpy as np
assert ~np.True_ == np.False_
Reversing logical value can be useful sometimes, e.g., below ~
operator is used to cleanse your dataset and return you a column without NaN.
from numpy import NaN
import pandas as pd
matrix = pd.DataFrame([1,2,3,4,NaN], columns=['Number'], dtype='float64')
# Remove NaN in column 'Number'
matrix['Number'][~matrix['Number'].isnull()]
I will give you steps to writing and compiling code. Use this example:
public class Paycheck {
public static void main(String args[]) {
double amountInAccount;
amountInAccount = 128.57;
System.out.print("You earned $");
System.out.print(amountInAccount);
System.out.println(" at work today.");
}
}
Paycheck.java
cd Desktop
javac Paycheck.java
java Paycheck
You can use transitions to delay the :hover
effect you want, if the effect is CSS-based.
For example
div{
transition: 0s background-color;
}
div:hover{
background-color:red;
transition-delay:1s;
}
this will delay applying the the hover effects (background-color
in this case) for one second.
Demo of delay on both hover on and off:
div{_x000D_
display:inline-block;_x000D_
padding:5px;_x000D_
margin:10px;_x000D_
border:1px solid #ccc;_x000D_
transition: 0s background-color;_x000D_
transition-delay:1s;_x000D_
}_x000D_
div:hover{_x000D_
background-color:red;_x000D_
}
_x000D_
<div>delayed hover</div>
_x000D_
Demo of delay only on hover on:
div{_x000D_
display:inline-block;_x000D_
padding:5px;_x000D_
margin:10px;_x000D_
border:1px solid #ccc;_x000D_
transition: 0s background-color;_x000D_
}_x000D_
div:hover{_x000D_
background-color:red; _x000D_
transition-delay:1s;_x000D_
}
_x000D_
<div>delayed hover</div>
_x000D_
Vendor Specific Extentions for Transitions and W3C CSS3 transitions
There's a really nice easy way to do this in Macintosh OsX. A fellow has made a quicklook plugin (command-space) that renders .mat formats so you can view the variables inside etc. Quite useful! https://github.com/jaketmp/matlab-quicklook/releases
Here is an another way find value index in complex array in javascript. Hope help somebody indeed. Let us assume we have a JavaScript array as following,
var studentsArray =
[
{
"rollnumber": 1,
"name": "dj",
"subject": "physics"
},
{
"rollnumber": 2,
"name": "tanmay",
"subject": "biology"
},
{
"rollnumber": 3,
"name": "amit",
"subject": "chemistry"
},
];
Now if we have a requirement to select a particular object in the array. Let us assume that we want to find index of student with name Tanmay.
We can do that by iterating through the array and comparing value at the given key.
function functiontofindIndexByKeyValue(arraytosearch, key, valuetosearch) {
for (var i = 0; i < arraytosearch.length; i++) {
if (arraytosearch[i][key] == valuetosearch) {
return i;
}
}
return null;
}
You can use the function to find index of a particular element as below,
var index = functiontofindIndexByKeyValue(studentsArray, "name", "tanmay");
alert(index);
I suggest you to update your SDK and start new project and recompile everything you have. It seems you have some inner program errors. Or you are missing package.
And ofc do what Abdijeek said.
The ID will work with @
sign in front also, but we have to add one parameter after that. that is null
look like:
@Html.ActionLink("Label Name", "Name_Of_Page_To_Redirect", "Controller", new {@id="Id_Value"}, null)
You can just go to the place where the screen session is housed and run:
screen -ls
which results in
There is a screen on:
26727.pts-0.devxxx (Attached)
1 Socket in /tmp/uscreens/S-xxx. <------ this is where the session is.
And just remove it:
cd /tmp/uscreens/S-xxx
ls
26727.pts-0.devxxx
rm 26727.pts-0.devxxx
ls
The uscreens
directory will not have the 26727.pts-0.devxxx
file in it anymore. Now to make sure just type this:
screen -ls
and you should get:
No Sockets found in /tmp/uscreens/S-xxx.
As josh527
said, handler.removeCallbacksAndMessages(null);
can work.
But why?
If you have a look at the source code, you can understand it more clearly.
There are 3 type of method to remove callbacks/messages from handler(the MessageQueue):
Handler.java (leave some overload method)
/**
* Remove any pending posts of Runnable <var>r</var> with Object
* <var>token</var> that are in the message queue. If <var>token</var> is null,
* all callbacks will be removed.
*/
public final void removeCallbacks(Runnable r, Object token)
{
mQueue.removeMessages(this, r, token);
}
/**
* Remove any pending posts of messages with code 'what' and whose obj is
* 'object' that are in the message queue. If <var>object</var> is null,
* all messages will be removed.
*/
public final void removeMessages(int what, Object object) {
mQueue.removeMessages(this, what, object);
}
/**
* Remove any pending posts of callbacks and sent messages whose
* <var>obj</var> is <var>token</var>. If <var>token</var> is null,
* all callbacks and messages will be removed.
*/
public final void removeCallbacksAndMessages(Object token) {
mQueue.removeCallbacksAndMessages(this, token);
}
MessageQueue.java do the real work:
void removeMessages(Handler h, int what, Object object) {
if (h == null) {
return;
}
synchronized (this) {
Message p = mMessages;
// Remove all messages at front.
while (p != null && p.target == h && p.what == what
&& (object == null || p.obj == object)) {
Message n = p.next;
mMessages = n;
p.recycleUnchecked();
p = n;
}
// Remove all messages after front.
while (p != null) {
Message n = p.next;
if (n != null) {
if (n.target == h && n.what == what
&& (object == null || n.obj == object)) {
Message nn = n.next;
n.recycleUnchecked();
p.next = nn;
continue;
}
}
p = n;
}
}
}
void removeMessages(Handler h, Runnable r, Object object) {
if (h == null || r == null) {
return;
}
synchronized (this) {
Message p = mMessages;
// Remove all messages at front.
while (p != null && p.target == h && p.callback == r
&& (object == null || p.obj == object)) {
Message n = p.next;
mMessages = n;
p.recycleUnchecked();
p = n;
}
// Remove all messages after front.
while (p != null) {
Message n = p.next;
if (n != null) {
if (n.target == h && n.callback == r
&& (object == null || n.obj == object)) {
Message nn = n.next;
n.recycleUnchecked();
p.next = nn;
continue;
}
}
p = n;
}
}
}
void removeCallbacksAndMessages(Handler h, Object object) {
if (h == null) {
return;
}
synchronized (this) {
Message p = mMessages;
// Remove all messages at front.
while (p != null && p.target == h
&& (object == null || p.obj == object)) {
Message n = p.next;
mMessages = n;
p.recycleUnchecked();
p = n;
}
// Remove all messages after front.
while (p != null) {
Message n = p.next;
if (n != null) {
if (n.target == h && (object == null || n.obj == object)) {
Message nn = n.next;
n.recycleUnchecked();
p.next = nn;
continue;
}
}
p = n;
}
}
}
If you want it to be List<string>
, get rid of the anonymous type and add a .ToList()
call:
List<string> list = (from char c in source
select c.ToString()).ToList();
compare
has overloads for comparing substrings. If you're comparing whole strings you should just use ==
operator (and whether it calls compare
or not is pretty much irrelevant).
Yes, you can.
@supports (-webkit-touch-callout: none) {
/* CSS specific to iOS devices */
}
@supports not (-webkit-touch-callout: none) {
/* CSS for other than iOS devices */
}
YMMV.
It works because only Safari Mobile implements -webkit-touch-callout
: https://developer.mozilla.org/en-US/docs/Web/CSS/-webkit-touch-callout
Please note that @supports
does not work in IE. IE will skip both of the above @support
blocks above. To find out more see https://hacks.mozilla.org/2016/08/using-feature-queries-in-css/. It is recommended to not use @supports not
because of this.
What about Chrome or Firefox on iOS? The reality is these are just skins over the WebKit rendering engine. Hence the above works everywhere on iOS as long as iOS policy does not change. See 2.5.6 in App Store Review Guidelines.
Warning: iOS may remove support for this in any new iOS release in the coming years. You SHOULD try a bit harder to not need the above CSS. An earlier version of this answer used -webkit-overflow-scrolling
but a new iOS version removed it. As a commenter pointed out, there are other options to choose from: Go to Supported CSS Properties and search for "Safari on iOS".
int main () //start of main fcn
{
int values[ 20 ]; //delcares array and how many elements
int small,big; //declares integer
for ( int i = 0; i < 20; i++ ) //counts to 20 and prompts user for value and stores it
{
cout << "Enter value " << i << ": ";
cin >> values[i];
}
big=small=values[0]; //assigns element to be highest or lowest value
for (int i = 0; i < 20; i++) //works out bigggest number
{
if(values[i]>big) //compare biggest value with current element
{
big=values[i];
}
if(values[i]<small) //compares smallest value with current element
{
small=values[i];
}
}
cout << "The biggest number is " << big << endl; //prints outs biggest no
cout << "The smallest number is " << small << endl; //prints out smalles no
}
You should use strcat
, or better, strncat
. Google it (the keyword is "concatenating").
This is the only way that worked for me using Python 3.5.2
plus it's the easiest to implement w/ using the standard PyData
suite
Shout out to https://stackoverflow.com/users/4502363/gadi-oron for the answer (I copied it completely) from How do I copy a string to the clipboard on Windows using Python?
import pandas as pd
df=pd.DataFrame(['Text to copy'])
df.to_clipboard(index=False,header=False)
I wrote a little wrapper for it that I put in my ipython
profile <3
The notation that is used in
a[::-1]
means that for a given string/list/tuple, you can slice the said object using the format
<object_name>[<start_index>, <stop_index>, <step>]
This means that the object is going to slice every "step" index from the given start index, till the stop index (excluding the stop index) and return it to you.
In case the start index or stop index is missing, it takes up the default value as the start index and stop index of the given string/list/tuple. If the step is left blank, then it takes the default value of 1 i.e it goes through each index.
So,
a = '1234'
print a[::2]
would print
13
Now the indexing here and also the step count, support negative numbers. So, if you give a -1 index, it translates to len(a)-1 index. And if you give -x as the step count, then it would step every x'th value from the start index, till the stop index in the reverse direction. For example
a = '1234'
print a[3:0:-1]
This would return
432
Note, that it doesn't return 4321 because, the stop index is not included.
Now in your case,
str(int(a[::-1]))
would just reverse a given integer, that is stored in a string, and then convert it back to a string
i.e "1234" -> "4321" -> 4321 -> "4321"
If what you are trying to do is just reverse the given string, then simply a[::-1] would work .
If you can use boost,
#include <boost/filesystem.hpp>
path p("C:\\MyDirectory\\MyFile.bat");
string basename = p.filename().string();
//or
//string basename = path("C:\\MyDirectory\\MyFile.bat").filename().string();
This is all.
I recommend you to use boost library. Boost gives you a lot of conveniences when you work with C++. It supports almost all platforms.
If you use Ubuntu, you can install boost library by only one line sudo apt-get install libboost-all-dev
(ref. How to Install boost on Ubuntu?)
Android already has a dedicated class for this. Check DateUtils.isToday(long when)
I had the same sort of need and found this to work well for me (postgres 8.4):
CAST((COALESCE(myfield,'0')) AS INTEGER)
Some test cases to demonstrate:
db=> select CAST((COALESCE(NULL,'0')) AS INTEGER);
int4
------
0
(1 row)
db=> select CAST((COALESCE('','0')) AS INTEGER);
int4
------
0
(1 row)
db=> select CAST((COALESCE('4','0')) AS INTEGER);
int4
------
4
(1 row)
db=> select CAST((COALESCE('bad','0')) AS INTEGER);
ERROR: invalid input syntax for integer: "bad"
If you need to handle the possibility of the field having non-numeric text (such as "100bad") you can use regexp_replace to strip non-numeric characters before the cast.
CAST(REGEXP_REPLACE(COALESCE(myfield,'0'), '[^0-9]+', '', 'g') AS INTEGER)
Then text/varchar values like "b3ad5" will also give numbers
db=> select CAST(REGEXP_REPLACE(COALESCE('b3ad5','0'), '[^0-9]+', '', 'g') AS INTEGER);
regexp_replace
----------------
35
(1 row)
To address Chris Cogdon's concern with the solution not giving 0 for all cases, including a case such as "bad" (no digit characters at all), I made this adjusted statement:
CAST((COALESCE(NULLIF(REGEXP_REPLACE(myfield, '[^0-9]+', '', 'g'), ''), '0')) AS INTEGER);
It works similar to the simpler solutions, except will give 0 when the value to convert is non-digit characters only, such as "bad":
db=> select CAST((COALESCE(NULLIF(REGEXP_REPLACE('no longer bad!', '[^0-9]+', '', 'g'), ''), '0')) AS INTEGER);
coalesce
----------
0
(1 row)
I have a sample
import * as types from '../../helpers/ActionTypes';
var initialState = {
changedValues: {}
};
const quickEdit = (state = initialState, action) => {
switch (action.type) {
case types.PRODUCT_QUICKEDIT:
{
const item = action.item;
const changedValues = {
...state.changedValues,
[item.id]: item,
};
return {
...state,
loading: true,
changedValues: changedValues,
};
}
default:
{
return state;
}
}
};
export default quickEdit;
In Express you can use
res.redirect('http://example.com');
to redirect user from server.
To include a status code 301 or 302 it can be used
res.redirect(301, 'http://example.com');
Dim
and Private
work the same, though the common convention is to use Private
at the module level, and Dim
at the Sub/Function level. Public
and Global
are nearly identical in their function, however Global
can only be used in standard modules, whereas Public
can be used in all contexts (modules, classes, controls, forms etc.) Global
comes from older versions of VB and was likely kept for backwards compatibility, but has been wholly superseded by Public
.
Try encodeURIComponent.
Encodes a Uniform Resource Identifier (URI) component by replacing each instance of certain characters by one, two, three, or four escape sequences representing the UTF-8 encoding of the character (will only be four escape sequences for characters composed of two "surrogate" characters).
Example:
var encoded = encodeURIComponent(str);
A good (and simple) solution as pointed out in the comments on the original question is to use the stack
property of an Error
object like so:
function stackTrace() {
var err = new Error();
return err.stack;
}
This will generate output like this:
DBX.Utils.stackTrace@http://localhost:49573/assets/js/scripts.js:44
DBX.Console.Debug@http://localhost:49573/assets/js/scripts.js:9
.success@http://localhost:49573/:462
x.Callbacks/c@http://localhost:49573/assets/js/jquery-1.10.2.min.js:4
x.Callbacks/p.fireWith@http://localhost:49573/assets/js/jquery-1.10.2.min.js:4
k@http://localhost:49573/assets/js/jquery-1.10.2.min.js:6
.send/r@http://localhost:49573/assets/js/jquery-1.10.2.min.js:6
Giving the name of the calling function along with the URL and line number, its calling function, and so on.
I have a really elaborate and pretty solution that I have devised for a project I am currently working on and I have extracted and reworked it a bit to be generalized. Here it is:
(function(context){
// Only global namespace.
var Console = {
//Settings
settings: {
debug: {
alwaysShowURL: false,
enabled: true,
showInfo: true
},
stackTrace: {
enabled: true,
collapsed: true,
ignoreDebugFuncs: true,
spacing: false
}
}
};
// String formatting prototype function.
if (!String.prototype.format) {
String.prototype.format = function () {
var s = this.toString(),
args = typeof arguments[0],
args = (("string" == args || "number" == args) ? arguments : arguments[0]);
if (!arguments.length)
return s;
for (arg in args)
s = s.replace(RegExp("\\{" + arg + "\\}", "gi"), args[arg]);
return s;
}
}
// String repeating prototype function.
if (!String.prototype.times) {
String.prototype.times = function () {
var s = this.toString(),
tempStr = "",
times = arguments[0];
if (!arguments.length)
return s;
for (var i = 0; i < times; i++)
tempStr += s;
return tempStr;
}
}
// Commonly used functions
Console.debug = function () {
if (Console.settings.debug.enabled) {
var args = ((typeof arguments !== 'undefined') ? Array.prototype.slice.call(arguments, 0) : []),
sUA = navigator.userAgent,
currentBrowser = {
firefox: /firefox/gi.test(sUA),
webkit: /webkit/gi.test(sUA),
},
aLines = Console.stackTrace().split("\n"),
aCurrentLine,
iCurrIndex = ((currentBrowser.webkit) ? 3 : 2),
sCssBlack = "color:black;",
sCssFormat = "color:{0}; font-weight:bold;",
sLines = "";
if (currentBrowser.firefox)
aCurrentLine = aLines[iCurrIndex].replace(/(.*):/, "$1@").split("@");
else if (currentBrowser.webkit)
aCurrentLine = aLines[iCurrIndex].replace("at ", "").replace(")", "").replace(/( \()/gi, "@").replace(/(.*):(\d*):(\d*)/, "$1@$2@$3").split("@");
// Show info if the setting is true and there's no extra trace (would be kind of pointless).
if (Console.settings.debug.showInfo && !Console.settings.stackTrace.enabled) {
var sFunc = aCurrentLine[0].trim(),
sURL = aCurrentLine[1].trim(),
sURL = ((!Console.settings.debug.alwaysShowURL && context.location.href == sURL) ? "this page" : sURL),
sLine = aCurrentLine[2].trim(),
sCol;
if (currentBrowser.webkit)
sCol = aCurrentLine[3].trim();
console.info("%cOn line %c{0}%c{1}%c{2}%c of %c{3}%c inside the %c{4}%c function:".format(sLine, ((currentBrowser.webkit) ? ", column " : ""), ((currentBrowser.webkit) ? sCol : ""), sURL, sFunc),
sCssBlack, sCssFormat.format("red"),
sCssBlack, sCssFormat.format("purple"),
sCssBlack, sCssFormat.format("green"),
sCssBlack, sCssFormat.format("blue"),
sCssBlack);
}
// If the setting permits, get rid of the two obvious debug functions (Console.debug and Console.stackTrace).
if (Console.settings.stackTrace.ignoreDebugFuncs) {
// In WebKit (Chrome at least), there's an extra line at the top that says "Error" so adjust for this.
if (currentBrowser.webkit)
aLines.shift();
aLines.shift();
aLines.shift();
}
sLines = aLines.join(((Console.settings.stackTrace.spacing) ? "\n\n" : "\n")).trim();
trace = typeof trace !== 'undefined' ? trace : true;
if (typeof console !== "undefined") {
for (var arg in args)
console.debug(args[arg]);
if (Console.settings.stackTrace.enabled) {
var sCss = "color:red; font-weight: bold;",
sTitle = "%c Stack Trace" + " ".times(70);
if (Console.settings.stackTrace.collapsed)
console.groupCollapsed(sTitle, sCss);
else
console.group(sTitle, sCss);
console.debug("%c" + sLines, "color: #666666; font-style: italic;");
console.groupEnd();
}
}
}
}
Console.stackTrace = function () {
var err = new Error();
return err.stack;
}
context.Console = Console;
})(window);
Check it out on GitHub (currently v1.2)! You can use it like Console.debug("Whatever");
and it will, depending on the settings in Console
, print the output and a stack trace (or just simple info/nothing extra at all). Here's an example:
Make sure to play around with the settings in the Console
object! You can add spacing between the lines of the trace and turn it off entirely. Here it is with Console.trace
set to false
:
You can even turn off the first bit of info shown (set Console.settings.debug.showInfo
to false
) or disable debugging entirely (set Console.settings.debug.enabled
to false
) so you never have to comment out a debug statement again! Just leave them in and this will do nothing.
As mentioned in other answers, all of the following will work for the standard string-based syntax.
WAITFOR DELAY '02:00' --Two hours
WAITFOR DELAY '00:02' --Two minutes
WAITFOR DELAY '00:00:02' --Two seconds
WAITFOR DELAY '00:00:00.200' --Two tenths of a seconds
There is also an alternative method of passing it a DATETIME
value. You might think I'm confusing this with WAITFOR TIME
, but it also works for WAITFOR DELAY
.
Considerations for passing DATETIME
:
'1900-01-01'
).DATETIME
than to properly format a VARCHAR
.How to wait for 2 seconds:
--Example 1
DECLARE @Delay1 DATETIME
SELECT @Delay1 = '1900-01-01 00:00:02.000'
WAITFOR DELAY @Delay1
--Example 2
DECLARE @Delay2 DATETIME
SELECT @Delay2 = dateadd(SECOND, 2, convert(DATETIME, 0))
WAITFOR DELAY @Delay2
A note on waiting for TIME
vs DELAY
:
Have you ever noticed that if you accidentally pass WAITFOR TIME
a date that already passed, even by just a second, it will never return? Check it out:
--Example 3
DECLARE @Time1 DATETIME
SELECT @Time1 = getdate()
WAITFOR DELAY '00:00:01'
WAITFOR TIME @Time1 --WILL HANG FOREVER
Unfortunately, WAITFOR DELAY
will do the same thing if you pass it a negative DATETIME
value (yes, that's a thing).
--Example 4
DECLARE @Delay3 DATETIME
SELECT @Delay3 = dateadd(SECOND, -1, convert(DATETIME, 0))
WAITFOR DELAY @Delay3 --WILL HANG FOREVER
However, I would still recommend using WAITFOR DELAY
over a static time because you can always confirm your delay is positive and it will stay that way for however long it takes your code to reach the WAITFOR
statement.
copy the image that you want to show in android app and paste in drawable folder. given below code
<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:src="@drawable/image"
/>
public class MostFrequentNumber {
public MostFrequentNumber() {
}
int frequentNumber(List<Integer> list){
int popular = 0;
int holder = 0;
for(Integer number: list) {
int freq = Collections.frequency(list,number);
if(holder < freq){
holder = freq;
popular = number;
}
}
return popular;
}
public static void main(String[] args){
int[] numbers = {4,6,2,5,4,7,6,4,7,7,7};
List<Integer> list = new ArrayList<Integer>();
for(Integer num : numbers){
list.add(num);
}
MostFrequentNumber mostFrequentNumber = new MostFrequentNumber();
System.out.println(mostFrequentNumber.frequentNumber(list));
}
}
Change your positioning a bit:
.container {
border: 1px solid #DDDDDD;
width: 200px;
height: 200px;
position:relative;
}
.tag {
float: left;
position: absolute;
left: 0px;
top: 0px;
background-color: green;
}
You need to set relative positioning on the container and then absolute on the inner tag div. The inner tag's absolute positioning will be with respect to the outer relatively positioned div. You don't even need the z-index rule on the tag div.
myCars.TakeWhile(car => !myCondition(car)).Count();
It works! Think about it. The index of the first matching item equals the number of (not matching) item before it.
I too dislike the horrible standard solution you already suggested in your question. Like the accepted answer I went for a plain old loop although with a slight modification:
public static int FindIndex<T>(this IEnumerable<T> items, Predicate<T> predicate) {
int index = 0;
foreach (var item in items) {
if (predicate(item)) break;
index++;
}
return index;
}
Note that it will return the number of items instead of -1
when there is no match. But let's ignore this minor annoyance for now. In fact the horrible standard solution crashes in that case and I consider returning an index that is out-of-bounds superior.
What happens now is ReSharper telling me Loop can be converted into LINQ-expression. While most of the time the feature worsens readability, this time the result was awe-inspiring. So Kudos to the JetBrains.
new
ing anonymous objectsTherefore I consider it optimal in time and space while remaining readable.
-1
when there is no matchOf course you can always hide it behind an extension method. And what to do best when there is no match heavily depends on the context.
It's simply “No such directory entry”. Since directory entries can be directories or files (or symlinks, or sockets, or pipes, or devices), the name ENOFILE
would have been too narrow in its meaning.
For Intellij IDEA Community 2019.1 you will need to follow these steps :
File -> New -> Edit File Templates.. -> Class -> /* Created by ${USER} on ${DATE} */
One thing to note - as I had exactly this problem today, depending on your HTML jQuery may or may not parse it that well. jQuery wouldn't parse my HTML into a correct DOM - on smaller XML compliant files it worked fine, but the HTML I had (that would render in a page) wouldn't parse when passed back to an Ajax callback.
In the end I simply searched manually in the string for the tag I wanted, not ideal but did work.
The command setwd("~/")
should set your working directory to your home directory. You might be experiencing problems because the OS you are using does not recognise "~/"
as your home directory: this might be because of the OS, or it might be because of not having set that as your home directory elsewhere.
As you have tagged the post using RStudio:
You will now have set the folder as your working directory. Use the command getwd()
to get the working directory as it is now set, and save that as a variable string at the top of your script. Then use setwd
with that string as the argument, so that each time you run the script you use the same directory.
For example at the top of my script I would have:
work_dir <- "C:/Users/john.smith/Documents"
setwd(work_dir)
You might be interested by https://github.com/pandas-ml/pandas-ml/
which implements a Python Pandas implementation of Confusion Matrix.
Some features:
Here is an example:
In [1]: from pandas_ml import ConfusionMatrix
In [2]: import matplotlib.pyplot as plt
In [3]: y_test = ['business', 'business', 'business', 'business', 'business',
'business', 'business', 'business', 'business', 'business',
'business', 'business', 'business', 'business', 'business',
'business', 'business', 'business', 'business', 'business']
In [4]: y_pred = ['health', 'business', 'business', 'business', 'business',
'business', 'health', 'health', 'business', 'business', 'business',
'business', 'business', 'business', 'business', 'business',
'health', 'health', 'business', 'health']
In [5]: cm = ConfusionMatrix(y_test, y_pred)
In [6]: cm
Out[6]:
Predicted business health __all__
Actual
business 14 6 20
health 0 0 0
__all__ 14 6 20
In [7]: cm.plot()
Out[7]: <matplotlib.axes._subplots.AxesSubplot at 0x1093cf9b0>
In [8]: plt.show()
In [9]: cm.print_stats()
Confusion Matrix:
Predicted business health __all__
Actual
business 14 6 20
health 0 0 0
__all__ 14 6 20
Overall Statistics:
Accuracy: 0.7
95% CI: (0.45721081772371086, 0.88106840959427235)
No Information Rate: ToDo
P-Value [Acc > NIR]: 0.608009812201
Kappa: 0.0
Mcnemar's Test P-Value: ToDo
Class Statistics:
Classes business health
Population 20 20
P: Condition positive 20 0
N: Condition negative 0 20
Test outcome positive 14 6
Test outcome negative 6 14
TP: True Positive 14 0
TN: True Negative 0 14
FP: False Positive 0 6
FN: False Negative 6 0
TPR: (Sensitivity, hit rate, recall) 0.7 NaN
TNR=SPC: (Specificity) NaN 0.7
PPV: Pos Pred Value (Precision) 1 0
NPV: Neg Pred Value 0 1
FPR: False-out NaN 0.3
FDR: False Discovery Rate 0 1
FNR: Miss Rate 0.3 NaN
ACC: Accuracy 0.7 0.7
F1 score 0.8235294 0
MCC: Matthews correlation coefficient NaN NaN
Informedness NaN NaN
Markedness 0 0
Prevalence 1 0
LR+: Positive likelihood ratio NaN NaN
LR-: Negative likelihood ratio NaN NaN
DOR: Diagnostic odds ratio NaN NaN
FOR: False omission rate 1 0
JavaScript is always synchronous and single-threaded. If you're executing a JavaScript block of code on a page then no other JavaScript on that page will currently be executed.
JavaScript is only asynchronous in the sense that it can make, for example, Ajax calls. The Ajax call will stop executing and other code will be able to execute until the call returns (successfully or otherwise), at which point the callback will run synchronously. No other code will be running at this point. It won't interrupt any other code that's currently running.
JavaScript timers operate with this same kind of callback.
Describing JavaScript as asynchronous is perhaps misleading. It's more accurate to say that JavaScript is synchronous and single-threaded with various callback mechanisms.
jQuery has an option on Ajax calls to make them synchronously (with the async: false
option). Beginners might be tempted to use this incorrectly because it allows a more traditional programming model that one might be more used to. The reason it's problematic is that this option will block all JavaScript on the page until it finishes, including all event handlers and timers.
return collection.All(i => i == collection.First()))
? collection.First() : otherValue;.
Or if you're worried about executing First() for each element (which could be a valid performance concern):
var first = collection.First();
return collection.All(i => i == first) ? first : otherValue;
Make sure right depency is selected. File > Project Structure
Select your project and navigate to Dependencies tab. Select right dependancy from dropdown or create new.
maxAge = Persons.Max(c => c.age)
or something along those lines.
I am using below solution for IIS hosting in ASP.NET compatibility mode. Credits to Rodney Viana's MSDN blog.
Add following to your web.config under appSettings:
<add key="LogPath" value="C:\\logpath" />
<add key="LogRequestResponse" value="true" />
Replace your global.asax.cs with below (also fix namespace name):
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.SessionState;
using System.Text;
using System.IO;
using System.Configuration;
namespace Yournamespace
{
public class Global : System.Web.HttpApplication
{
protected static bool LogFlag;
protected static string fileNameBase;
protected static string ext = "log";
// One file name per day
protected string FileName
{
get
{
return String.Format("{0}{1}.{2}", fileNameBase, DateTime.Now.ToString("yyyy-MM-dd"), ext);
}
}
protected void Application_Start(object sender, EventArgs e)
{
LogFlag = bool.Parse(ConfigurationManager.AppSettings["LogRequestResponse"].ToString());
fileNameBase = ConfigurationManager.AppSettings["LogPath"].ToString() + @"\C5API-";
}
protected void Session_Start(object sender, EventArgs e)
{
}
protected void Application_BeginRequest(object sender, EventArgs e)
{
if (LogFlag)
{
// Creates a unique id to match Rquests with Responses
string id = String.Format("Id: {0} Uri: {1}", Guid.NewGuid(), Request.Url);
FilterSaveLog input = new FilterSaveLog(HttpContext.Current, Request.Filter, FileName, id);
Request.Filter = input;
input.SetFilter(false);
FilterSaveLog output = new FilterSaveLog(HttpContext.Current, Response.Filter, FileName, id);
output.SetFilter(true);
Response.Filter = output;
}
}
protected void Application_AuthenticateRequest(object sender, EventArgs e)
{
}
protected void Application_Error(object sender, EventArgs e)
{
}
protected void Session_End(object sender, EventArgs e)
{
}
protected void Application_End(object sender, EventArgs e)
{
}
}
class FilterSaveLog : Stream
{
protected static string fileNameGlobal = null;
protected string fileName = null;
protected static object writeLock = null;
protected Stream sinkStream;
protected bool inDisk;
protected bool isClosed;
protected string id;
protected bool isResponse;
protected HttpContext context;
public FilterSaveLog(HttpContext Context, Stream Sink, string FileName, string Id)
{
// One lock per file name
if (String.IsNullOrWhiteSpace(fileNameGlobal) || fileNameGlobal.ToUpper() != fileNameGlobal.ToUpper())
{
fileNameGlobal = FileName;
writeLock = new object();
}
context = Context;
fileName = FileName;
id = Id;
sinkStream = Sink;
inDisk = false;
isClosed = false;
}
public void SetFilter(bool IsResponse)
{
isResponse = IsResponse;
id = (isResponse ? "Reponse " : "Request ") + id;
//
// For Request only read the incoming stream and log it as it will not be "filtered" for a WCF request
//
if (!IsResponse)
{
AppendToFile(String.Format("at {0} --------------------------------------------", DateTime.Now));
AppendToFile(id);
if (context.Request.InputStream.Length > 0)
{
context.Request.InputStream.Position = 0;
byte[] rawBytes = new byte[context.Request.InputStream.Length];
context.Request.InputStream.Read(rawBytes, 0, rawBytes.Length);
context.Request.InputStream.Position = 0;
AppendToFile(rawBytes);
}
else
{
AppendToFile("(no body)");
}
}
}
public void AppendToFile(string Text)
{
byte[] strArray = Encoding.UTF8.GetBytes(Text);
AppendToFile(strArray);
}
public void AppendToFile(byte[] RawBytes)
{
bool myLock = System.Threading.Monitor.TryEnter(writeLock, 100);
if (myLock)
{
try
{
using (FileStream stream = new FileStream(fileName, FileMode.OpenOrCreate, FileAccess.ReadWrite))
{
stream.Position = stream.Length;
stream.Write(RawBytes, 0, RawBytes.Length);
stream.WriteByte(13);
stream.WriteByte(10);
}
}
catch (Exception ex)
{
string str = string.Format("Unable to create log. Type: {0} Message: {1}\nStack:{2}", ex, ex.Message, ex.StackTrace);
System.Diagnostics.Debug.WriteLine(str);
System.Diagnostics.Debug.Flush();
}
finally
{
System.Threading.Monitor.Exit(writeLock);
}
}
}
public override bool CanRead
{
get { return sinkStream.CanRead; }
}
public override bool CanSeek
{
get { return sinkStream.CanSeek; }
}
public override bool CanWrite
{
get { return sinkStream.CanWrite; }
}
public override long Length
{
get
{
return sinkStream.Length;
}
}
public override long Position
{
get { return sinkStream.Position; }
set { sinkStream.Position = value; }
}
//
// For WCF this code will never be reached
//
public override int Read(byte[] buffer, int offset, int count)
{
int c = sinkStream.Read(buffer, offset, count);
return c;
}
public override long Seek(long offset, System.IO.SeekOrigin direction)
{
return sinkStream.Seek(offset, direction);
}
public override void SetLength(long length)
{
sinkStream.SetLength(length);
}
public override void Close()
{
sinkStream.Close();
isClosed = true;
}
public override void Flush()
{
sinkStream.Flush();
}
// For streamed responses (i.e. not buffered) there will be more than one Response (but the id will match the Request)
public override void Write(byte[] buffer, int offset, int count)
{
sinkStream.Write(buffer, offset, count);
AppendToFile(String.Format("at {0} --------------------------------------------", DateTime.Now));
AppendToFile(id);
AppendToFile(buffer);
}
}
}
It should create log file in the folder LogPath with request and response XML.
For Angular 1 or 2 (but not for Angular 4+):
You can also open the console and go to the element tab on the developer tools of whatever browser you use.
Or
Type angular.version to access the Javascript object that holds angular version.
For Angular 4+ There is are the number of ways as listed below :
Write below code in the command prompt/or in the terminal in the VS Code.(up to 3)
- ng version or ng --version (Find the image for the reference)
- ng v
- ng -v
In the terminal you can find the angular version as shown in the attached image :
- You can also open the console and go to the element tab on the developer tools of whatever browser you use. As displayed in the below image :
- Find the package.json file, You will find all the installed dependencies and their version.
JAVA_HOME = C:\Program Files\Java\jdk(JDK version number)
Example: C:\Program Files\Java\jdk-10
And then restart you command prompt it works.
How about this? Not using another library (dateutil
) or timedelta
?
building on vartec's answer I did this and I believe it works:
import datetime
today = datetime.date.today()
six_months_from_today = datetime.date(today.year + (today.month + 6)/12, (today.month + 6) % 12, today.day)
I tried using timedelta
, but because it is counting the days, 365/2
or 6*356/12
does not always translate to 6 months, but rather 182 days. e.g.
day = datetime.date(2015, 3, 10)
print day
>>> 2015-03-10
print (day + datetime.timedelta(6*365/12))
>>> 2015-09-08
I believe that we usually assume that 6 month's from a certain day will land on the same day of the month but 6 months later (i.e. 2015-03-10
--> 2015-09-10
, Not 2015-09-08
)
I hope you find this helpful.
Julien Danjou wrote a good article explaining why you should never deal with timezones. An excerpt:
Indeed, Python datetime API always returns unaware datetime objects, which is very unfortunate. Indeed, as soon as you get one of this object, there is no way to know what the timezone is, therefore these objects are pretty "useless" on their own.
Alas, even though you may use utcnow()
, you still won't see the timezone info, as you discovered.
Recommendations:
Always use aware
datetime
objects, i.e. with timezone information. That makes sure you can compare them directly (aware and unawaredatetime
objects are not comparable) and will return them correctly to users. Leverage pytz to have timezone objects.Use ISO 8601 as the input and output string format. Use
datetime.datetime.isoformat()
to return timestamps as string formatted using that format, which includes the timezone information.If you need to parse strings containing ISO 8601 formatted timestamps, you can rely on
iso8601
, which returns timestamps with correct timezone information. This makes timestamps directly comparable.
I used the command
ansible -i inventory example -m ping -u <your_user_name> --ask-pass
And it will ask for your password.
For anyone who gets the error:
to use the 'ssh' connection type with passwords, you must install the sshpass program
On MacOS, you can follow below instructions to install sshpass:
Both setInterval
and requestAnimationFrame
don't work when tab is inactive or work but not at the right periods. A solution is to use another source for time events. For example web sockets or web workers are two event sources that work fine while tab is inactive. So no need to move all of your code to a web worker, just use worker as a time event source:
// worker.js
setInterval(function() {
postMessage('');
}, 1000 / 50);
.
var worker = new Worker('worker.js');
var t1 = 0;
worker.onmessage = function() {
var t2 = new Date().getTime();
console.log('fps =', 1000 / (t2 - t1) | 0);
t1 = t2;
}
jsfiddle link of this sample.
HashSet:
The underlined data structure is Hashtable. Duplicate objects are not allowed.insertion order is not preserved and it is based on hash code of objects. Null insertion is possible(only once). It implements Serializable, Clonable but not RandomAccess interface. HashSet is best choose if frequent operation is search operation.
In HashSet duplicates are not allowed.if users are trying to insert duplicates when we won't get any compile or runtime exceptions. add method returns simply false.
Constructors:
HashSet h=new HashSet(); creates an empty HashSet object with default initial capacity 16 and default fill ratio(Load factor) is 0.75 .
HashSet h=new HashSet(int initialCapacity); creates an empty HashSet object with specified initialCapacity and default fill ration is 0.75.
HashSet h=new HashSet(int initialCapacity, float fillRatio);
HashSet h=new HashSet(Collection c); creates an equivalent HashSet object for the given collection. This constructor meant for inter conversion between collection object.
LinkedHashSet:
It is a child class of HashSet. it is exactly same as HashSet including(Constructors and Methods) except the following differences.
Differences HashSet:
LinkedHashSet:
Just return an object literal
function newCodes(){
var dCodes = fg.codecsCodes.rs; // Linked ICDs
var dCodes2 = fg.codecsCodes2.rs; //Linked CPTs
return {
dCodes: dCodes,
dCodes2: dCodes2
};
}
var result = newCodes();
alert(result.dCodes);
alert(result.dCodes2);
As an extension to @VinaySajip answer. There are additional nargs
worth mentioning.
parser.add_argument('dir', nargs=1, default=os.getcwd())
N (an integer). N arguments from the command line will be gathered together into a list
parser.add_argument('dir', nargs='*', default=os.getcwd())
'*'. All command-line arguments present are gathered into a list. Note that it generally doesn't make much sense to have more than one positional argument with nargs='*'
, but multiple optional arguments with nargs='*'
is possible.
parser.add_argument('dir', nargs='+', default=os.getcwd())
'+'. Just like '*', all command-line args present are gathered into a list. Additionally, an error message will be generated if there wasn’t at least one command-line argument present.
parser.add_argument('dir', nargs=argparse.REMAINDER, default=os.getcwd())
argparse.REMAINDER
. All the remaining command-line arguments are gathered into a list. This is commonly useful for command line utilities that dispatch to other command line utilities
If the nargs
keyword argument is not provided, the number of arguments consumed is determined by the action. Generally this means a single command-line argument will be consumed and a single item (not a list) will be produced.
Edit (copied from a comment by @Acumenus) nargs='?'
The docs say: '?'. One argument will be consumed from the command line if possible and produced as a single item. If no command-line argument is present, the value from default will be produced.
For others who came here via google like me - here's another approach:
css:
.disabled {
color: grey; // ...whatever
}
jQuery:
$('#myLink').click(function (e) {
e.preventDefault();
if ($(this).hasClass('disabled'))
return false; // Do something else in here if required
else
window.location.href = $(this).attr('href');
});
// Elsewhere in your code
if (disabledCondition == true)
$('#myLink').addClass('disabled')
else
$('#myLink').removeClass('disabled')
Remember: not only this is a css class
class="buttonstyle"
but also these two
class="buttonstyle disabled"
so you can easily add and remove further classes with jQuery. No need to touch href...
I love jQuery! ;-)
let suppose ,
data = {};
if( if(!$.isEmptyObject(data)))
{
document.write("Object is empty);
}
else{
document.write("Object is not empty);
}
It worked for me and its an easy way to check if object is empty or not
In IDP Init SSO (Unsolicited Web SSO) the Federation process is initiated by the IDP sending an unsolicited SAML Response to the SP. In SP-Init, the SP generates an AuthnRequest that is sent to the IDP as the first step in the Federation process and the IDP then responds with a SAML Response. IMHO ADFSv2 support for SAML2.0 Web SSO SP-Init is stronger than its IDP-Init support re: integration with 3rd Party Fed products (mostly revolving around support for RelayState) so if you have a choice you'll want to use SP-Init as it'll probably make life easier with ADFSv2.
Here are some simple SSO descriptions from the PingFederate 8.0 Getting Started Guide that you can poke through that may help as well -- https://documentation.pingidentity.com/pingfederate/pf80/index.shtml#gettingStartedGuide/task/idpInitiatedSsoPOST.html
From the documentation I get the impression that in your example it would be intended to use:
@Range(min= SEQ_MIN_VALUE, max= SEQ_MAX_VALUE)
Checks whether the annotated value lies between (inclusive) the specified minimum and maximum. Supported data types:
BigDecimal, BigInteger, CharSequence, byte, short, int, long and the respective wrappers of the primitive types
i had reached for this and i hope to help all create my_controller in application/core then put this code in it with change as your file's name
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
// this is page helper to load pages daunamically
class MY_Controller extends CI_Controller {
function loadPage($user,$data,$page='home'){
switch($user){
case 'user':
$this->load->view('Temp/head',$data);
$this->load->view('Temp/us_sidebar',$data);
$this->load->view('Users/'.$page,$data);
$this->load->view('Temp/footer',$data);
break;
case 'admin':
$this->load->view('Temp/head',$data);
$this->load->view('Temp/ad_sidebar',$data);
$this->load->view('Admin/'.$page,$data);
$this->load->view('Temp/footer',$data);
break;
case 'visitor';
$this->load->view('Temp/head',$data);
$this->load->view($page);
$this->load->view('Temp/footer',$data);
break;
default:
echo 'wrong argument';
die();
}//end switch
}//end function loadPage
}
in your controller use this
class yourControllerName extends MY_Controller
note : about name of controller prefix you have to be sure about your prefix on config.php file i hope that give help to any one
It has 2 possible solutions:
1) You can set it in the view by javascript... (not recomended)
<input class="form-control"
type="text"
id="tbFormControll"
th:field="*{clientName}"/>
<script type="text/javascript">
document.getElementById("tbFormControll").value = "default";
</script>
2) Or the better solution is to set the value in the model, that you attach to the view in GET operation by a controller. You can also change the value in the controller, just make a Java object from $client.name and call setClientName.
public class FormControllModel {
...
private String clientName = "default";
public String getClientName () {
return clientName;
}
public void setClientName (String value) {
clientName = value;
}
...
}
I hope it helps.
I don't think a message box is the best way to go with this as you would need the VB code running in a loop to check the cell contents, or unless you plan to run the macro manually. In this case I think it would be better to add conditional formatting to the cell to change the background to red (for example) if the value exceeds the upper limit.
If you don't want to list the fields, and the structure of the tables is the same, you can do:
INSERT INTO `table2` SELECT * FROM `table1`;
or if you want to create a new table with the same structure:
CREATE TABLE new_tbl [AS] SELECT * FROM orig_tbl;
Reference for insert select; Reference for create table select
Here is the briefest summary I could make of the two strongest arguments for and against using the new
operator:
new
new
operator can have disastrous
effects if they are incorrectly
invoked as normal functions. A
function's code in such a case will
be executed in the scope where the
function is called, instead of in
the scope of a local object as
intended. This can cause global
variables and properties to get
overwritten with disastrous
consequences.function Func()
,
and then calling Func.prototype
and adding stuff to it so that you
can call new Func()
to construct
your object seems ugly to some
programmers, who would rather use
another style of object inheritance
for architectural and stylistic
reasons.For more on this argument check out Douglas Crockford's great and concise book Javascript: The Good Parts. In fact check it out anyway.
new
new
operator along with
prototypal assignment is fast.See John Resig's post for a simple explanation of this technique, and for a generally deeper explanation of the inheritance model he advocates.
They mean different things.
If you use var
the variable is declared within the scope you are in (e.g. of the function). If you don't use var
, the variable bubbles up through the layers of scope until it encounters a variable by the given name or the global object (window, if you are doing it in the browser), where it then attaches. It is then very similar to a global variable. However, it can still be deleted with delete
(most likely by someone else's code who also failed to use var
). If you use var
in the global scope, the variable is truly global and cannot be deleted.
This is, in my opinion, one of the most dangerous issues with javascript, and should be deprecated, or at least raise warnings over warnings. The reason is, it's easy to forget var
and have by accident a common variable name bound to the global object. This produces weird and difficult to debug behavior.
request.getContextPath()-
returns root path of your application, while
../
- returns parent directory of a file.
You use request.getContextPath(), as it will always points to root of your application. If you were to move your jsp file from one directory to another, nothing needs to be changed. Now, consider the second approach. If you were to move your jsp files from one folder to another, you'd have to make changes at every location where you are referring your files.
Also, better approach of using request.getContextPath() will be to set 'request.getContextPath()' in a variable and use that variable for referring your path.
<c:set var="context" value="${pageContext.request.contextPath}" />
<script src="${context}/themes/js/jquery.js"></script>
PS- This is the one reason I can figure out. Don't know if there is any more significance to it.
In android gradle 0.4.0 you can just do:
println System.env.HOME
classpath com.android.tools.build:gradle-experimental:0.4.0
You can use #define as an alternative solution, which do not introduce vector and malloc, and you are still using the same syntax when defining an array.
#define row 8
#define col 8
int main()
{
int array_name[row][col];
}
$parts = preg_split('/\s+/', $str);
There are two scenarios to compare files:
Scenario 1: Compare files at remote branches (both branches should exists on remote repository)
Scenario 2: Compare local files (at local working area copy) to the files at remote repository.
The logic is simple. If you provide two branch names to diff, it will always compare the remote branches, and if you provide only one branch name, it will always compare your local working copy with the remote repo (the one you provided). You can use range to provide remote repositories.
e.g. Checkout a branch
git checkout branch1
git diff branch2 [filename]
in this case, if you provide filename, it will compare your local copy of filename with remote branch named "branch2".
git diff branch1 branch2 [filename]
in this case, it will compare filename from remote branches named "branch1" vs "branch2"
git diff ..branch2 [filename]
in this case also, it will compare filename from remote branches named "branch1" vs "branch2". So, its same as above. However, if you have just created a branch from another branch, say "master" and your current branch doesn't exists on remote repository, it will compare remote "master" vs remote "branch2".
Hope its useful.
SELECT ..., CONCAT( 'category_id=', tableOne.category_id) as query2 FROM tableOne
LEFT JOIN tableTwo
ON tableTwo.query = query2
package com.keshav.datePicker_With_Hide_Future_Past_Date;
import android.app.DatePickerDialog;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.DatePicker;
import android.widget.EditText;
import java.util.Calendar;
public class MainActivity extends AppCompatActivity {
EditText ed_date;
int year;
int month;
int day;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ed_date=(EditText) findViewById(R.id.et_date);
ed_date.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
Calendar mcurrentDate=Calendar.getInstance();
year=mcurrentDate.get(Calendar.YEAR);
month=mcurrentDate.get(Calendar.MONTH);
day=mcurrentDate.get(Calendar.DAY_OF_MONTH);
final DatePickerDialog mDatePicker =new DatePickerDialog(MainActivity.this, new DatePickerDialog.OnDateSetListener()
{
@Override
public void onDateSet(DatePicker datepicker, int selectedyear, int selectedmonth, int selectedday)
{
ed_date.setText(new StringBuilder().append(year).append("-").append(month+1).append("-").append(day));
int month_k=selectedmonth+1;
}
},year, month, day);
mDatePicker.setTitle("Please select date");
// TODO Hide Future Date Here
mDatePicker.getDatePicker().setMaxDate(System.currentTimeMillis());
// TODO Hide Past Date Here
// mDatePicker.getDatePicker().setMinDate(System.currentTimeMillis());
mDatePicker.show();
}
});
}
}
// Its Working
The original question concerns Dialogs and my EditText is on a regular view. Anyhow, I suspect this should work for most of you too. So here's what works for me (the above suggested highest rated method did nothing for me). Here's a custom EditView that does this (subclassing is not necessary, but I found it convenient for my purposes as I wanted to also grab the focus when the view becomes visible).
This is actually largely the same as the tidbecks answer. I actually didn't notice his answer at all as it had zero up votes. Then I was about to just comment his post, but it would have been too long, so I ended doing this post anyways. tidbeck points out that he's unsure how it works with devices having keyboards. I can confirm that the behaviour seems to be exactly the same in either case. That being such that on portrait mode the software keyboard gets popped up and on landscape it doesn't. Having the physical keyboard slid out or not makes no difference on my phone.
Because, I personally found the behaviour a bit awkward I opted for using: InputMethodManager.SHOW_FORCED
. This works as I wanted it to work. The keyboard becomes visible regardless of the orientation, however, at least on my device it doesn't pop up if the hardware keyboard has been slid out.
import android.app.Service;
import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
public class BringOutTheSoftInputOnFocusEditTextView extends EditText {
protected InputMethodManager inputMethodManager;
public BringOutTheSoftInputOnFocusEditTextView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init();
}
public BringOutTheSoftInputOnFocusEditTextView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public BringOutTheSoftInputOnFocusEditTextView(Context context) {
super(context);
init();
}
private void init() {
this.inputMethodManager = (InputMethodManager)getContext().getSystemService(Service.INPUT_METHOD_SERVICE);
this.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if (hasFocus) {
BringOutTheSoftInputOnFocusEditTextView.this.inputMethodManager.showSoftInput(BringOutTheSoftInputOnFocusEditTextView.this, InputMethodManager.SHOW_FORCED);
}
}
});
}
@Override
protected void onVisibilityChanged(View changedView, int visibility) {
super.onVisibilityChanged(changedView, visibility);
if (visibility == View.VISIBLE) {
BringOutTheSoftInputOnFocusEditTextView.this.requestFocus();
}
}
}
Rails does not use the stdlib's ERB by default, it uses erubis. Sources: this dev's comment, ActionView's gemspec, accepted merge request I did while writing this.
There are behavior differences between them, in particular on how the hyphen operators %-
and -%
work.
Documentation is scarce, Where is Ruby's ERB format "officially" defined? so what follows are empirical conclusions.
All tests suppose:
require 'erb'
require 'erubis'
When you can use -
-
to trim_mode
option of ERB.new
to use it.Examples:
begin ERB.new("<%= 'a' -%>\nb").result; rescue SyntaxError ; else raise; end
ERB.new("<%= 'a' -%>\nb" , nil, '-') .result == 'ab' or raise
Erubis::Eruby.new("<%= 'a' -%> \n b").result == 'a b' or raise
What -%
does:
ERB: remove the next character if it is a newline.
erubis:
in <% %>
(without =
), -
is useless because <% %>
and <% -%>
are the same. <% %>
removes the current line if it only contains whitespaces, and does nothing otherwise.
in <%= -%>
(with =
):
Examples:
# Remove
ERB.new("a \nb <% 0 -%>\n c", nil, '-').result == "a \nb c" or raise
# Don't do anything: not followed by newline, but by space:
ERB.new("a\n<% 0 -%> \nc", nil, '-').result == "a\nb \nc" or raise
# Remove the current line because only whitesapaces:
Erubis::Eruby.new(" <% 0 %> \nb").result == 'b' or raise
# Same as above, thus useless because longer.
Erubis::Eruby.new(" <% 0 -%> \nb").result == 'b' or raise
# Don't do anything because line not empty.
Erubis::Eruby.new("a <% 0 %> \nb").result == "a \nb" or raise
Erubis::Eruby.new(" <% 0 %> a\nb").result == " a\nb" or raise
Erubis::Eruby.new(" <% 0 -%> a\nb").result == " a\nb" or raise
# Don't remove the current line because of `=`:
Erubis::Eruby.new(" <%= 0 %> \nb").result == " 0 \nb" or raise
# Remove the current line even with `=`:
Erubis::Eruby.new(" <%= 0 -%> \nb").result == " 0b" or raise
# Remove forward only because of `-` and non space before:
Erubis::Eruby.new("a <%= 0 -%> \nb").result == "a 0b" or raise
# Don't do anything because non-whitespace forward:
Erubis::Eruby.new(" <%= 0 -%> a\nb").result == " 0 a\nb" or raise
What %-
does:
ERB: remove whitespaces before tag and after previous newlines, but only if there are only whitespaces before.
erubis: useless because <%- %>
is the same as <% %>
(without =
), and this cannot be used with =
which is the only case where -%
can be useful. So never use this.
Examples:
# Remove
ERB.new("a \n <%- 0 %> b\n c", nil, '-').result == "a \n b\n c" or raise
# b is not whitespace: do nothing:
ERB.new("a \nb <%- 0 %> c\n d", nil, '-').result == "a \nb c\n d" or raise
What %-
and -%
do together
The exact combination of both effects separately.
http://php.net/manual/en/function.unlink.php
Unlink can safely remove a single file; just make sure the file you are removing it actually a file and not a directory ('.' or '..')
if (is_file($filepath))
{
unlink($filepath);
}
bool b = list.Contains("Hello", StringComparer.CurrentCultureIgnoreCase);
[EDIT] extension code:
public static bool Contains(this string source, string cont
, StringComparison compare)
{
return source.IndexOf(cont, compare) >= 0;
}
This could work :)
I had this problem of no .env files showing up in the project.
Turns out the IDE I was using (Netbeans, try not to judge) will show certain types of .hidden files but not all.
After racking my brains for a bit I checked the file system and found the .env + .env.example files / modified them with a text editor.
Leaving this answer for the rare situation someones using a dodgy IDE like myself.
Using jQuery, you can do it easily:
$("input").addClass("class-name")
Here is your input tag
@Html.EditorFor(model => model.Name)
For DropDownlist you can use this one:
$("select").addClass("class-name")
For Dropdownlist:
@Html.DropDownlistFor(model=>model.Name)
On Mac OS use
find -E packages -regex ".*\.(jpg|gif|png|jpeg)"
If speed is your concern, then you should use as less memory copying as possible. Thus it is required to work with arrays of chars.
public static String repeatString(String what, int howmany) {
char[] pattern = what.toCharArray();
char[] res = new char[howmany * pattern.length];
int length = pattern.length;
for (int i = 0; i < howmany; i++)
System.arraycopy(pattern, 0, res, i * length, length);
return new String(res);
}
To test speed, a similar optimal method using StirngBuilder is like this:
public static String repeatStringSB(String what, int howmany) {
StringBuilder out = new StringBuilder(what.length() * howmany);
for (int i = 0; i < howmany; i++)
out.append(what);
return out.toString();
}
and the code to test it:
public static void main(String... args) {
String res;
long time;
for (int j = 0; j < 1000; j++) {
res = repeatString("123", 100000);
res = repeatStringSB("123", 100000);
}
time = System.nanoTime();
res = repeatString("123", 1000000);
time = System.nanoTime() - time;
System.out.println("elapsed repeatString: " + time);
time = System.nanoTime();
res = repeatStringSB("123", 1000000);
time = System.nanoTime() - time;
System.out.println("elapsed repeatStringSB: " + time);
}
And here the run results from my system:
elapsed repeatString: 6006571
elapsed repeatStringSB: 9064937
Note that the test for loop is to kick in JIT and have optimal results.
If you're using Python 2.5 or later, the uuid module is already included with the Python standard distribution.
Ex:
>>> import uuid
>>> uuid.uuid4()
UUID('5361a11b-615c-42bf-9bdb-e2c3790ada14')
I've had this error when I tried applying context menus to my TreeView
. Those tries ended up in a bad XAML which compiled somehow:
<TreeView Height="Auto" MinHeight="100" ItemsSource="{Binding Path=TreeNodes, Mode=TwoWay}"
ContextMenu="{Binding Converter={StaticResource ContextMenuConverter}}">
ContextMenu="">
<TreeView.ItemContainerStyle>
...
Note the problematic line: ContextMenu="">
.
I don't know why it compiled, but I figured it's worth mentioning as a reason for this cryptic exception message. Like Armentage said, look around the XAML carefully, especially in places you've recently edited.
I thought I'd throw in my two cents with a simple (and not complete) implementation of a date range:
from datetime import date, timedelta, datetime
class DateRange:
def __init__(self, start, end, step=timedelta(1)):
self.start = start
self.end = end
self.step = step
def __iter__(self):
start = self.start
step = self.step
end = self.end
n = int((end - start) / step)
d = start
for _ in range(n):
yield d
d += step
def __contains__(self, value):
return (
(self.start <= value < self.end) and
((value - self.start) % self.step == timedelta(0))
)
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="com.example.app"
tools:ignore="GoogleAppIndexingWarning">
You can remove the warning by adding xmlns:tools="http://schemas.android.com/tools"
and tools:ignore="GoogleAppIndexingWarning"
to the <manifest>
tag.
For Folder Copy You can Use
robocopy C:\Source D:\Destination /E
For File Copy
copy D:\Sourcefile.txt D:\backup\Destinationfile.txt /Y
Delete file in some folder last modify date more than some day
forfiles -p "D:\FolderPath" -s -m *.[Filetype eg-->.txt] -d -[Numberof dates] -c "cmd /c del @PATH"
And you can Shedule task in windows perform this task automatically in specific time.