What does the exclamation mark after the gem name in the 'DEPENDECIES' group mean?
The exclamation mark appears when the gem was installed using a source other than "https://rubygems.org".
It's all a perceptual thing. Git is generally rather good at recognising moves, because GIT is a content tracker
All that really depends is how your "stat" displays it. The only difference here is the -M flag.
git log --stat -M
commit 9c034a76d394352134ee2f4ede8a209ebec96288
Author: Kent Fredric
Date: Fri Jan 9 22:13:51 2009 +1300
Category Restructure
lib/Gentoo/Repository.pm | 10 +++++-----
lib/Gentoo/{ => Repository}/Base.pm | 2 +-
lib/Gentoo/{ => Repository}/Category.pm | 12 ++++++------
lib/Gentoo/{ => Repository}/Package.pm | 10 +++++-----
lib/Gentoo/{ => Repository}/Types.pm | 10 +++++-----
5 files changed, 22 insertions(+), 22 deletions(-)
git log --stat
commit 9c034a76d394352134ee2f4ede8a209ebec96288
Author: Kent Fredric
Date: Fri Jan 9 22:13:51 2009 +1300
Category Restructure
lib/Gentoo/Base.pm | 36 ------------------------
lib/Gentoo/Category.pm | 51 ----------------------------------
lib/Gentoo/Package.pm | 41 ---------------------------
lib/Gentoo/Repository.pm | 10 +++---
lib/Gentoo/Repository/Base.pm | 36 ++++++++++++++++++++++++
lib/Gentoo/Repository/Category.pm | 51 ++++++++++++++++++++++++++++++++++
lib/Gentoo/Repository/Package.pm | 41 +++++++++++++++++++++++++++
lib/Gentoo/Repository/Types.pm | 55 +++++++++++++++++++++++++++++++++++++
lib/Gentoo/Types.pm | 55 -------------------------------------
9 files changed, 188 insertions(+), 188 deletions(-)
git help log
-M
Detect renames.
-C
Detect copies as well as renames. See also --find-copies-harder.
Use .. LIMIT :pageSize OFFSET :pageStart
Where :pageStart
is bound to the_page_index (i.e. 0 for the first page) * number_of_items_per_pages (e.g. 4) and :pageSize
is bound to number_of_items_per_pages.
To detect for "has more pages", either use SQL_CALC_FOUND_ROWS or use .. LIMIT :pageSize OFFSET :pageStart + 1
and detect a missing last (pageSize+1) record. Needless to say, for pages with an index > 0, there exists a previous page.
If the page index value is embedded in the URL (e.g. in "prev page" and "next page" links) then it can be obtained via the appropriate $_GET
item.
Learning C forces you to think harder about some issues such as explicit and implicit memory management or storage sizes of basic data types at the time you write your code.
Once you have reached a point where you feel comfortable around C's features and misfeatures, you will probably have less trouble learning and writing in C++.
It is entirely possible that the C++ code you have seen did not look much different from standard C, but that may well be because it was not object oriented and did not use exceptions, object-orientation, templates or other advanced features.
You can use $expr ( 3.6 mongo version operator ) to use aggregation functions in regular query.
Compare query operators
vs aggregation comparison operators
.
Regular Query:
db.T.find({$expr:{$gt:["$Grade1", "$Grade2"]}})
Aggregation Query:
db.T.aggregate({$match:{$expr:{$gt:["$Grade1", "$Grade2"]}}})
Your syntax is incorrect.
card_value = $(array[i]).val();
or card_value = array[i].value;
array[i] is not a jQuery object (for some reason).
Checking your browser's console can be helpful for things like this.
The else
is only connected to the last if
. You want elif
:
if 'bad' in line:
pass
elif 'naughty' in line:
pass
else:
newopen.write(line)
Also note that I removed the line substitution, as you don't write those lines anyway.
Use http://[jenkins-server]/exit
This page shows how to use URL commands.
You can use ServerXMLHTTP
in a VBA project by adding a reference to MSXML
.
- Open the VBA Editor (usually by editing a Macro)
- Go to the list of Available References
- Check Microsoft XML
- Click OK.
(from Referencing MSXML within VBA Projects)
The ServerXMLHTTP MSDN documentation has full details about all the properties and methods of ServerXMLHTTP.
In short though, it works basically like this:
- Call open method to connect to the remote server
- Call send to send the request.
- Read the response via responseXML, responseText, responseStream or responseBody
If you happen to use CRA with default yarn
package manager use the following. Worked for me.
yarn remove node-sass
yarn add [email protected]
Declare PtrSafe Function URLDownloadToFile Lib "urlmon" Alias "URLDownloadToFileA" _
(ByVal pCaller As Long, ByVal szURL As String, ByVal szFileName As String, _
ByVal dwReserved As Long, ByVal lpfnCB As Long) As Long
Sub Example()
DownloadFile$ = "someFile.ext" 'here the name with extension
URL$ = "http://some.web.address/" & DownloadFile 'Here is the web address
LocalFilename$ = "C:\Some\Path" & DownloadFile !OR! CurrentProject.Path & "\" & DownloadFile 'here the drive and download directory
MsgBox "Download Status : " & URLDownloadToFile(0, URL, LocalFilename, 0, 0) = 0
End Sub
I found the above when looking for downloading from FTP with username and address in URL. Users supply information and then make the calls.
This was helpful because our organization has Kaspersky AV which blocks active
FTP.exe, but not web connections. We were unable to develop in house with ftp.exe and this was our solution. Hope this helps other looking for info!
Python's built-in itertools
module actually has a groupby
function , but for that the elements to be grouped must first be sorted such that the elements to be grouped are contiguous in the list:
from operator import itemgetter
sortkeyfn = itemgetter(1)
input = [('11013331', 'KAT'), ('9085267', 'NOT'), ('5238761', 'ETH'),
('5349618', 'ETH'), ('11788544', 'NOT'), ('962142', 'ETH'), ('7795297', 'ETH'),
('7341464', 'ETH'), ('9843236', 'KAT'), ('5594916', 'ETH'), ('1550003', 'ETH')]
input.sort(key=sortkeyfn)
Now input looks like:
[('5238761', 'ETH'), ('5349618', 'ETH'), ('962142', 'ETH'), ('7795297', 'ETH'),
('7341464', 'ETH'), ('5594916', 'ETH'), ('1550003', 'ETH'), ('11013331', 'KAT'),
('9843236', 'KAT'), ('9085267', 'NOT'), ('11788544', 'NOT')]
groupby
returns a sequence of 2-tuples, of the form (key, values_iterator)
. What we want is to turn this into a list of dicts where the 'type' is the key, and 'items' is a list of the 0'th elements of the tuples returned by the values_iterator. Like this:
from itertools import groupby
result = []
for key,valuesiter in groupby(input, key=sortkeyfn):
result.append(dict(type=key, items=list(v[0] for v in valuesiter)))
Now result
contains your desired dict, as stated in your question.
You might consider, though, just making a single dict out of this, keyed by type, and each value containing the list of values. In your current form, to find the values for a particular type, you'll have to iterate over the list to find the dict containing the matching 'type' key, and then get the 'items' element from it. If you use a single dict instead of a list of 1-item dicts, you can find the items for a particular type with a single keyed lookup into the master dict. Using groupby
, this would look like:
result = {}
for key,valuesiter in groupby(input, key=sortkeyfn):
result[key] = list(v[0] for v in valuesiter)
result
now contains this dict (this is similar to the intermediate res
defaultdict in @KennyTM's answer):
{'NOT': ['9085267', '11788544'],
'ETH': ['5238761', '5349618', '962142', '7795297', '7341464', '5594916', '1550003'],
'KAT': ['11013331', '9843236']}
(If you want to reduce this to a one-liner, you can:
result = dict((key,list(v[0] for v in valuesiter)
for key,valuesiter in groupby(input, key=sortkeyfn))
or using the newfangled dict-comprehension form:
result = {key:list(v[0] for v in valuesiter)
for key,valuesiter in groupby(input, key=sortkeyfn)}
In Html
<div [style.background]="background"></div>
In Typescript
this.background=
this.sanitization.bypassSecurityTrustStyle(`url(${this.section.backgroundSrc}) no-repeat`);
A working solution.
What is the recommended way to dynamically set background image in Angular 4
Try this query.. It uses the Analytic function SUM:
SELECT * FROM
(
SELECT SUM(1) OVER(PARTITION BY ctn_no) cnt, A.*
FROM table1 a
WHERE s_ind ='Y'
)
WHERE cnt > 2
Am not sure why you are identifying a record as a duplicate if the ctn_no repeats more than 2 times. FOr me it repeats more than once it is a duplicate. In this case change the las part of the query to WHERE cnt > 1
I think the code below
<item name="android:actionMenuTextAppearance">@style/MyActionBar.MenuTextStyle</item>
must be in MyAppTheme
section.
Static type systems seek to eliminate certain errors statically, inspecting the program without running it and attempting to prove soundness in certain respects. Some type systems are able to catch more errors than others. For example, C# can eliminate null pointer exceptions when used properly, whereas Java has no such power. Twelf has a type system which actually guarantees that proofs will terminate, "solving" the halting problem.
However, no type system is perfect. In order to eliminate a particular class of errors, they must also reject certain perfectly valid programs which violate the rules. This is why Twelf doesn't really solve the halting problem, it just avoids it by throwing out a large number of perfectly valid proofs which happen to terminate in odd ways. Likewise, Java's type system rejects Clojure's PersistentVector
implementation due to its use of heterogeneous arrays. It works at runtime, but the type system cannot verify it.
For that reason, most type systems provide "escapes", ways to override the static checker. For most languages, these take the form of casting, though some (like C# and Haskell) have entire modes which are marked as "unsafe".
Subjectively, I like static typing. Implemented properly (hint: not Java), a static type system can be a huge help in weeding out errors before they crash the production system. Dynamically typed languages tend to require more unit testing, which is tedious at the best of times. Also, statically typed languages can have certain features which are either impossible or unsafe in dynamic type systems (implicit conversions spring to mind). It's all a question of requirements and subjective taste. I would no more build the next Eclipse in Ruby than I would attempt to write a backup script in Assembly or patch a kernel using Java.
Oh, and people who say that "x typing is 10 times more productive than y typing" are simply blowing smoke. Dynamic typing may "feel" faster in many cases, but it loses ground once you actually try to make your fancy application run. Likewise, static typing may seem like it's the perfect safety net, but one look at some of the more complicated generic type definitions in Java sends most developers scurrying for eye blinders. Even with type systems and productivity, there is no silver bullet.
Final note: don't worry about performance when comparing static with dynamic typing. Modern JITs like V8 and TraceMonkey are coming dangerously-close to static language performance. Also, the fact that Java actually compiles down to an inherently dynamic intermediate language should be a hint that for most cases, dynamic typing isn't the huge performance-killer that some people make it out to be.
It's as simple as iterating the array and looking for the regexp
function searchStringInArray (str, strArray) {
for (var j=0; j<strArray.length; j++) {
if (strArray[j].match(str)) return j;
}
return -1;
}
Edit - make str
as an argument to function.
scp -i ~/.ssh/key.pem ec2-user@ip:/home/ec2-user/file-to-copy.txt .
The file name shouldnt be between the pem file and the ec2-user string - that doesnt work. This also allows you to reserve the name of the copied file.
"We usually put ' (space)' after the first sentence before a new line, but it doesn't work in Jupyter."
That inspired me to try using two spaces instead of just one - and it worked!!
(Of course, that functionality could possibly have been introduced between when the question was asked in January 2017, and when my answer was posted in March 2018.)
The advantage over Ctrl-Alt-Down followed by Ctrl-X suggested by other users is that it doesn't make eclipse think that the file was changed in any way. It's also faster and causes no problems even if the user has rotating screen issue with Ctrl-Alt-Down/Up keyboard shorcut. So there's no need to remap shorcuts for this.
Another way to go would be hitting Alt-Shift-Up until the entire line gets selected. If you've gone too far, of course you can select less with Alt-Shift-Down.
Step by steps:
To create/edit the .gemrc file from the terminal:
vi ~/.gemrc
You will open a editor called vi. paste in:
gem: --no-ri --no-rdoc
click 'esc'-button.
type in:
:exit
You can check if everything is correct with this command:
sudo /Applications/TextEdit.app/Contents/MacOS/TextEdit ~/.gemrc
Assuming you want to use numpy
, you can numerically compute the derivative of a function at any point using the Rigorous definition:
def d_fun(x):
h = 1e-5 #in theory h is an infinitesimal
return (fun(x+h)-fun(x))/h
You can also use the Symmetric derivative for better results:
def d_fun(x):
h = 1e-5
return (fun(x+h)-fun(x-h))/(2*h)
Using your example, the full code should look something like:
def fun(x):
return x**2 + 1
def d_fun(x):
h = 1e-5
return (fun(x+h)-fun(x-h))/(2*h)
Now, you can numerically find the derivative at x=5
:
In [1]: d_fun(5)
Out[1]: 9.999999999621423
if you want to update the default charset on a schema:
ALTER SCHEMA MYSCHEMA DEFAULT CHARACTER SET utf8 DEFAULT COLLATE utf8_unicode_ci;
Let's say you have a collection of Car
objects (database rows), and each Car
has a collection of Wheel
objects (also rows). In other words, Car
? Wheel
is a 1-to-many relationship.
Now, let's say you need to iterate through all the cars, and for each one, print out a list of the wheels. The naive O/R implementation would do the following:
SELECT * FROM Cars;
And then for each Car
:
SELECT * FROM Wheel WHERE CarId = ?
In other words, you have one select for the Cars, and then N additional selects, where N is the total number of cars.
Alternatively, one could get all wheels and perform the lookups in memory:
SELECT * FROM Wheel
This reduces the number of round-trips to the database from N+1 to 2. Most ORM tools give you several ways to prevent N+1 selects.
Reference: Java Persistence with Hibernate, chapter 13.
For the sake of completeness, what you are trying to create is a "modal window".
Numerous JS solutions allow you to create them with ease, take the time to find the one which best suits your needs.
I have used Tinybox 2 for small projects : http://sandbox.scriptiny.com/tinybox2/
I found this way to be a good one, without having to worry too much about charsets and arrays, or iconv:
function replace_accents($str) {
$str = htmlentities($str, ENT_COMPAT, "UTF-8");
$str = preg_replace('/&([a-zA-Z])(uml|acute|grave|circ|tilde|ring);/','$1',$str);
return html_entity_decode($str);
}
I see a few answers here, most of them complicated or with some cons (additional divs, text-align doesn't work because of display: inline-block). I think this is the simplest and problem-free solution:
HTML:
<table>
<!-- Rows -->
<tr>
<td>E-MAIL</td>
<td><input name="email" type="email" /></td>
</tr>
<tr>
<td></td>
<td><input type="submit" value="Register!" /></td>
</tr>
</table>
CSS:
table input[type="submit"] {
display: block;
margin: 0 auto;
}
1.
first of all Port 80(or what ever you are using) and 443 must be allow for both TCP and UDP packets. To do this, create 2 inbound rules for TPC and UDP on Windows Firewall for port 80 and 443. (or you can disable your whole firewall for testing but permanent solution if allow inbound rule)
2.
You need to change the security setting on Apache to allow access from anywhere else, so edit your httpd.conf
file.
Change this section from :
# onlineoffline tag - don't remove
Order Deny,Allow
Deny from all
Allow from 127.0.0.1
Allow from ::1
Allow from localhost
To :
# onlineoffline tag - don't remove
Order Allow,Deny
Allow from all
if "Allow from all" line not work for your then use "Require all granted" then it will work for you.
In version 3 and > of WAMPServer there is a Virtual Hosts pre defined for localhost
so dont amend the httpd.conf
file at all, leave it as you found it.
Using the menus, edit the httpd-vhosts.conf
file.
It should look like this :
<VirtualHost *:80>
ServerName localhost
DocumentRoot D:/wamp/www
<Directory "D:/wamp/www/">
Options +Indexes +FollowSymLinks +MultiViews
AllowOverride All
Require local
</Directory>
</VirtualHost>
Amend it to
<VirtualHost *:80>
ServerName localhost
DocumentRoot D:/wamp/www
<Directory "D:/wamp/www/">
Options +Indexes +FollowSymLinks +MultiViews
AllowOverride All
Require all granted
</Directory>
</VirtualHost>
Note:if you are running wamp for other than port 80 then VirtualHost will be like VirtualHost *:86.(86 or port whatever you are using) instead of VirtualHost *:80
3. Dont forget to restart All Services of Wamp or Apache after making this change
Firstly, you should read this page thoroughly http://codex.wordpress.org/AJAX_in_Plugins
Secondly, ajax_script
is not defined so you should change to: url: ajaxurl
. I don't see your function1()
in the above code but you might already define it in other file.
And finally, learn how to debug ajax call using Firebug, network and console tab will be your friends. On the PHP side, print_r()
or var_dump()
will be your friends.
If you can hard-code the number of players
Player[] thePlayers = {
new Player(0),
new Player(1),
new Player(2),
new Player(3)
};
The best way to get rid on it is adding or modifying the data-interval attribute like this:
<div data-ride="carousel" class="carousel slide" data-interval="10000" id="myCarousel">
It's specified on ms like it's usually on js, so 1000 = 1s, 3000 = 3s... 10000 = 10s.
By the way you can also specify it at 0 for not sliding automatically. It's useful when showing product images on mobile for example.
<div data-ride="carousel" class="carousel slide" data-interval="0" id="myCarousel">
The html
<select id="drop" name="company" class="company btn btn-outline dropdown-toggle" >
<option value="demo1">Group Medical</option>
<option value="demo">Motor Insurance</option>
</select>
Script.js
$("#drop").change(function () {
var category= $('select[name=company]').val() // Here we can get the value of selected item
alert(category);
});
I am not sure I understand what you want, but based on what I understood
the x scale seems to be the same, it is the y scale that is not the same, and that is because you specified scales ="free"
you can specify scales = "free_x" to only allow x to be free (in this case it is the same as pred has the same range by definition)
p <- ggplot(plot, aes(x = pred, y = value)) + geom_point(size = 2.5) + theme_bw()
p <- p + facet_wrap(~variable, scales = "free_x")
worked for me, see the picture
I think you were making it too difficult - I do seem to remember one time defining the limits based on a formula with min and max and if faceted I think it used only those values, but I can't find the code
bundle exec rake db:rollback
rails destroy model <model_name>
When you generate a model, it creates a database migration. If you run 'destroy' on that model, it will delete the migration file, but not the database table. So before run
bundle exec rake db:rollback
None of the above worked for me. Somehow the box had the wrong public key added in the vagrant user authorised_keys file.
If you can still ssh on the box with the vagrant password (password is vagrant), i.e.
ssh vagrant@localhost -p 2222
then copy the public key content from https://raw.githubusercontent.com/mitchellh/vagrant/master/keys/vagrant.pub to the authorised_keys file with the following command
echo "ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAQEA6NF8iallvQVp22WDkTkyrtvp9eWW6A8YVr+kz4TjGYe7gHzIw+niNltGEFHzD8+v1I2YJ6oXevct1YeS0o9HZyN1Q9qgCgzUFtdOKLv6IedplqoPkcmF0aYet2PkEDo3MlTBckFXPITAMzF8dJSIFo9D8HfdOV0IAdx4O7PtixWKn5y2hMNG0zQPyUecp4pzC6kivAIhyfHilFR61RGL+GPXQ2MWZWFYbAGjyiYJnAmCP3NOTd0jMZEnDkbUvxhMmBYSdETk1rRgm+R4LOzFUGaHqHDLKLX+FIPKcF96hrucXzcWyLbIbEgE98OHlnVYCzRdK8jlqm8tehUc9c9WhQ== vagrant insecure public key" > .ssh/authorized_keys
When done exit the VM and try vagrant ssh again. It should work now.
This thread is ancient, but I wasn't happy with any of the given answers, and ended up writing my own. I'm sharing it now:
We start with:
Sub ResetWSFilters(ws as worksheet)
If ws.FilterMode Then
ws.ShowAllData
Else
End If
'This gets rid of "normal" filters - but tables will remain filtered
For Each listObj In ws.ListObjects
If listObj.ShowHeaders Then
listObj.AutoFilter.ShowAllData
listObj.Sort.SortFields.Clear
End If
Next listObj
'And this gets rid of table filters
End Sub
We can feed a specific worksheet to this macro which will unfilter just that one worksheet. Useful if you need to make sure just one worksheet is clear. However, I usually want to do the entire workbook
Sub ResetAllWBFilters(wb as workbook)
Dim ws As Worksheet
Dim wb As Workbook
Dim listObj As ListObject
For Each ws In wb.Worksheets
If ws.FilterMode Then
ws.ShowAllData
Else
End If
'This removes "normal" filters in the workbook - however, it doesn't remove table filters
For Each listObj In ws.ListObjects
If listObj.ShowHeaders Then
listObj.AutoFilter.ShowAllData
listObj.Sort.SortFields.Clear
End If
Next listObj
Next
'And this removes table filters. You need both aspects to make it work.
End Sub
You can use this, by, for example, opening a workbook you need to deal with and resetting their filters before doing anything with it:
Sub ExampleOpen()
Set TestingWorkBook = Workbooks.Open("C:\Intel\......") 'The .open is assuming you need to open the workbook in question - different procedure if it's already open
Call ResetAllWBFilters(TestingWorkBook)
End Sub
The one I use the most: Resetting all filters in the workbook that the module is stored in:
Sub ResetFilters()
Dim ws As Worksheet
Dim wb As Workbook
Dim listObj As ListObject
Set wb = ThisWorkbook
'Set wb = ActiveWorkbook
'This is if you place the macro in your personal wb to be able to reset the filters on any wb you're currently working on. Remove the set wb = thisworkbook if that's what you need
For Each ws In wb.Worksheets
If ws.FilterMode Then
ws.ShowAllData
Else
End If
'This removes "normal" filters in the workbook - however, it doesn't remove table filters
For Each listObj In ws.ListObjects
If listObj.ShowHeaders Then
listObj.AutoFilter.ShowAllData
listObj.Sort.SortFields.Clear
End If
Next listObj
Next
'And this removes table filters. You need both aspects to make it work.
End Sub
Hmm..I did this right now by just downloading Python 3.6.5 for Windows at https://www.python.org/downloads/release/python-365/ and made sure that the launcher would be installed. Then, I followed the instructions for using python 2 and python 3. Restart the command prompt and then use py -2.7
to use Python 2 and py
or py -3.6
to use Python 3. You can also use pip2
for Python 2's pip
and pip
for Python 3's pip
.
The following does it in a single line:
dataTable.Rows.OfType<DataRow>()
.Select(dr => dr.Field<MyType>(columnName)).ToList();
[Edit: Add a reference to System.Data.DataSetExtensions
to your project if this does not compile]
Another extension method for Linq-to-Objects, without using GroupBy:
/// <summary>
/// Returns the set of items, made distinct by the selected value.
/// </summary>
/// <typeparam name="TSource">The type of the source.</typeparam>
/// <typeparam name="TResult">The type of the result.</typeparam>
/// <param name="source">The source collection.</param>
/// <param name="selector">A function that selects a value to determine unique results.</param>
/// <returns>IEnumerable<TSource>.</returns>
public static IEnumerable<TSource> Distinct<TSource, TResult>(this IEnumerable<TSource> source, Func<TSource, TResult> selector)
{
HashSet<TResult> set = new HashSet<TResult>();
foreach(var item in source)
{
var selectedValue = selector(item);
if (set.Add(selectedValue))
yield return item;
}
}
this is an example of a stored procedure that returns a value and it's execution in c#
CREATE PROCEDURE [dbo].[InsertPerson]
-- Add the parameters for the stored procedure here
@FirstName nvarchar(50),@LastName nvarchar(50),
@PersonID int output
AS
BEGIN
insert [dbo].[Person](LastName,FirstName) Values(@LastName,@FirstName)
set @PersonID=SCOPE_IDENTITY()
END
Go
--------------
// Using stored procedure in adapter to insert new rows and update the identity value.
static void InsertPersonInAdapter(String connectionString, String firstName, String lastName) {
String commandText = "dbo.InsertPerson";
using (SqlConnection conn = new SqlConnection(connectionString)) {
SqlDataAdapter mySchool = new SqlDataAdapter("Select PersonID,FirstName,LastName from [dbo].[Person]", conn);
mySchool.InsertCommand = new SqlCommand(commandText, conn);
mySchool.InsertCommand.CommandType = CommandType.StoredProcedure;
mySchool.InsertCommand.Parameters.Add(
new SqlParameter("@FirstName", SqlDbType.NVarChar, 50, "FirstName"));
mySchool.InsertCommand.Parameters.Add(
new SqlParameter("@LastName", SqlDbType.NVarChar, 50, "LastName"));
SqlParameter personId = mySchool.InsertCommand.Parameters.Add(new SqlParameter("@PersonID", SqlDbType.Int, 0, "PersonID"));
personId.Direction = ParameterDirection.Output;
DataTable persons = new DataTable();
mySchool.Fill(persons);
DataRow newPerson = persons.NewRow();
newPerson["FirstName"] = firstName;
newPerson["LastName"] = lastName;
persons.Rows.Add(newPerson);
mySchool.Update(persons);
Console.WriteLine("Show all persons:");
ShowDataTable(persons, 14);
Use round
, floor
or ceil
methods to round it to the closest integer, along with intval()
which is limited.
http://php.net/manual/en/function.round.php
Awesome, thank you!! Just had to make a few adjustments to get it working with ui-router:
var app = app || angular.module('app', []);
app.directive('head', ['$rootScope', '$compile', '$state', function ($rootScope, $compile, $state) {
return {
restrict: 'E',
link: function ($scope, elem, attrs, ctrls) {
var html = '<link rel="stylesheet" ng-repeat="(routeCtrl, cssUrl) in routeStyles" ng-href="{{cssUrl}}" />';
var el = $compile(html)($scope)
elem.append(el);
$scope.routeStyles = {};
function applyStyles(state, action) {
var sheets = state ? state.css : null;
if (state.parent) {
var parentState = $state.get(state.parent)
applyStyles(parentState, action);
}
if (sheets) {
if (!Array.isArray(sheets)) {
sheets = [sheets];
}
angular.forEach(sheets, function (sheet) {
action(sheet);
});
}
}
$rootScope.$on('$stateChangeStart', function (event, toState, toParams, fromState, fromParams) {
applyStyles(fromState, function(sheet) {
delete $scope.routeStyles[sheet];
console.log('>> remove >> ', sheet);
});
applyStyles(toState, function(sheet) {
$scope.routeStyles[sheet] = sheet;
console.log('>> add >> ', sheet);
});
});
}
}
}]);
You would normally use -stringWithFormat
here.
NSString *myString = [NSString stringWithFormat:@"%@%@%@", @"some text", stringVariable, @"some more text"];
Try pfiles PID
to show all open files for a process.
At the time of writing, setting display:none
on the element didn't work for me. Setting the element's width and height to 0 did not work either. So the element has to be at least 1px
in width for this to work.
The following example worked in Chrome and Firefox:
const str = 'Copy me';
const el = document.createElement("input");
// Does not work:
// dummy.style.display = "none";
el.style.height = '0px';
// Does not work:
// el.style.width = '0px';
el.style.width = '1px';
document.body.appendChild(el);
el.value = str;
el.select();
document.execCommand("copy");
document.body.removeChild(el);
I'd like to add that I can see why the browsers are trying to prevent this hackish approach. It's better to openly show the content you are going copy into the user's browser. But sometimes there are design requirements, we can't change.
I got this error
Connection to bitbucket.org closed by remote host. fatal: Could not read from remote repository. Please make sure you have the correct access rights.
Then i tried
git config --global user.email "[email protected]"
worked without quotes.
I built this small helper method for an android app, may come of use:
/**
* @param originalColor color, without alpha
* @param alpha from 0.0 to 1.0
* @return
*/
public static String addAlpha(String originalColor, double alpha) {
long alphaFixed = Math.round(alpha * 255);
String alphaHex = Long.toHexString(alphaFixed);
if (alphaHex.length() == 1) {
alphaHex = "0" + alphaHex;
}
originalColor = originalColor.replace("#", "#" + alphaHex);
return originalColor;
}
I have searched for a solution that will visualize process steps in my web application. I have found the following excellent write-up by Stephen A Thomas:
Tracking Progress in Pure CSS (Original Link now dead)
In his approach Thomas even gets away with just using CSS - no Javascript! In an essence the following CSS code from his article does the trick for me:
<style>
<!-- Progress with steps -->
ol.progtrckr {
margin: 0;
padding: 0;
list-style-type: none;
}
ol.progtrckr li {
display: inline-block;
text-align: center;
line-height: 3em;
}
ol.progtrckr[data-progtrckr-steps="2"] li { width: 49%; }
ol.progtrckr[data-progtrckr-steps="3"] li { width: 33%; }
ol.progtrckr[data-progtrckr-steps="4"] li { width: 24%; }
ol.progtrckr[data-progtrckr-steps="5"] li { width: 19%; }
ol.progtrckr[data-progtrckr-steps="6"] li { width: 16%; }
ol.progtrckr[data-progtrckr-steps="7"] li { width: 14%; }
ol.progtrckr[data-progtrckr-steps="8"] li { width: 12%; }
ol.progtrckr[data-progtrckr-steps="9"] li { width: 11%; }
ol.progtrckr li.progtrckr-done {
color: black;
border-bottom: 4px solid yellowgreen;
}
ol.progtrckr li.progtrckr-todo {
color: silver;
border-bottom: 4px solid silver;
}
ol.progtrckr li:after {
content: "\00a0\00a0";
}
ol.progtrckr li:before {
position: relative;
bottom: -2.5em;
float: left;
left: 50%;
line-height: 1em;
}
ol.progtrckr li.progtrckr-done:before {
content: "\2713";
color: white;
background-color: yellowgreen;
height: 1.2em;
width: 1.2em;
line-height: 1.2em;
border: none;
border-radius: 1.2em;
}
ol.progtrckr li.progtrckr-todo:before {
content: "\039F";
color: silver;
background-color: white;
font-size: 1.5em;
bottom: -1.6em;
}
</style>
As well as HTML tags from his example (I use Grails GSP pages to generate tags and 'done/todo' class dynamically):
<ol class="progtrckr" data-progtrckr-steps="5">
<li class="progtrckr-done">Order Processing</li>
<li class="progtrckr-done">Pre-Production</li>
<li class="progtrckr-done">In Production</li>
<li class="progtrckr-done">Shipped</li>
<li class="progtrckr-todo">Delivered</li>
</ol>
Hope it helps. Works pretty well for me.
UPDATE: The following (shortened) version also works well.
ol.progtrckr {
display: table;
list-style-type: none;
margin: 0;
padding: 0;
table-layout: fixed;
width: 100%;
}
ol.progtrckr li {
display: table-cell;
text-align: center;
line-height: 3em;
}
... and the rest of the CSS ...
<ol class="progtrckr">
...
</ol>
display: table; table-layout: fixed; width: 100%
ensure that the list items are automatically sized equally as long as the content does not overflow. There is no need to use data-progtrckr-steps
and its associated CSS.
Generate the object files with gcc, then use ar
to bundle them into a static library.
some sources prefere to use .env.development
and .env.production
but that's not obligatory.
it seems that if your environment variable does not start like that so you will have problems
to include your environment variable just put on your code process.env.REACT_APP_VARIABLE
You don't have to install any external dependency
As an aside, apart from the answer by mipadi (which should work by the way), you should know that doing:
git branch -D master
git checkout master
also does exactly what you want without having to redownload everything
(your quote paraphrased). That is because your local repo contains a copy of the remote repo (and that copy is not the same as your local directory, it is not even the same as your checked out branch).
Wiping out a branch is perfectly safe and reconstructing that branch is very fast and involves no network traffic. Remember, git is primarily a local repo by design. Even remote branches have a copy on the local. There's only a bit of metadata that tells git that a specific local copy is actually a remote branch. In git, all files are on your hard disk all the time.
If you don't have any branches other than master, you should:
git checkout -b 'temp'
git branch -D master
git checkout master
git branch -D temp
jdk is necessary to compile to code and convert java code to byte codes while jre is necessary for executing the byte codes.
It's trying to run it as a shell script, which interprets your <?php
token as bash, which is a syntax error. Just use include()
or one of its friends:
For example, in a.php
put:
<?php
print "one";
include 'b.php';
print "three";
?>
In b.php
put:
<?php
print "two";
?>
Prints:
eric@dev ~ $ php a.php
onetwothree
I have had the same problem. I am using windows 7 and this should also work for windows 8. The services responsible for the TNS listener and database were stopped when I looked in the Task Manager.
1: Hit Ctrl-Alt-Del and select "Start Task Manager".
From there go to the "Services" tab.
There are 5 services that need to be running for the database to be accessed correctly.
In the list below "databasename" is the database name you assigned during creation without the quotes.
I am also using database 11g, if you are using another type those fields would be different below. the * after home is the home install, if you have more than 1 database there would be home1, and home2
These are the 5 services
If any of these services are stopped right click on them and start them. After they have all started go back into SQL developer and re-try the connection and it should work.
you need to store the token while creating for 1st registration. When you retrieve data from login table you need to differentiate entered date with current date if it is more than 1 day (24 hours) you need to display message like your token is expired.
To generate key refer here
I wanted to add a new way of doing this that I just recently ran into. Even though form validation doesn't run when you submit the form using the submit()
method, there's nothing stopping you from clicking a submit button programmatically. Even if it's hidden.
Having a form:
<form>
<input type="text" name="title" required />
<button style="display: none;" type="submit" id="submit-button">Not Shown</button>
<button type="button" onclick="doFancyStuff()">Submit</button>
</form>
This will trigger form validation:
function doFancyStuff() {
$("#submit-button").click();
}
Or without jQuery
function doFancyStuff() {
document.getElementById("submit-button").click();
}
In my case, I do a bunch of validation and calculations when the fake submit button is pressed, if my manual validation fails, then I know I can programmatically click the hidden submit button and display form validation.
Here's a VERY simple jsfiddle showing the concept:
This doesn't say how to "fix" the problem - that's already been done in other answers; it exists to draw out the details and applicable documentation references.
When using String.replaceAll
or any of the applicable Matcher replacers, pay attention to the replacement string and how it is handled:
Note that backslashes (
\
) and dollar signs ($
) in the replacement string may cause the results to be different than if it were being treated as a literal replacement string. Dollar signs may be treated as references to captured subsequences as described above, and backslashes are used to escape literal characters in the replacement string.
As pointed out by isnot2bad in a comment, Matcher.quoteReplacement
may be useful here:
Returns a literal replacement String for the specified String. .. The String produced will match the sequence of characters in s treated as a literal sequence. Slashes (
\
) and dollar signs ($
) will be given no special meaning.
For .NET 4.5 and higher, you should use:
var culture = new CultureInfo("en-US");
CultureInfo.DefaultThreadCurrentCulture = culture;
CultureInfo.DefaultThreadCurrentUICulture = culture;
Nicely explained above!
For all those who may suffer like me to get this working in a localized Windows (mine is XP in Slovak), you may try to replace the %
with a !
So:
SET TEXT=Hello World
SET SUBSTRING=!TEXT:~3,5!
ECHO !SUBSTRING!
HTTP is a protocol used for communication, usually used to communicate with internet resources or any application with a web browser client.
REST means that the main concept you are using while designing the application is the Resource: for each action you want to perform you need to define a resource on which you usually do only CRUD operation, which is a simple task. for that its very convenient to use 4 verbs used in HTTP protocol against the 4 CRUD operations (Get for Read, POST is for CREATE, PUT is for UPDATE and DELETE is for DELETE). that's unlike the older concept of RPC (Remote Procedure Call), in which you have a set of actions you want to perform as a result of the user's call. if you think for example on how to describe a facebook like on a post, with RPC you might create services called AddLikeToPost and RemoveLikeFromPost, and manage it along with all your other services related to FB posts, thus you won't need to create special object for Like. with REST you will have a Like object which will be managed separately with Delete and Create functions. It also means it will describe a separate entity in your db. that might look like a small difference, but working like that would usually yield a much simpler code and a much simpler application. with that design, most of the app's logic is obvious from the object's structure (model), unlike RPC with which you would usually have to explicitly add a lot more logic.
designing RESTful application is usually a lot harder because it requires you to describe complicated things in a simple manner. describing all functionalities using only CRUD functions is tricky, but after doing that your life would be a lot simpler and you will find that you will write a lot shorter methods.
One more restraint REST architecture present is not to use session context when communicating with client (stateless), meaning all the information needs to understand who is the client and what he wants is passed with the web message. each call to a function is self descriptive, there is no previous conversation with the client which can be referenced in the message. therefor a client could not tell you "give me the next page" since you don't have a session to store what is the previous page and what kind of page you want, the client would have to say "my name is yuval, get me page 2 of a specific post in a specific forum". that means a bit more data would have to transfer in the communication, but think of the difference between finding a bug reported from the "get me next page" function in oppose to "get me page 2 of question id 2190836 in stack overflow".
Of course there is a lot more to it, but to my opinion that's the main concepts in a teaspoon.
That is working for me. Could be a browser issue as mentioned, or maybe jQuery isn't registered properly, or perhaps the real issue is more complicated (that you made a simpler version to ask this). PS - did have to click out of the text box to make it fire.
To completely remove the ul
default style:
list-style-type: none;
margin: 0;
margin-block-start: 0;
margin-block-end: 0;
margin-inline-start: 0;
margin-inline-end: 0;
padding-inline-start: 0;
Here are some tidyverse
and custom function options that might work depending on your needs:
library(tidyverse)
# custom function to generate, filter, and mutate the data:
combine_dfs <- function(i){
data_frame(x = rnorm(5), y = runif(5)) %>%
filter(x < y) %>%
mutate(x_plus_y = x + y) %>%
mutate(i = i)
}
df <- 1:5 %>% map_df(~combine_dfs(.))
df <- map_df(1:5, ~combine_dfs(.)) # both give the same results
> df %>% head()
# A tibble: 6 x 4
x y x_plus_y i
<dbl> <dbl> <dbl> <int>
1 -0.973 0.673 -0.300 1
2 -0.553 0.0463 -0.507 1
3 0.250 0.716 0.967 2
4 -0.745 0.0640 -0.681 2
5 -0.736 0.228 -0.508 2
6 -0.365 0.496 0.131 3
You could do something similar if you had a directory of files that needed to be combined:
dir_path <- '/path/to/data/test_directory/'
list.files(dir_path)
combine_files <- function(path, file){
read_csv(paste0(path, file)) %>%
filter(a < b) %>%
mutate(a_plus_b = a + b) %>%
mutate(file_name = file)
}
df <- list.files(dir_path, '\\.csv$') %>%
map_df(~combine_files(dir_path, .))
# or if you have Excel files, using the readxl package:
combine_xl_files <- function(path, file){
readxl::read_xlsx(paste0(path, file)) %>%
filter(a < b) %>%
mutate(a_plus_b = a + b) %>%
mutate(file_name = file)
}
df <- list.files(dir_path, '\\.xlsx$') %>%
map_df(~combine_xl_files(dir_path, .))
I used to use curly brackets for "if, else" conditions. However, I found "if(xxx): endif;" is more semantic if the code is heavily wrapped and easier to read in any editors.
Of course, lots editors are capable of recognise and highlight chunks of code when curly brackets are selected. Some also do well on "if(xxx): endif" pair (eg, NetBeans)
Personally, I would recommend "if(xxx): endif", but for small condition check (eg, only one line of code), there are not much differences.
You can use Microsoft Office Web Apps to embed PowerPoint and Excel Files. See Say more in your blog with embedded PowerPoint and Excel files.
Considering filter:expression is a Microsoft extension to CSS, so it will only work in Internet Explorer. If you want to grey it out, I would recommend that you set it's opacity to 50% using a bit of javascript.
http://lyxus.net/mv would be a good place to start, because it discusses an opacity script that works with Firefox, Safari, KHTML, Internet Explorer and CSS3 capable browsers.
You might also want to give it a grey border.
I don't think converting to a tuple is the right answer. You need go and look at where you are calling the function and make sure that c
is a list of list of strings, or whatever you designed this function to work with
For example you might get this error if you passed [c]
to the function instead of c
If the variable is entered like a string (e.g. '2010'
):
if variable and variable.isdigit():
return variable #or whatever you want to do with it.
else:
return "Error" #or whatever you want to do with it.
Before using this I worked it out with try/except
and checking for (int(variable))
, but it was longer code. I wonder if there's any difference in use of resources or speed.
Take a look at this forum http://htmlcoderhelper.com/why-is-using-a-wild-card-with-a-java-import-statement-bad/. Theres a discussion on how using wildcards can lead to conflicts if you add new classes to the packages and if there are two classes with the same name in different packages where only one of them will be imported.
List<Integer> i = new ArrayList<Integer>(Arrays.asList(0,1,2,3,4,5,6,7,8,9,10));
List<Integer> j = new ArrayList<Integer>();
You need to specify the type for array list or the compiler will give that warning because it cannot identify that you are using the list in a type safe way.
Reflector and the File Disassembler add-in from Denis Bauer. It actually produces source projects from assemblies, where Reflector on its own only displays the disassembled source.
ADDED: My latest favourite is JetBrains' dotPeek.
Other posters gave some examples for situations in which you'd use daemon threads. My recommendation, however, is never to use them.
It's not because they're not useful, but because there are some bad side effects you can experience if you use them. Daemon threads can still execute after the Python runtime starts tearing down things in the main thread, causing some pretty bizarre exceptions.
More info here:
https://joeshaw.org/python-daemon-threads-considered-harmful/
https://mail.python.org/pipermail/python-list/2005-February/343697.html
Strictly speaking you never need them, it just makes implementation easier in some cases.
Set your positional arguments with nargs, and check if positional args are empty.
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('file', nargs='?')
args = parser.parse_args()
if not args.file:
parser.print_help()
Reference Python nargs
This is a very old thread but it is sure to be noticed. Hence the note that the solutions offered are no longer up to date and that modern Javascript is much better.
<script>
document.getElementById(id of the form).addEventListener(
"submit",
function(event)
{
if(validData() === false)
{
event.preventDefault();
}
},
false
);
The form receives an event handler that monitors the submit. If the there called function validData (not shown here) returns a FALSE, calling the method PreventDefault, which suppresses the submit of the form and the browser returns to the input. Otherwise the form will be sent as usual.
P.S. This also works with the attribute onsubmit. Then the anonymus function function(event){...} must in the attribute onsubmit of the form. This is not really modern and you can only work with one event handler for submit. But you don't have to create an extra javascript. In addition, it can be specified directly in the source code as an attribute of the form and there is no need to wait until the form is integrated in the DOM.
C++ gives you three ways to pass an object: by pointer, by reference, and by value. Java limits you with the latter one (the only exception is primitive types like int, boolean etc). If you want to use C++ not just like a weird toy, then you'd better get to know the difference between these three ways.
Java pretends that there is no such problem as 'who and when should destroy this?'. The answer is: The Garbage Collector, Great and Awful. Nevertheless, it can't provide 100% protection against memory leaks (yes, java can leak memory). Actually, GC gives you a false sense of safety. The bigger your SUV, the longer your way to the evacuator.
C++ leaves you face-to-face with object's lifecycle management. Well, there are means to deal with that (smart pointers family, QObject in Qt and so on), but none of them can be used in 'fire and forget' manner like GC: you should always keep in mind memory handling. Not only should you care about destroying an object, you also have to avoid destroying the same object more than once.
Not scared yet? Ok: cyclic references - handle them yourself, human. And remember: kill each object precisely once, we C++ runtimes don't like those who mess with corpses, leave dead ones alone.
So, back to your question.
When you pass your object around by value, not by pointer or by reference, you copy the object (the whole object, whether it's a couple of bytes or a huge database dump - you're smart enough to care to avoid latter, aren't you?) every time you do '='. And to access the object's members, you use '.' (dot).
When you pass your object by pointer, you copy just a few bytes (4 on 32-bit systems, 8 on 64-bit ones), namely - the address of this object. And to show this to everyone, you use this fancy '->' operator when you access the members. Or you can use the combination of '*' and '.'.
When you use references, then you get the pointer that pretends to be a value. It's a pointer, but you access the members through '.'.
And, to blow your mind one more time: when you declare several variables separated by commas, then (watch the hands):
Example:
struct MyStruct
{
int* someIntPointer, someInt; //here comes the surprise
MyStruct *somePointer;
MyStruct &someReference;
};
MyStruct s1; //we allocated an object on stack, not in heap
s1.someInt = 1; //someInt is of type 'int', not 'int*' - value/pointer modifier is individual
s1.someIntPointer = &s1.someInt;
*s1.someIntPointer = 2; //now s1.someInt has value '2'
s1.somePointer = &s1;
s1.someReference = s1; //note there is no '&' operator: reference tries to look like value
s1.somePointer->someInt = 3; //now s1.someInt has value '3'
*(s1.somePointer).someInt = 3; //same as above line
*s1.somePointer->someIntPointer = 4; //now s1.someInt has value '4'
s1.someReference.someInt = 5; //now s1.someInt has value '5'
//although someReference is not value, it's members are accessed through '.'
MyStruct s2 = s1; //'NO WAY' the compiler will say. Go define your '=' operator and come back.
//OK, assume we have '=' defined in MyStruct
s2.someInt = 0; //s2.someInt == 0, but s1.someInt is still 5 - it's two completely different objects, not the references to the same one
MockMultipartFile exists for this purpose. As in your snippet if the file path is known, the below code works for me.
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import org.springframework.mock.web.MockMultipartFile;
Path path = Paths.get("/path/to/the/file.txt");
String name = "file.txt";
String originalFileName = "file.txt";
String contentType = "text/plain";
byte[] content = null;
try {
content = Files.readAllBytes(path);
} catch (final IOException e) {
}
MultipartFile result = new MockMultipartFile(name,
originalFileName, contentType, content);
You can examine the response object and verify that it contains the expected value:
@expected = {
:flashcard => @flashcard,
:lesson => @lesson,
:success => true
}.to_json
get :action # replace with action name / params as necessary
response.body.should == @expected
EDIT
Changing this to a post
makes it a bit trickier. Here's a way to handle it:
it "responds with JSON" do
my_model = stub_model(MyModel,:save=>true)
MyModel.stub(:new).with({'these' => 'params'}) { my_model }
post :create, :my_model => {'these' => 'params'}, :format => :json
response.body.should == my_model.to_json
end
Note that mock_model
will not respond to to_json
, so either stub_model
or a real model instance is needed.
Annotate your method in controller with @ResponseBody
:
@RequestMapping(value="/controller", method=GET)
@ResponseBody
public String foo() {
return "Response!";
}
From: 15.3.2.6 Mapping the response body with the @ResponseBody
annotation:
The
@ResponseBody
annotation [...] can be put on a method and indicates that the return type should be written straight to the HTTP response body (and not placed in a Model, or interpreted as a view name).
Made a couple of additions to the above answers so that you get returned a type instead of string value.
I figured that this is primarily going to be used for UI adjustments so I didn't think it relevant to include all the sub models i.e. iPhone 5s but this could be easily extended by adding in model tests to the isDevice Array
Tested working in Swift 3.1 Xcode 8.3.2 with physical and simulator devices
Implementation:
UIDevice.whichDevice()
public enum SVNDevice {
case isiPhone4, isIphone5, isIphone6or7, isIphone6por7p, isIphone, isIpad, isIpadPro
}
extension UIDevice {
class func whichDevice() -> SVNDevice? {
let isDevice = { (comparision: Array<(Bool, SVNDevice)>) -> SVNDevice? in
var device: SVNDevice?
comparision.forEach({
device = $0.0 ? $0.1 : device
})
return device
}
return isDevice([
(UIDevice.current.userInterfaceIdiom == .phone && ScreenSize.SCREEN_MAX_LENGTH < 568.0, SVNDevice.isiPhone4),
(UIDevice.current.userInterfaceIdiom == .phone && ScreenSize.SCREEN_MAX_LENGTH == 568.0, SVNDevice.isIphone5),
(UIDevice.current.userInterfaceIdiom == .phone && ScreenSize.SCREEN_MAX_LENGTH == 667.0, SVNDevice.isIphone6or7),
(UIDevice.current.userInterfaceIdiom == .phone && ScreenSize.SCREEN_MAX_LENGTH == 736.0, SVNDevice.isIphone6por7p),
(UIDevice.current.userInterfaceIdiom == .pad && ScreenSize.SCREEN_MAX_LENGTH == 1024.0, SVNDevice.isIpad),
(UIDevice.current.userInterfaceIdiom == .pad && ScreenSize.SCREEN_MAX_LENGTH == 1366.0, SVNDevice.isIpadPro)])
}
}
private struct ScreenSize {
static let SCREEN_WIDTH = UIScreen.main.bounds.size.width
static let SCREEN_HEIGHT = UIScreen.main.bounds.size.height
static let SCREEN_MAX_LENGTH = max(ScreenSize.SCREEN_WIDTH, ScreenSize.SCREEN_HEIGHT)
static let SCREEN_MIN_LENGTH = min(ScreenSize.SCREEN_WIDTH, ScreenSize.SCREEN_HEIGHT)
}
I've created a framework called SVNBootstaper which includes this and some other helper protocols, it's public and available through Carthage.
If you are using Authentication, I recommend adding the following in web.config file.
In my case, users are redirected to the login page upon timing out:
<authentication mode="Forms">
<forms defaultUrl="Login.aspx" timeout="120"/>
</authentication>
A subtle alternative to MaxNoe's answer where you aren't explicitly setting the ticks but instead setting the cadence.
import matplotlib.pyplot as plt
from matplotlib.ticker import (AutoMinorLocator, MultipleLocator)
fig, ax = plt.subplots(figsize=(10, 8))
# Set axis ranges; by default this will put major ticks every 25.
ax.set_xlim(0, 200)
ax.set_ylim(0, 200)
# Change major ticks to show every 20.
ax.xaxis.set_major_locator(MultipleLocator(20))
ax.yaxis.set_major_locator(MultipleLocator(20))
# Change minor ticks to show every 5. (20/4 = 5)
ax.xaxis.set_minor_locator(AutoMinorLocator(4))
ax.yaxis.set_minor_locator(AutoMinorLocator(4))
# Turn grid on for both major and minor ticks and style minor slightly
# differently.
ax.grid(which='major', color='#CCCCCC', linestyle='--')
ax.grid(which='minor', color='#CCCCCC', linestyle=':')
you can simply use onBackPressed();
or if you are using fragment you can use getActivity().onBackPressed()
You can do it this way:
xml.Descendants().SingleOrDefault(p => p.Name.LocalName == "Name of the node to find")
where xml is a XDocument.
Be aware that the property Name returns an object that has a LocalName and a Namespace. That's why you have to use Name.LocalName if you want to compare by name.
Just wrap in Arrow function where you requiring the files
Create a custom Router
with its own browserHistory
:
import React from 'react';
import { Router } from 'react-router-dom';
import { createBrowserHistory } from 'history';
export const history = createBrowserHistory();
const ExtBrowserRouter = ({children}) => (
<Router history={history} >
{ children }
</Router>
);
export default ExtBrowserRouter
Next, on your Root where you define your Router
, use the following:
import React from 'react';
import { /*BrowserRouter,*/ Route, Switch, Redirect } from 'react-router-dom';
//Use 'ExtBrowserRouter' instead of 'BrowserRouter'
import ExtBrowserRouter from './ExtBrowserRouter';
...
export default class Root extends React.Component {
render() {
return (
<Provider store={store}>
<ExtBrowserRouter>
<Switch>
...
<Route path="/login" component={Login} />
...
</Switch>
</ExtBrowserRouter>
</Provider>
)
}
}
Finally, import history
where you need it and use it:
import { history } from '../routers/ExtBrowserRouter';
...
export function logout(){
clearTokens();
history.push('/login'); //WORKS AS EXPECTED!
return Promise.reject('Refresh token has expired');
}
Did you try -v
(or --verbose
) option for git commit
? It adds the diff of the commit in the message editor.
Here is a good example -
ul li{
list-style-type: disc;
list-style-position: inside;
padding: 10px 0 10px 20px;
text-indent: -1em;
}
Working Demo: http://jsfiddle.net/d9VNk/
Here's an alternative solution.
If you're doing a lot of changes to the DOM (add/removing elements and classes), there could be several things that need to be "reset." Rather than clearing each element when the modal closes, you could reset the entire modal everytime it's reopened.
Sample code:
(function(){
var template = null
$('.modal').on('show.bs.modal', function (event) {
if (template == null) {
template = $(this).html()
} else {
$(this).html(template)
}
// other initialization here, if you want to
})
})()
You can still write your initial state in HTML without worrying too much about what will happen to it later. You can write your UI JS code without worrying about having to clean up later. Each time the modal is relaunched it will be reset to the exact same state it was in the first time.
Edit: Here's a version that should handle multiple modals (I haven't tested it)...
(function(){
$('.modal').on('show.bs.modal', function (event) {
if (!$(this).data('template')) {
$(this).data('template', $(this).html())
} else {
$(this).html($this.data('template'))
}
// other initialization here, if you want to
})
})()
On RHEL6.6 only this works (note the use of export
):
/etc/sysconfig/docker
export http_proxy="http://myproxy.example.com:8080"
export https_proxy="http://myproxy.example.com:8080"
NOTE: Both can use the http
protocol.)
Yes, the function is querySelectorAll
(or querySelector
for a single element), which allows you to use CSS selectors to find elements.
document.querySelectorAll('[property]'); // All with attribute named "property"
document.querySelectorAll('[property="value"]'); // All with "property" set to "value" exactly.
(Complete list of attribute selectors on MDN.)
This finds all elements with the attribute property. It would be better to specify a tag name if possible:
document.querySelectorAll('span[property]');
You can work around this if necessary by looping through all the elements on the page to see whether they have the attribute set:
var withProperty = [],
els = document.getElementsByTagName('span'), // or '*' for all types of element
i = 0;
for (i = 0; i < els.length; i++) {
if (els[i].hasAttribute('property')) {
withProperty.push(els[i]);
}
}
Libraries such as jQuery handle this for you; it's probably a good idea to let them do the heavy lifting.
For anyone dealing with ancient browsers, note that querySelectorAll
was introduced to Internet Explorer in v8 (2009) and fully supported in IE9. All modern browsers support it.
I know this is an old question, but someone should have mentioned the compile-time macros in Availability.h
. All of the other methods here are runtime solutions, and will not work in a header file, class category, or ivar definition.
For these situations, use
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_6_0
// iOS 6+ code here
#else
// Pre iOS 6 code here
#endif
h/t this answer
I met this problem on my project too.
This helped me, so hopefuly will help someone else:
adb uninstall "com.domain.yourapp"
Y = y.values[:,0]
Y - formated_train_y
y - train_y
Francis Shanahan,
Why do you call partial postback as "nonsense"? This is the core feature of Ajax and has been utilized very well in Atlas framework and wonderful third party controls like Telerik
I agree to your point regarding the viewstate. But if developers are careful to disable viewstate, this can greatly reduce the size of the HTML which is rendered thus the page becomes light weight.
Only HTML Server controls are renamed in ASP.NET Web Form model and not pure html controls. Whatever it may be, why are you so worried if the renaming is done? I know you want to deal with lot of javascript events on the client side but if you design your web pages smartly, you can definitely get all the id's you want
Even ASP.NET Web Forms meets XHTML Standards and I don't see any bloating. This is not a justification of why we need an MVC pattern
Again, why are you bothered with AXD Javascript? Why does it hurts you? This is not a valid justification again
So far, i am a fan of developing applications using classic ASP.NET Web forms. For eg: If you want to bind a dropdownlist or a gridview, you need a maximum of 30 minutes and not more than 20 lines of code (minimal of course). But in case of MVC, talk to the developers how pain it is.
The biggest downside of MVC is we are going back to the days of ASP. Remember the spaghetti code of mixing up Server code and HTML??? Oh my god, try to read an MVC aspx page mixed with javascript, HTML, JQuery, CSS, Server tags and what not....Any body can answer this question?
If you really want to create an array rather than a list use either
String[] names = ["lucas", "Fred", "Mary"]
or
def names = ["lucas", "Fred", "Mary"].toArray()
Its work for all external devices, But make sure only get external device folder name and then you need to get file from given location using File class.
public static List<String> getExternalMounts() {
final List<String> out = new ArrayList<>();
String reg = "(?i).*vold.*(vfat|ntfs|exfat|fat32|ext3|ext4).*rw.*";
String s = "";
try {
final Process process = new ProcessBuilder().command("mount")
.redirectErrorStream(true).start();
process.waitFor();
final InputStream is = process.getInputStream();
final byte[] buffer = new byte[1024];
while (is.read(buffer) != -1) {
s = s + new String(buffer);
}
is.close();
} catch (final Exception e) {
e.printStackTrace();
}
// parse output
final String[] lines = s.split("\n");
for (String line : lines) {
if (!line.toLowerCase(Locale.US).contains("asec")) {
if (line.matches(reg)) {
String[] parts = line.split(" ");
for (String part : parts) {
if (part.startsWith("/"))
if (!part.toLowerCase(Locale.US).contains("vold"))
out.add(part);
}
}
}
}
return out;
}
Calling:
List<String> list=getExternalMounts();
if(list.size()>0)
{
String[] arr=list.get(0).split("/");
int size=0;
if(arr!=null && arr.length>0) {
size= arr.length - 1;
}
File parentDir=new File("/storage/"+arr[size]);
if(parentDir.listFiles()!=null){
File parent[] = parentDir.listFiles();
for (int i = 0; i < parent.length; i++) {
// get file path as parent[i].getAbsolutePath());
}
}
}
Getting access to external storage
In order to read or write files on the external storage, your app must acquire the READ_EXTERNAL_STORAGE or WRITE_EXTERNAL_STORAGE system permissions. For example:
<manifest ...>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
...
</manifest>
I guess the answer you need is referenced here Python sets are not json serializable
Not all datatypes can be json serialized . I guess pickle module will serve your purpose.
You can achieve this with this simple CSS/HTML:
.image-container {
position: relative;
width: 200px;
height: 300px;
}
.image-container .after {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
display: none;
color: #FFF;
}
.image-container:hover .after {
display: block;
background: rgba(0, 0, 0, .6);
}
HTML
<div class="image-container">
<img src="http://lorempixel.com/300/200" />
<div class="after">This is some content</div>
</div>
UPD: Here is one nice final demo with some extra stylings.
.image-container {_x000D_
position: relative;_x000D_
display: inline-block;_x000D_
}_x000D_
.image-container img {display: block;}_x000D_
.image-container .after {_x000D_
position: absolute;_x000D_
top: 0;_x000D_
left: 0;_x000D_
width: 100%;_x000D_
height: 100%;_x000D_
display: none;_x000D_
color: #FFF;_x000D_
}_x000D_
.image-container:hover .after {_x000D_
display: block;_x000D_
background: rgba(0, 0, 0, .6);_x000D_
}_x000D_
.image-container .after .content {_x000D_
position: absolute;_x000D_
bottom: 0;_x000D_
font-family: Arial;_x000D_
text-align: center;_x000D_
width: 100%;_x000D_
box-sizing: border-box;_x000D_
padding: 5px;_x000D_
}_x000D_
.image-container .after .zoom {_x000D_
color: #DDD;_x000D_
font-size: 48px;_x000D_
position: absolute;_x000D_
top: 50%;_x000D_
left: 50%;_x000D_
margin: -30px 0 0 -19px;_x000D_
height: 50px;_x000D_
width: 45px;_x000D_
cursor: pointer;_x000D_
}_x000D_
.image-container .after .zoom:hover {_x000D_
color: #FFF;_x000D_
}
_x000D_
<link href="//netdna.bootstrapcdn.com/font-awesome/4.0.3/css/font-awesome.min.css" rel="stylesheet"/>_x000D_
_x000D_
<div class="image-container">_x000D_
<img src="http://lorempixel.com/300/180" />_x000D_
<div class="after">_x000D_
<span class="content">This is some content. It can be long and span several lines.</span>_x000D_
<span class="zoom">_x000D_
<i class="fa fa-search"></i>_x000D_
</span>_x000D_
</div>_x000D_
</div>
_x000D_
The previous answers assume that you always have a signed index. Sadly, std::vector
uses size_type
for indexing, and difference_type
for iterator arithmetic, so they don't work together if you have "-Wconversion" and friends enabled. This is another way to answer the question, while being able to handle both signed and unsigned:
To remove:
template<class T, class I, class = typename std::enable_if<std::is_integral<I>::value>::type>
void remove(std::vector<T> &v, I index)
{
const auto &iter = v.cbegin() + gsl::narrow_cast<typename std::vector<T>::difference_type>(index);
v.erase(iter);
}
To take:
template<class T, class I, class = typename std::enable_if<std::is_integral<I>::value>::type>
T take(std::vector<T> &v, I index)
{
const auto &iter = v.cbegin() + gsl::narrow_cast<typename std::vector<T>::difference_type>(index);
auto val = *iter;
v.erase(iter);
return val;
}
Besides syntactical differences, many people also prefer using void function(void)
for pracitical reasons:
If you're using the search function and want to find the implementation of the function, you can search for function(void)
, and it will return the prototype as well as the implementation.
If you omit the void
, you have to search for function()
and will therefore also find all function calls, making it more difficult to find the actual implementation.
UIButton extension with Swift 3+ syntax:
extension UIButton {
func alignImageAndTitleVertically(padding: CGFloat = 6.0) {
let imageSize: CGSize = imageView!.image!.size
titleEdgeInsets = UIEdgeInsetsMake(0.0, -imageSize.width, -(imageSize.height + padding), 0.0)
let labelString = NSString(string: titleLabel!.text!)
let titleSize = labelString.size(attributes: [NSFontAttributeName: titleLabel!.font])
self.imageEdgeInsets = UIEdgeInsetsMake(-(titleSize.height + padding), 0.0, 0.0, -titleSize.width)
let edgeOffset = abs(titleSize.height - imageSize.height) / 2.0;
self.contentEdgeInsets = UIEdgeInsetsMake(edgeOffset, 0.0, edgeOffset, 0.0)
}
}
Original answer: https://stackoverflow.com/a/7199529/3659227
You need to use regular expressions to identify the unwanted characters. For the most easily readable code, you want the str_replace_all
from the stringr
package, though gsub
from base R works just as well.
The exact regular expression depends upon what you are trying to do. You could just remove those specific characters that you gave in the question, but it's much easier to remove all punctuation characters.
x <- "a1~!@#$%^&*(){}_+:\"<>?,./;'[]-=" #or whatever
str_replace_all(x, "[[:punct:]]", " ")
(The base R equivalent is gsub("[[:punct:]]", " ", x)
.)
An alternative is to swap out all non-alphanumeric characters.
str_replace_all(x, "[^[:alnum:]]", " ")
Note that the definition of what constitutes a letter or a number or a punctuatution mark varies slightly depending upon your locale, so you may need to experiment a little to get exactly what you want.
On Windows you need to include the gl.h
header for OpenGL 1.1 support and link against OpenGL32.lib. Both are a part of the Windows SDK. In addition, you might want the following headers which you can get from http://www.opengl.org/registry .
<GL/glext.h>
- OpenGL 1.2 and above compatibility profile and extension interfaces..<GL/glcorearb.h>
- OpenGL core profile and ARB extension interfaces, as described in appendix G.2 of the OpenGL 4.3 Specification. Does not include interfaces found only in the compatibility profile.<GL/glxext.h>
- GLX 1.3 and above API and GLX extension interfaces.<GL/wglext.h>
- WGL extension interfaces.On Linux you need to link against libGL.so, which is usually a symlink to libGL.so.1, which is yet a symlink to the actual library/driver which is a part of your graphics driver. For example, on my system the actual driver library is named libGL.so.256.53, which is the version number of the nvidia driver I use. You also need to include the gl.h
header, which is usually a part of a Mesa or Xorg package. Again, you might need glext.h
and glxext.h
from http://www.opengl.org/registry . glxext.h
holds GLX extensions, the equivalent to wglext.h
on Windows.
If you want to use OpenGL 3.x or OpenGL 4.x functionality without the functionality which were moved into the GL_ARB_compatibility
extension, use the new gl3.h
header from the registry webpage. It replaces gl.h
and also glext.h
(as long as you only need core functionality).
Last but not the least, glaux.h
is not a header associated with OpenGL. I assume you've read the awful NEHE tutorials and just went along with it. Glaux is a horribly outdated Win32 library (1996) for loading uncompressed bitmaps. Use something better, like libPNG, which also supports alpha channels.
The package names in Jackson 2.x got changed to com.fasterxml
1 from org.codehaus
2. So if you just need ObjectMapper, I think Jackson 1.X can satisfy with your needs.
In order to avoid security you can use annotations. Use this annotation on top of configure class:
@EnableWebSecurity
For example:
@EnableWebSecurity
@Configuration
public class AuthFilter{
// configured method
}
UPD 2020: "Open Graph Object Debugger" has been discontinued. Use Sharing Debugger to refresh Facebook cache.
There is some confusion about tons of Facebook Tools and Documentation. So many people probably use the Sharing Debugger tool to check their OpenGraph markup: https://developers.facebook.com/tools/debug/sharing/
But it only retrieves the information about your site from the Facebook cache. This means that after you change the ogp-markup on your site, the Sharing Debugger will still be using the old cached data. Moreover, if there is no cached data on the Facebook server then the Sharing Debugger will show you the error: This URL hasn't been shared on Facebook before.
So, the solution is to use another tool – Open Graph Object Debugger: https://developers.facebook.com/tools/debug/og/object/
It allows you to Fetch new scrape information and refresh the Facebook cache:
Honestly, I don't know how to find this tool exploring the Tools & Support section of developers.facebook.com – I cannot find any links and mentions. I only have this tool in my bookmarks. That's Facebook :)
I also noted that some developers use the name
attribute instead of property
. Many parsers probably will process such tags properly, but according to The Open Graph protocol, we should use property
, not name
:
<meta property="og:url" content="http://www.mywebaddress.com"/>
The last recommendation is to specify full URLs. For example, Facebook complains when you use relative URL in og:image
. So use the full one:
<meta property="og:image" content="http://www.mywebaddress.com/myimage.jpg"/>
For joins, I strongly prefer query-syntax for all the details that are happily hidden (not the least of which are the transparent identifiers involved with the intermediate projections along the way that are apparent in the dot-syntax equivalent). However, you asked regarding Lambdas which I think you have everything you need - you just need to put it all together.
var categorizedProducts = product
.Join(productcategory, p => p.Id, pc => pc.ProdId, (p, pc) => new { p, pc })
.Join(category, ppc => ppc.pc.CatId, c => c.Id, (ppc, c) => new { ppc, c })
.Select(m => new {
ProdId = m.ppc.p.Id, // or m.ppc.pc.ProdId
CatId = m.c.CatId
// other assignments
});
If you need to, you can save the join into a local variable and reuse it later, however lacking other details to the contrary, I see no reason to introduce the local variable.
Also, you could throw the Select
into the last lambda of the second Join
(again, provided there are no other operations that depend on the join results) which would give:
var categorizedProducts = product
.Join(productcategory, p => p.Id, pc => pc.ProdId, (p, pc) => new { p, pc })
.Join(category, ppc => ppc.pc.CatId, c => c.Id, (ppc, c) => new {
ProdId = ppc.p.Id, // or ppc.pc.ProdId
CatId = c.CatId
// other assignments
});
...and making a last attempt to sell you on query syntax, this would look like this:
var categorizedProducts =
from p in product
join pc in productcategory on p.Id equals pc.ProdId
join c in category on pc.CatId equals c.Id
select new {
ProdId = p.Id, // or pc.ProdId
CatId = c.CatId
// other assignments
};
Your hands may be tied on whether query-syntax is available. I know some shops have such mandates - often based on the notion that query-syntax is somewhat more limited than dot-syntax. There are other reasons, like "why should I learn a second syntax if I can do everything and more in dot-syntax?" As this last part shows - there are details that query-syntax hides that can make it well worth embracing with the improvement to readability it brings: all those intermediate projections and identifiers you have to cook-up are happily not front-and-center-stage in the query-syntax version - they are background fluff. Off my soap-box now - anyhow, thanks for the question. :)
For verbose
> 0, fit
method logs:
Note: If regularization mechanisms are used, they are turned on to avoid overfitting.
if validation_data
or validation_split
arguments are not empty, fit
method logs:
Note: Regularization mechanisms are turned off at testing time because we are using all the capabilities of the network.
For example, using verbose
while training the model helps to detect overfitting which occurs if your acc
keeps improving while your val_acc
gets worse.
i have been working on Apachi Axis1.1 and Axis2.0 and JAX-WS but i would suggest you must JAX-WS because it allow you make wsdl in any format , i was making operation as GetInquiry() in Apache Axis2 it did not allow me to Start Operation name in Upper Case , so i find it not good , so i would suggest you must use JAX-WS
Use the to_datetime
function, specifying a format to match your data.
raw_data['Mycol'] = pd.to_datetime(raw_data['Mycol'], format='%d%b%Y:%H:%M:%S.%f')
I used the following for a drawable image with a circular background.
<?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/colorAccent"/>
</shape>
</item>
<item
android:drawable="@drawable/ic_select"
android:bottom="20dp"
android:left="20dp"
android:right="20dp"
android:top="20dp"/>
</layer-list>
Here is what it looks like
Hope that helps someone out.
M-^ is copy Text. "M" in my environment is "Esc" key ! not "Ctrl"; so I use Esc + 6 to copy that.
[nano help] Escape-key sequences are notated with the Meta (M-) symbol and can be entered using either the Esc, Alt, or Meta key depending on your keyboard setup.
Not exactly. But you can create a list of lists:
var ll = new List<List<int>>();
for(int i = 0; i < 10; ++i) {
var l = new List<int>();
ll.Add(l);
}
seq -w
will detect the max input width and normalize the width of the output.
for num in $(seq -w 01 05); do
...
done
At time of writing this didn't work on the newest versions of OSX, so you can either install macports and use its version of seq
, or you can set the format explicitly:
seq -f '%02g' 1 3
01
02
03
But given the ugliness of format specifications for such a simple problem, I prefer the solution Henk and Adrian gave, which just uses Bash. Apple can't screw this up since there's no generic "unix" version of Bash:
echo {01..05}
Or:
for number in {01..05}; do ...; done
Samsung file explorer needs not only custom action (com.sec.android.app.myfiles.PICK_DATA), but also category part (Intent.CATEGORY_DEFAULT) and mime-type should be passed as extra.
Intent intent = new Intent("com.sec.android.app.myfiles.PICK_DATA");
intent.putExtra("CONTENT_TYPE", "*/*");
intent.addCategory(Intent.CATEGORY_DEFAULT);
You can also use this action for opening multiple files: com.sec.android.app.myfiles.PICK_DATA_MULTIPLE Anyway here is my solution which works on Samsung and other devices:
public void openFile(String mimeType) {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType(mimeType);
intent.addCategory(Intent.CATEGORY_OPENABLE);
// special intent for Samsung file manager
Intent sIntent = new Intent("com.sec.android.app.myfiles.PICK_DATA");
// if you want any file type, you can skip next line
sIntent.putExtra("CONTENT_TYPE", mimeType);
sIntent.addCategory(Intent.CATEGORY_DEFAULT);
Intent chooserIntent;
if (getPackageManager().resolveActivity(sIntent, 0) != null){
// it is device with Samsung file manager
chooserIntent = Intent.createChooser(sIntent, "Open file");
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, new Intent[] { intent});
} else {
chooserIntent = Intent.createChooser(intent, "Open file");
}
try {
startActivityForResult(chooserIntent, CHOOSE_FILE_REQUESTCODE);
} catch (android.content.ActivityNotFoundException ex) {
Toast.makeText(getApplicationContext(), "No suitable File Manager was found.", Toast.LENGTH_SHORT).show();
}
}
This solution works well for me, and maybe will be useful for someone else.
I would set up a shortcut, either to CMD or to the thing you want to run, then set the properties of the shortcut to require admin, and then run the shortcut from your batch file. I haven't tested to confirm it will respect the properties, but I think it's more elegant and doesn't require activating the Administrator account.
Also if you do it as a scheduled task (which can be set up from code) there is an option to run it elevated there.
I understand that you want the Widget2 sharing the bottom border with the contents div. Try adding
style="position: relative; bottom: 0px"
to your Widget2 tag. Also try:
style="position: absolute; bottom: 0px"
if you want to snap your widget to the bottom of the screen.
I am a little rusty with CSS, perhaps the correct style is "margin-bottom: 0px" instead "bottom: 0px", give it a try. Also the pull-right class seems to add a "float=right" style to the element, and I am not sure how this behaves with "position: relative" and "position: absolute", I would remove it.
The question didn't clarify what type of session store was being used. Both answers seem to be correct.
For cookie based sessions:
From http://expressjs.com/api.html#cookieSession
req.session = null // Deletes the cookie.
For Redis, etc based sessions:
req.session.destroy // Deletes the session in the database.
You may already find your answer because it was some time ago you asked. But I tried to do something similar when coding ror. I wanted to run "rails server" in a new cmd window so I don't have to open a new cmd and then find my path again.
What I found out was to use the K switch like this:
start cmd /k echo Hello, World!
start before "cmd" will open the application in a new window and "/K" will execute "echo Hello, World!" after the new cmd is up.
You can also use the /C switch for something similar.
start cmd /C pause
This will then execute "pause" but close the window when the command is done. In this case after you pressed a button. I found this useful for "rails server", then when I shutdown my dev server I don't have to close the window after.
Use the following in your batch file:
start cmd.exe /c "more-batch-commands-here"
or
start cmd.exe /k "more-batch-commands-here"
/c Carries out the command specified by string and then terminates
/k Carries out the command specified by string but remains
The /c
and /k
options controls what happens once your command finishes running. With /c
the terminal window will close automatically, leaving your desktop clean. With /k
the terminal window will remain open. It's a good option if you want to run more commands manually afterwards.
Consult the cmd.exe documentation using cmd /?
for more details.
The proper formatting of the command string becomes more complicated when using arguments with spaces. See the examples below. Note the nested double quotes in some examples.
Run a program and pass a filename parameter:
CMD /c write.exe c:\docs\sample.txt
Run a program and pass a filename which contains whitespace:
CMD /c write.exe "c:\sample documents\sample.txt"
Spaces in program path:
CMD /c ""c:\Program Files\Microsoft Office\Office\Winword.exe""
Spaces in program path + parameters:
CMD /c ""c:\Program Files\demo.cmd"" Parameter1 Param2
CMD /k ""c:\batch files\demo.cmd" "Parameter 1 with space" "Parameter2 with space""
Launch demo1 and demo2:
CMD /c ""c:\Program Files\demo1.cmd" & "c:\Program Files\demo2.cmd""
Source: http://ss64.com/nt/cmd.html
The App_Data folder is a folder, which your asp.net worker process has files sytem rights too, but isn't published through the web server.
For example we use it to update a local CSV of a contact us form. If the preferred method of emails fails or any querying of the data source is required, the App_Data files are there.
It's not ideal, but it it's a good fall-back.
To get the keys on a deeper node in an JSON:
echo '{"data": "1", "user": { "name": 2, "phone": 3 } }' | jq '.user | keys[]'
"name"
"phone"
To delete all the files inside the directory as well as its sub-directories, without removing the folders themselves, simply do this:
import os
mypath = "my_folder" #Enter your path here
for root, dirs, files in os.walk(mypath):
for file in files:
os.remove(os.path.join(root, file))
In windows I use a simple command in a batch file and I use a Scheduled Task to keep all the info in only one file. Be sure to choose another path to the result file, or You will have duplicate data.
type PathToOriginalFiles\*.Extension > AnotherPathToResultFile\NameOfTheResultFile.Extension
If you need to join lots of csv files, a good thing to do is to have the header in only one file with a name like 0header.csv, or other name, so that it will allways be the first file in list, and be sure to program all the other csv files to not contain an header.
Hey all this is ridiculously easy...
And the added benefit is that if you don't approve the PR and just leave it in place, the stats (No of commits, files changed and total lines of code) will simply keep up-to-date as you merge changes into main. :) Enjoy.
I am facing problem while making an chat app using socket.io and node.js & React. Also this issue is not spacefic to Firefox browser, i face same issue in Edge & Chrome also.
"Cross-Origin request is blocked and it is used by some other resources..."
Then i download cors in project directory and put it in the server file index.js as below: To download simply type command using node.js :
npm install cors
const cors = require('cors');
app.use(cors());
This will allow CORS to used by different resources in the files and allow cross origin request in the browser.
You can use LIKE
instead of =
. Without any wildcards this will have the same effect.
DECLARE @Village TABLE
(CastleType TEXT)
INSERT INTO @Village
VALUES
(
'foo'
)
SELECT *
FROM @Village
WHERE [CastleType] LIKE 'foo'
text
is deprecated. Changing to varchar(max)
will be easier to work with.
Also how large is the data likely to be? If you are going to be doing equality comparisons you will ideally want to index this column. This isn't possible if you declare the column as anything wider than 900 bytes though you can add a computed checksum
or hash
column that can be used to speed this type of query up.
As per my understanding, this can be done in two ways :
1) You can use Directory Class with Getfiles method and traverse across all files to check our required extension.
Directory.GetFiles("your_folder_path)[i].Contains("*.txt")
2) You can use Path Class with GetExtension Method which takes file path as a parameter and verifies the extension.To get the file path, just have a looping condition that will fetch a single file and return the filepath that can be used for verification.
Path.GetExtension(your_file_path).Equals(".json")
Note : Both the logic has to be inside a looping condition.
You could try a ColorMatrixColorFilter, since your key color is white:
// Assuming "color" is your target color
float r = Color.red(color) / 255f;
float g = Color.green(color) / 255f;
float b = Color.blue(color) / 255f;
ColorMatrix cm = new ColorMatrix(new float[] {
// Change red channel
r, 0, 0, 0, 0,
// Change green channel
0, g, 0, 0, 0,
// Change blue channel
0, 0, b, 0, 0,
// Keep alpha channel
0, 0, 0, 1, 0,
});
ColorMatrixColorFilter cf = new ColorMatrixColorFilter(cm);
myDrawable.setColorFilter(cf);
For checking one date is after another by using isAfter()
method.
moment('2020-01-20').isAfter('2020-01-21'); // false
moment('2020-01-20').isAfter('2020-01-19'); // true
For checking one date is before another by using isBefore()
method.
moment('2020-01-20').isBefore('2020-01-21'); // true
moment('2020-01-20').isBefore('2020-01-19'); // false
For checking one date is same as another by using isSame()
method.
moment('2020-01-20').isSame('2020-01-21'); // false
moment('2020-01-20').isSame('2020-01-20'); // true
If you're planning on building a function in the if statement, I'd also advise the use of in_array. It's a lot cleaner.
If you're attempting to assign values to variables you can use the if/else shorthand:
$variable_to_fill = $some_variable !== 'uk' ? false : true;
payton109’s answer is correct if you’re in the default US-EAST-1 region. If your bucket is in a different region, use a slightly different URL:
https://s3-<region>.amazonaws.com/your.domain.com/some/asset
Where <region>
is the bucket location name. For example, if your bucket is in the us-west-2
(Oregon) region, you can do this:
https://s3-us-west-2.amazonaws.com/your.domain.com/some/asset
Quick and dirty method to determine if Maven is using desired settings.xml would be invalidate its xml and run some safe maven command that requires settings.xml.
If it reads this settings.xml then Maven reports an error: "Error reading settings.xml..."
for me the device selection bar (or whatever it's actually called) in logcat tab doesn't show, to resolve this I had to move logcat to some other position (left/right) and move it back
public List<Control> GetAllChildControls(Control Root, Type FilterType = null)
{
List<Control> AllChilds = new List<Control>();
foreach (Control ctl in Root.Controls) {
if (FilterType != null) {
if (ctl.GetType == FilterType) {
AllChilds.Add(ctl);
}
} else {
AllChilds.Add(ctl);
}
if (ctl.HasChildren) {
GetAllChildControls(ctl, FilterType);
}
}
return AllChilds;
}
In this solution you do not need to take static variable;
Button nextBtn;
private SupportMapFragment mMapFragment;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
if (mRootView != null) {
ViewGroup parent = (ViewGroup) mRootView.getParent();
Utility.log(0,"removeView","mRootView not NULL");
if (parent != null) {
Utility.log(0, "removeView", "view removeViewed");
parent.removeAllViews();
}
}
else {
try {
mRootView = inflater.inflate(R.layout.dummy_fragment_layout_one, container, false);//
} catch (InflateException e) {
/* map is already there, just return view as it is */
e.printStackTrace();
}
}
return mRootView;
}
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
FragmentManager fm = getChildFragmentManager();
SupportMapFragment mapFragment = (SupportMapFragment) fm.findFragmentById(R.id.mapView);
if (mapFragment == null) {
mapFragment = new SupportMapFragment();
FragmentTransaction ft = fm.beginTransaction();
ft.add(R.id.mapView, mapFragment, "mapFragment");
ft.commit();
fm.executePendingTransactions();
}
//mapFragment.getMapAsync(this);
nextBtn = (Button) view.findViewById(R.id.nextBtn);
nextBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Utility.replaceSupportFragment(getActivity(),R.id.dummyFragment,dummyFragment_2.class.getSimpleName(),null,new dummyFragment_2());
}
});
}`
Use the static method Guid.NewGuid()
instead of calling the default constructor.
var responseObject = proxy.CallService(new RequestObject
{
Data = "misc. data",
Guid = Guid.NewGuid()
});
This question seems to be answered, however for completeness, I would add another approach.
You can use a unique ID number generator which is based on Twitter's Snowflake id generator. C# implementation can be found here.
var id64Generator = new Id64Generator();
// ...
public string generateID(string sourceUrl)
{
return string.Format("{0}_{1}", sourceUrl, id64Generator.GenerateId());
}
Note that one of very nice features of that approach is possibility to have multiple generators on independent nodes (probably something useful for a search engine) generating real time, globally unique identifiers.
// node 0
var id64Generator = new Id64Generator(0);
// node 1
var id64Generator = new Id64Generator(1);
// ... node 10
var id64Generator = new Id64Generator(10);
With iOS7 you can simply change tintColor of the textField
Hey i also need 2 different fonts in my app for different widgeds! I use this way:
In my Application class i create an static method:
public static Typeface getTypeface(Context context, String typeface) {
if (mFont == null) {
mFont = Typeface.createFromAsset(context.getAssets(), typeface);
}
return mFont;
}
The String typeface represents the xyz.ttf in the asset folder. (i created an Constants Class) Now you can use this everywhere in your app:
mTextView = (TextView) findViewById(R.id.text_view);
mTextView.setTypeface(MyApplication.getTypeface(this, Constants.TYPEFACE_XY));
The only problem is, you need this for every widget where you want to use the Font! But i think this is the best way.
You can use Regex.Match
if(text.matches("\\d*")&& text.length() > 2){
System.out.println("number");
}
Or you could use onversions like Integer.parseInt(String)
or better Long.parseLong(String)
for bigger numbers
like for example:
private boolean onlyContainsNumbers(String text) {
try {
Long.parseLong(text);
return true;
} catch (NumberFormatException ex) {
return false;
}
}
And then test with:
if (onlyContainsNumbers(text) && text.length() > 2) {
// do Stuff
}
Use the Array.prototype.push
method to append values to the end of an array:
// initialize array
var arr = [
"Hi",
"Hello",
"Bonjour"
];
// append new value to the array
arr.push("Hola");
console.log(arr);
_x000D_
You can use the push()
function to append more than one value to an array in a single call:
// initialize array
var arr = ["Hi", "Hello", "Bonjour", "Hola"];
// append multiple values to the array
arr.push("Salut", "Hey");
// display all values
for (var i = 0; i < arr.length; i++) {
console.log(arr[i]);
}
_x000D_
Update
If you want to add the items of one array to another array, you can use firstArray.concat(secondArray)
:
var arr = [
"apple",
"banana",
"cherry"
];
arr = arr.concat([
"dragonfruit",
"elderberry",
"fig"
]);
console.log(arr);
_x000D_
Update
Just an addition to this answer if you want to prepend any value to the start of an array (i.e. first index) then you can use Array.prototype.unshift
for this purpose.
var arr = [1, 2, 3];
arr.unshift(0);
console.log(arr);
_x000D_
It also supports appending multiple values at once just like push
.
Update
Another way with ES6 syntax is to return a new array with the spread syntax. This leaves the original array unchanged, but returns a new array with new items appended, compliant with the spirit of functional programming.
const arr = [
"Hi",
"Hello",
"Bonjour",
];
const newArr = [
...arr,
"Salut",
];
console.log(newArr);
_x000D_
public static void main(String[] args) {
public String[] name = {"Art", "Dan", "Jen"};
public String[] country = {"Canada", "Germant", "USA"};
// initialize your performance array here too.
//Your constructor takes arrays as an argument so you need to be sure to pass in the arrays and not just objects.
Athlete art = new Athlete(name, country, performance);
}
Normally svn add *
works. But if you get message like svn: warning: W150002:
due to mix off versioned and non-versioned files in working copy. Use this command:
svn add <path to directory> --force
or
svn add * --force
for mac I can tell you that first you have to check your path
by executing this command
which python
or which python3
then you have to configure it in your pycharm.
pycharm-->preferences-->gear button-->add..
click on system interpreter--> then on ...
then you search where your python version is installed
once it is done then you have to configure for your project
click on edit configuration
then choose the python interpreter
You can use aggregate to calculate the means:
means<-aggregate(df,by=list(df$gender),mean)
Group.1 tea coke beer water gender
1 1 87.70171 27.24834 24.27099 37.24007 1
2 2 24.73330 25.27344 25.64657 24.34669 2
Get rid of the Group.1 column
means<-means[,2:length(means)]
Then you have reformat the data to be in long format:
library(reshape2)
means.long<-melt(means,id.vars="gender")
gender variable value
1 1 tea 87.70171
2 2 tea 24.73330
3 1 coke 27.24834
4 2 coke 25.27344
5 1 beer 24.27099
6 2 beer 25.64657
7 1 water 37.24007
8 2 water 24.34669
Finally, you can use ggplot2 to create your plot:
library(ggplot2)
ggplot(means.long,aes(x=variable,y=value,fill=factor(gender)))+
geom_bar(stat="identity",position="dodge")+
scale_fill_discrete(name="Gender",
breaks=c(1, 2),
labels=c("Male", "Female"))+
xlab("Beverage")+ylab("Mean Percentage")
Kotlin:
val selectedIndex = radioButtonGroup?.indexOfChild(
radioButtonGroup?.findViewById(
radioButtonGroup.getCheckedRadioButtonId())
)
private String encodeFileToBase64Binary(File file){
String encodedfile = null;
try {
FileInputStream fileInputStreamReader = new FileInputStream(file);
byte[] bytes = new byte[(int)file.length()];
fileInputStreamReader.read(bytes);
encodedfile = Base64.encodeBase64(bytes).toString();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return encodedfile;
}
Actually, the simplest way to manipulate this is to
And then the URL www.yoursite.com/data will read that index.php file. If you want to take it further, open a subfolder (e.g. "List") in it, put another index.php in that folder and you can have www.yoursite.com/data/list run that PHP file.
This way you can have full control over this, very useful for SEO.
if a device has an SD card, you use:
Environment.getExternalStorageState()
if you don't have an SD card, you use:
Environment.getDataDirectory()
if there is no SD card, you can create your own directory on the device locally.
//if there is no SD card, create new directory objects to make directory on device
if (Environment.getExternalStorageState() == null) {
//create new file directory object
directory = new File(Environment.getDataDirectory()
+ "/RobotiumTestLog/");
photoDirectory = new File(Environment.getDataDirectory()
+ "/Robotium-Screenshots/");
/*
* this checks to see if there are any previous test photo files
* if there are any photos, they are deleted for the sake of
* memory
*/
if (photoDirectory.exists()) {
File[] dirFiles = photoDirectory.listFiles();
if (dirFiles.length != 0) {
for (int ii = 0; ii <= dirFiles.length; ii++) {
dirFiles[ii].delete();
}
}
}
// if no directory exists, create new directory
if (!directory.exists()) {
directory.mkdir();
}
// if phone DOES have sd card
} else if (Environment.getExternalStorageState() != null) {
// search for directory on SD card
directory = new File(Environment.getExternalStorageDirectory()
+ "/RobotiumTestLog/");
photoDirectory = new File(
Environment.getExternalStorageDirectory()
+ "/Robotium-Screenshots/");
if (photoDirectory.exists()) {
File[] dirFiles = photoDirectory.listFiles();
if (dirFiles.length > 0) {
for (int ii = 0; ii < dirFiles.length; ii++) {
dirFiles[ii].delete();
}
dirFiles = null;
}
}
// if no directory exists, create new directory to store test
// results
if (!directory.exists()) {
directory.mkdir();
}
}// end of SD card checking
add permissions on your manifest.xml
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Happy coding..
const express = require('express');_x000D_
let app = express();_x000D_
app.use(express.json());
_x000D_
This app.use(express.json) will now let you read the incoming post JSON object
Since I don't find a simple answer just adding more this will be JSP page. save this content to a jsp file once you run you can see the values of the selected displayed.
Update: save the file as test.jsp and run it on any web/app server
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<%@ page import="java.lang.*" %>
<%@ page import="java.io.*" %>
<% String[] a = request.getParameterValues("multiple");
if(a!=null)
{
for(int i=0;i<a.length;i++){
//out.println(Integer.parseInt(a[i])); //If integer
out.println(a[i]);
}}
%>
<html>
<body>
<form action="test.jsp" method="get">
<select name="multiple" multiple="multiple"><option value="1">1</option><option value="2">2</option><option value="3">3</option></select>
<input type="submit">
</form>
</body>
</html>
In Java 8, you could do:
try (Stream<String> lines = Files.lines (file, StandardCharsets.UTF_8))
{
for (String line : (Iterable<String>) lines::iterator)
{
;
}
}
Some notes: The stream returned by Files.lines
(unlike most streams) needs to be closed. For the reasons mentioned here I avoid using forEach()
. The strange code (Iterable<String>) lines::iterator
casts a Stream to an Iterable.
They are not case sensitive. In fact NodeJS web server explicitly converts them to lower-case, before making them available in the request object.
It's important to note here that all headers are represented in lower-case only, regardless of how the client actually sent them. This simplifies the task of parsing headers for whatever purpose.
Options -Indexes should work to prevent directory listings.
If you are using a .htaccess file make sure you have at least the "allowoverride options" setting in your main apache config file.
It is an extra part to the answer to this question here but I thought it might be useful. As many people mentioned, Visual Studio Code has the OUTLINE part which provides the ability to browse to different function and show them on the side.
I also wanted to add that if you check the follow cursor mark, it highlights that function name in the OUTLINE view, which is very helpful in browsing and seeing which function you are in.
Try Linq:
Result = string.Join("", input.ToCharArray().Where(x=> ((int)x) < 127));
This will filter out all non ascii characters. Now if you want an equivalent, try the following:
Result = string.Join("", System.Text.Encoding.ASCII.GetChars(System.Text.Encoding.ASCII.GetBytes(input.ToCharArray())));
I wrote a set extension methods a while back that work for several different kinds of Enum
s. One in particular works for what you are trying to accomplish and handles Enum
s with the FlagsAttribute
as well as Enum
s with different underlying types.
public static tEnum SetFlags<tEnum>(this Enum e, tEnum flags, bool set, bool typeCheck = true) where tEnum : IComparable
{
if (typeCheck)
{
if (e.GetType() != flags.GetType())
throw new ArgumentException("Argument is not the same type as this instance.", "flags");
}
var flagsUnderlyingType = Enum.GetUnderlyingType(typeof(tEnum));
var firstNum = Convert.ToUInt32(e);
var secondNum = Convert.ToUInt32(flags);
if (set)
firstNum |= secondNum;
else
firstNum &= ~secondNum;
var newValue = (tEnum)Convert.ChangeType(firstNum, flagsUnderlyingType);
if (!typeCheck)
{
var values = Enum.GetValues(typeof(tEnum));
var lastValue = (tEnum)values.GetValue(values.Length - 1);
if (newValue.CompareTo(lastValue) > 0)
return lastValue;
}
return newValue;
}
From there you can add other more specific extension methods.
public static tEnum AddFlags<tEnum>(this Enum e, tEnum flags) where tEnum : IComparable
{
SetFlags(e, flags, true);
}
public static tEnum RemoveFlags<tEnum>(this Enum e, tEnum flags) where tEnum : IComparable
{
SetFlags(e, flags, false);
}
This one will change types of Enum
s like you are trying to do.
public static tEnum ChangeType<tEnum>(this Enum e) where tEnum : IComparable
{
return SetFlags(e, default(tEnum), true, false);
}
Be warned, though, that you CAN convert between any Enum
and any other Enum
using this method, even those that do not have flags. For example:
public enum Turtle
{
None = 0,
Pink,
Green,
Blue,
Black,
Yellow
}
[Flags]
public enum WriteAccess : short
{
None = 0,
Read = 1,
Write = 2,
ReadWrite = 3
}
static void Main(string[] args)
{
WriteAccess access = WriteAccess.ReadWrite;
Turtle turtle = access.ChangeType<Turtle>();
}
The variable turtle
will have a value of Turtle.Blue
.
However, there is safety from undefined Enum
values using this method. For instance:
static void Main(string[] args)
{
Turtle turtle = Turtle.Yellow;
WriteAccess access = turtle.ChangeType<WriteAccess>();
}
In this case, access
will be set to WriteAccess.ReadWrite
, since the WriteAccess
Enum
has a maximum value of 3.
Another side effect of mixing Enum
s with the FlagsAttribute
and those without it is that the conversion process will not result in a 1 to 1 match between their values.
public enum Letters
{
None = 0,
A,
B,
C,
D,
E,
F,
G,
H
}
[Flags]
public enum Flavors
{
None = 0,
Cherry = 1,
Grape = 2,
Orange = 4,
Peach = 8
}
static void Main(string[] args)
{
Flavors flavors = Flavors.Peach;
Letters letters = flavors.ChangeType<Letters>();
}
In this case, letters
will have a value of Letters.H
instead of Letters.D
, since the backing value of Flavors.Peach
is 8. Also, a conversion from Flavors.Cherry | Flavors.Grape
to Letters
would yield Letters.C
, which can seem unintuitive.
As in Swift 3.x for upload image with parameter we can use below alamofire upload method-
static func uploadImageData(inputUrl:String,parameters:[String:Any],imageName: String,imageFile : UIImage,completion:@escaping(_:Any)->Void) {
let imageData = UIImageJPEGRepresentation(imageFile , 0.5)
Alamofire.upload(multipartFormData: { (multipartFormData) in
multipartFormData.append(imageData!, withName: imageName, fileName: "swift_file\(arc4random_uniform(100)).jpeg", mimeType: "image/jpeg")
for key in parameters.keys{
let name = String(key)
if let val = parameters[name!] as? String{
multipartFormData.append(val.data(using: .utf8)!, withName: name!)
}
}
}, to:inputUrl)
{ (result) in
switch result {
case .success(let upload, _, _):
upload.uploadProgress(closure: { (Progress) in
})
upload.responseJSON { response in
if let JSON = response.result.value {
completion(JSON)
}else{
completion(nilValue)
}
}
case .failure(let encodingError):
completion(nilValue)
}
}
}
Note: Additionally if our parameter is array of key-pairs then we can use
var arrayOfKeyPairs = [[String:Any]]()
let json = try? JSONSerialization.data(withJSONObject: arrayOfKeyPairs, options: [.prettyPrinted])
let jsonPresentation = String(data: json!, encoding: .utf8)
Although there is nothing wrong with the other solutions presented, you could simplify and greatly escalate your solutions by using python's excellent library pandas.
Pandas is a library for handling data in Python, preferred by many Data Scientists.
Pandas has a simplified CSV interface to read and parse files, that can be used to return a list of dictionaries, each containing a single line of the file. The keys will be the column names, and the values will be the ones in each cell.
In your case:
import pandas
def create_dictionary(filename):
my_data = pandas.DataFrame.from_csv(filename, sep='\t', index_col=False)
# Here you can delete the dataframe columns you don't want!
del my_data['B']
del my_data['D']
# ...
# Now you transform the DataFrame to a list of dictionaries
list_of_dicts = [item for item in my_data.T.to_dict().values()]
return list_of_dicts
# Usage:
x = create_dictionary("myfile.csv")
From The Java™ Tutorials - Abstract Classes Compared to Interfaces
Which should you use, abstract classes or interfaces?
- Consider using abstract classes if any of these statements apply to your situation:
- You want to share code among several closely related classes.
- You expect that classes that extend your abstract class have many common methods or fields, or require access modifiers other than public (such as protected and private).
- You want to declare non-static or non-final fields. This enables you to define methods that can access and modify the state of the object to which they belong.
- Consider using interfaces if any of these statements apply to your situation:
- You expect that unrelated classes would implement your interface. For example, the interfaces
Comparable
andCloneable
are implemented by many unrelated classes.- You want to specify the behavior of a particular data type, but not concerned about who implements its behavior.
- You want to take advantage of multiple inheritance of type.
An example of an abstract class in the JDK is
AbstractMap
, which is part of the Collections Framework. Its subclasses (which includeHashMap
,TreeMap
, andConcurrentHashMap
) share many methods (includingget
,put
,isEmpty
,containsKey
, andcontainsValue
) thatAbstractMap
defines.
I had a problem slimier to yours I this quick and its the best solution I have found so far.
Shows what the output of the code looks like The borders are just to show the spacing and are not needed.
<div class="center">
<ul class="dots">
<span>
<li></li>
<li></li>
<li></li>
</span>
</ul>
</div>
ul {list-style-type: none;}
ul li{
display: inline-block;
padding: 2px;
border: 2px solid black;
border-radius: 5px;}
.center{
width: 100%;
border: 3px solid black;}
.dots{
padding: 0px;
border: 5px solid red;
text-align: center;}
span{
width: 100%;
border: 5px solid blue;}
You can cut the css down to this to get the same effect:
ul {list-style-type: none;}
ul li{display: inline-block;}
.center{width: 100%;}
.dots{
text-align: center;
padding: 0px;}
span{width: 100%;}
In search of this same solution, I found what I needed under a different question in stackoverflow: Powershell-log-off-remote-session. The below one line will return a list of logged on users.
query user /server:$SERVER
I'm using the latest version of WiX (3.0) and couldn't get the above working. But this did work:
<Product Id="*" UpgradeCode="PUT-GUID-HERE" ... >
<Upgrade Id="PUT-GUID-HERE">
<UpgradeVersion OnlyDetect="no" Property="PREVIOUSFOUND"
Minimum="1.0.0.0" IncludeMinimum="yes"
Maximum="99.0.0.0" IncludeMaximum="no" />
</Upgrade>
Note that PUT-GUID-HERE should be the same as the GUID that you have defined in the UpgradeCode property of the Product.
You can use your IP address to get your 'country', 'city', 'isp' etc...
Just use one of the web-services that provide you with a simple api like http://ip-api.com which provide you a JSON service at http://ip-api.com/json. Simple send a Ajax (or Xhr) request and then parse the JSON to get whatever data you need.
var requestUrl = "http://ip-api.com/json";
$.ajax({
url: requestUrl,
type: 'GET',
success: function(json)
{
console.log("My country is: " + json.country);
},
error: function(err)
{
console.log("Request failed, error= " + err);
}
});
How can I create a copy of an object in Python?
So, if I change values of the fields of the new object, the old object should not be affected by that.
You mean a mutable object then.
In Python 3, lists get a copy
method (in 2, you'd use a slice to make a copy):
>>> a_list = list('abc')
>>> a_copy_of_a_list = a_list.copy()
>>> a_copy_of_a_list is a_list
False
>>> a_copy_of_a_list == a_list
True
Shallow copies are just copies of the outermost container.
list.copy
is a shallow copy:
>>> list_of_dict_of_set = [{'foo': set('abc')}]
>>> lodos_copy = list_of_dict_of_set.copy()
>>> lodos_copy[0]['foo'].pop()
'c'
>>> lodos_copy
[{'foo': {'b', 'a'}}]
>>> list_of_dict_of_set
[{'foo': {'b', 'a'}}]
You don't get a copy of the interior objects. They're the same object - so when they're mutated, the change shows up in both containers.
Deep copies are recursive copies of each interior object.
>>> lodos_deep_copy = copy.deepcopy(list_of_dict_of_set)
>>> lodos_deep_copy[0]['foo'].add('c')
>>> lodos_deep_copy
[{'foo': {'c', 'b', 'a'}}]
>>> list_of_dict_of_set
[{'foo': {'b', 'a'}}]
Changes are not reflected in the original, only in the copy.
Immutable objects do not usually need to be copied. In fact, if you try to, Python will just give you the original object:
>>> a_tuple = tuple('abc')
>>> tuple_copy_attempt = a_tuple.copy()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'tuple' object has no attribute 'copy'
Tuples don't even have a copy method, so let's try it with a slice:
>>> tuple_copy_attempt = a_tuple[:]
But we see it's the same object:
>>> tuple_copy_attempt is a_tuple
True
Similarly for strings:
>>> s = 'abc'
>>> s0 = s[:]
>>> s == s0
True
>>> s is s0
True
and for frozensets, even though they have a copy
method:
>>> a_frozenset = frozenset('abc')
>>> frozenset_copy_attempt = a_frozenset.copy()
>>> frozenset_copy_attempt is a_frozenset
True
Immutable objects should be copied if you need a mutable interior object copied.
>>> tuple_of_list = [],
>>> copy_of_tuple_of_list = tuple_of_list[:]
>>> copy_of_tuple_of_list[0].append('a')
>>> copy_of_tuple_of_list
(['a'],)
>>> tuple_of_list
(['a'],)
>>> deepcopy_of_tuple_of_list = copy.deepcopy(tuple_of_list)
>>> deepcopy_of_tuple_of_list[0].append('b')
>>> deepcopy_of_tuple_of_list
(['a', 'b'],)
>>> tuple_of_list
(['a'],)
As we can see, when the interior object of the copy is mutated, the original does not change.
Custom objects usually store data in a __dict__
attribute or in __slots__
(a tuple-like memory structure.)
To make a copyable object, define __copy__
(for shallow copies) and/or __deepcopy__
(for deep copies).
from copy import copy, deepcopy
class Copyable:
__slots__ = 'a', '__dict__'
def __init__(self, a, b):
self.a, self.b = a, b
def __copy__(self):
return type(self)(self.a, self.b)
def __deepcopy__(self, memo): # memo is a dict of id's to copies
id_self = id(self) # memoization avoids unnecesary recursion
_copy = memo.get(id_self)
if _copy is None:
_copy = type(self)(
deepcopy(self.a, memo),
deepcopy(self.b, memo))
memo[id_self] = _copy
return _copy
Note that deepcopy
keeps a memoization dictionary of id(original)
(or identity numbers) to copies. To enjoy good behavior with recursive data structures, make sure you haven't already made a copy, and if you have, return that.
So let's make an object:
>>> c1 = Copyable(1, [2])
And copy
makes a shallow copy:
>>> c2 = copy(c1)
>>> c1 is c2
False
>>> c2.b.append(3)
>>> c1.b
[2, 3]
And deepcopy
now makes a deep copy:
>>> c3 = deepcopy(c1)
>>> c3.b.append(4)
>>> c1.b
[2, 3]
This is what I normally use, albeit a bit manual:
/* Add a 'temporary' UDDT with the new definition */
exec sp_addtype t_myudt_tmp, 'numeric(18,5)', NULL
/* Build a command to alter all the existing columns - cut and
** paste the output, then run it */
select 'alter table dbo.' + TABLE_NAME +
' alter column ' + COLUMN_NAME + ' t_myudt_tmp'
from INFORMATION_SCHEMA.COLUMNS
where DOMAIN_NAME = 't_myudt'
/* Remove the old UDDT */
exec sp_droptype t_mydut
/* Rename the 'temporary' UDDT to the correct name */
exec sp_rename 't_myudt_tmp', 't_myudt', 'USERDATATYPE'
Documentation for crypto: http://nodejs.org/api/crypto.html
const crypto = require('crypto')
const text = 'I love cupcakes'
const key = 'abcdeg'
crypto.createHmac('sha1', key)
.update(text)
.digest('hex')
Are you meaning?
data2 <- data1[good,]
With
data1[good]
you're selecting columns in a wrong way (using a logical vector of complete rows).
Consider that parameter pollutant
is not used; is it a column name that you want to extract? if so it should be something like
data2 <- data1[good, pollutant]
Furthermore consider that you have to rbind
the data.frame
s inside the for
loop, otherwise you get only the last data.frame (its completed.cases)
And last but not least, i'd prefer generating filenames eg with
id <- 1:322
paste0( directory, "/", gsub(" ", "0", sprintf("%3d",id)), ".csv")
A little modified chunk of ?sprintf
The string fmt
(in our case "%3d"
) contains normal characters, which are passed through to the output string, and also conversion specifications which operate on the arguments provided through ...
. The allowed conversion specifications start with a %
and end with one of the letters in the set aAdifeEgGosxX%
. These letters denote the following types:
d
: integerEg a more general example
sprintf("I am %10d years old", 25)
[1] "I am 25 years old"
^^^^^^^^^^
| |
1 10
Try this simple solution to convert file to base64 string
String base64String = imageFileToByte(file);
public String imageFileToByte(File file){
Bitmap bm = BitmapFactory.decodeFile(file.getAbsolutePath());
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.JPEG, 100, baos); //bm is the bitmap object
byte[] b = baos.toByteArray();
return Base64.encodeToString(b, Base64.DEFAULT);
}
The problem is on this line:
oShell.run "cmd.exe /C copy "S:Claims\Sound.wav" "C:\WINDOWS\Media\Sound.wav"
Your first quote next to "S:Claims" ends the string; you need to escape the quotes around your files with a second quote, like this:
oShell.run "cmd.exe /C copy ""S:\Claims\Sound.wav"" ""C:\WINDOWS\Media\Sound.wav"" "
You also have a typo in S:Claims\Sound.wav
, should be S:\Claims\Sound.wav
.
I also assume the apostrophe before Dim oShell
and after Set oShell = Nothing
are typos as well.
The "play" button is specifically for build and run (or test or profile, etc). The Archive action is intended to build for release and to generate an archive that is suitable for submission to the app store. If you want to skip that, you can choose Product > Build For > Archive to force the release build without actually archiving. To find the built product, expand the Products group in the Project navigator, right-click the product and choose to show in Finder.
That said, you can click and hold the play button for a menu of other build actions (including Build and Archive).
With minor corrections:
function rearrange()
{
var windowHeight;
if (typeof window.innerWidth != 'undefined')
{
windowHeight = window.innerHeight;
}
// IE6 in standards compliant mode (i.e. with a valid doctype as the first
// line in the document)
else if (typeof document.documentElement != 'undefined'
&& typeof document.documentElement.clientWidth != 'undefined'
&& document.documentElement.clientWidth != 0)
{
windowHeight = document.documentElement.clientHeight;
}
// older versions of IE
else
{
windowHeight = document.getElementsByTagName('body')[0].clientHeight;
}
document.getElementById("foobar").style.height = (windowHeight - document.getElementById("foobar").offsetTop - 6)+ "px";
}
Here is some PowerShell that creates a single TypeScript definition file a library that includes multiple *.js
files with modern JavaScript.
First, change all the extensions to .ts
.
Get-ChildItem | foreach { Rename-Item $_ $_.Name.Replace(".js", ".ts") }
Second, use the TypeScript compiler to generate definition files. There will be a bunch of compiler errors, but we can ignore those.
Get-ChildItem | foreach { tsc $_.Name }
Finally, combine all the *.d.ts
files into one index.d.ts
, removing the import
statements and removing the default
from each export statement.
Remove-Item index.d.ts;
Get-ChildItem -Path *.d.ts -Exclude "Index.d.ts" | `
foreach { Get-Content $_ } | `
where { !$_.ToString().StartsWith("import") } | `
foreach { $_.Replace("export default", "export") } | `
foreach { Add-Content index.d.ts $_ }
This ends with a single, usable index.d.ts
file that includes many of the definitions.
For the sake of completeness.
Using Java8
people.sort(Comparator.comparingInt(People::getId));
if you want in descending order
people.sort(Comparator.comparingInt(People::getId).reversed());
In my case, I had to remove the following from the .csproj file:
<Import Project="$(SolutionDir)\.nuget\NuGet.targets" Condition="Exists('$(SolutionDir)\.nuget\NuGet.targets')" />
<Target Name="EnsureNuGetPackageBuildImports" BeforeTargets="PrepareForBuild">
<PropertyGroup>
<ErrorText>This project references NuGet package(s) that are missing on this computer. Enable NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}.</ErrorText>
</PropertyGroup>
<Error Condition="!Exists('$(SolutionDir)\.nuget\NuGet.targets')" Text="$([System.String]::Format('$(ErrorText)', '$(SolutionDir)\.nuget\NuGet.targets'))" />
</Target>
In fact, in this snippet you can see where the error message is coming from.
I was converting from MSBuild-Integrated Package Restore to Automatic Package Restore (http://docs.nuget.org/docs/workflows/migrating-to-automatic-package-restore)
The solution I came up with is fragile; it relies on django's naming convention for foreign keys.
USE information_schema;
tee mysql_output
SELECT * FROM TABLE_CONSTRAINTS WHERE CONSTRAINT_TYPE = 'FOREIGN KEY' AND TABLE_SCHEMA = 'database_name';
notee
Then, in the shell,
grep 'refs_tablename_id' mysql_output
IFrame is just an "internal frame". The reason why it can be considered less secure (than not using any kind of frame at all) is because you can include content that does not originate from your domain.
All this means is that you should trust whatever you include in an iFrame or a regular frame.
Frames and IFrames are equally secure (and insecure if you include content from an untrusted source).
You could try:
tr:hover {
background-color: #000;
}
tr:hover td {
background-color: transparent; /* or #000 */
}
You should be able to use something similar to:
$('#selectElementId').change(
function(){
$(this).closest('form').trigger('submit');
/* or:
$('#formElementId').trigger('submit');
or:
$('#formElementId').submit();
*/
});
you should to delete your the Override onOptionsItemSelected and replate your onCreateOptionsMenu with this code
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_action_bar_finish_order_stop, menu);
menu.getItem(0).setOnMenuItemClickListener(new FinishOrderStopListener(this, getApplication(), selectedChild));
return true;
}
You can use the concept of selector. onFocus removes the hint.
android:hint="Email"
So when TextView
has focus, or has user input (i.e. not empty) the hint will not display.
First of all you should get JdK 8.
if you have Jdk installed.
you should set its path using cmd prompt or system variables.
sometimes it can happen that the path is not set due to which eclipse is unable to get the properties for jdk.
Installing latest ecipse luna can solve your problem.
i have indigo and luna. i can set 1.8 in luna but 1.7 in indigo.Eclipse luna
You can check the eclipse site. it says that the eclipse luna was certainly to associate the properties for jdk 8.
If the list to compare against is large, (ie the manilaListRange range in the example above), it is a smart move to use the match function. It avoids the use of a loop which could slow down the procedure. If you can ensure that the manilaListRange is all upper or lower case then this seems to be the best option to me. It is quick to apply 'UCase' or 'LCase' as you do your match.
If you did not have control over the ManilaListRange then you might have to resort to looping through this range in which case there are many ways to compare 'search', 'Instr', 'replace' etc.
You are dynamically generating those elements so any listener applied on page load wont be available. I have edited your fiddle with the correct solution. Basically jQuery holds the event for later binding by attaching it to the parent Element and propagating it downward to the correct dynamically created element.
$('#musics').on('change', '#want',function(e) {
$(this).closest('.from-group').val(($('#want').is(':checked')) ? "yes" : "no");
var ans=$(this).val();
console.log(($('#want').is(':checked')));
});
Had the same problem for few days. Found a solution at last. The PHP server returned some unseen characters which you could not see in the LOG or in System.out.
So the solution was that i tried to substring my json String one by one and when i came to substring(3) the error went away.
BTW. i used UTF-8 encoding on both sides.
PHP side: header('Content-type=application/json; charset=utf-8');
JAVA side: BufferedReader reader = new BufferedReader(new InputStreamReader(is, "utf-8"), 8);
So try the solution one by one 1,2,3,4...! Hope it helps you guys!
try {
jObj = new JSONObject(json.substring(3));
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data [" + e.getMessage()+"] "+json);
}
Try regexp currency with jQuery (no plugin):
$(document).ready(function(){_x000D_
$('#test').click(function() {_x000D_
TESTCURRENCY = $('#value').val().toString().match(/(?=[\s\d])(?:\s\.|\d+(?:[.]\d+)*)/gmi);_x000D_
if (TESTCURRENCY.length <= 1) {_x000D_
$('#valueshow').val(_x000D_
parseFloat(TESTCURRENCY.toString().match(/^\d+(?:\.\d{0,2})?/))_x000D_
);_x000D_
} else {_x000D_
$('#valueshow').val('Invalid a value!');_x000D_
}_x000D_
});_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>_x000D_
<input type="text" value="12345.67890" id="value">_x000D_
<input type="button" id="test" value="CLICK">_x000D_
<input type="text" value="" id="valueshow">
_x000D_
Edit: New check a value to valid/invalid
A ClusterIP exposes the following:
spec.clusterIp:spec.ports[*].port
You can only access this service while inside the cluster. It is accessible from its spec.clusterIp
port. If a spec.ports[*].targetPort
is set it will route from the port to the targetPort. The CLUSTER-IP you get when calling kubectl get services
is the IP assigned to this service within the cluster internally.
A NodePort exposes the following:
<NodeIP>:spec.ports[*].nodePort
spec.clusterIp:spec.ports[*].port
If you access this service on a nodePort from the node's external IP, it will route the request to spec.clusterIp:spec.ports[*].port
, which will in turn route it to your spec.ports[*].targetPort
, if set. This service can also be accessed in the same way as ClusterIP.
Your NodeIPs are the external IP addresses of the nodes. You cannot access your service from spec.clusterIp:spec.ports[*].nodePort
.
A LoadBalancer exposes the following:
spec.loadBalancerIp:spec.ports[*].port
<NodeIP>:spec.ports[*].nodePort
spec.clusterIp:spec.ports[*].port
You can access this service from your load balancer's IP address, which routes your request to a nodePort, which in turn routes the request to the clusterIP port. You can access this service as you would a NodePort or a ClusterIP service as well.
#!/usr/bin/python
import sys
def check_ip(address):
part=address.split(".")
temp=True
if len(part) != 4:
temp=False
return temp
for p in part:
if not 0<= int(p) <= 255:
temp=False
return temp
else:
temp=True
return temp
if __name__=="__main__":
print check_ip(sys.argv[1])
Save the code with some name say- check_ip.py
and run it as python check_ip.py 192.168.560.25
Note:- Above code fails for the below ip address-
023.65.029.33
Try this CSS to disable resizing
The CSS to disable resizing for all textareas looks like this:
textarea {
resize: none;
}
You could instead just assign it to a single textarea by name (where the textarea HTML is ):
textarea[name=foo] {
resize: none;
}
Or by id (where the textarea HTML is ):
#foo {
resize: none;
}
Taken from: http://www.electrictoolbox.com/disable-textarea-resizing-safari-chrome/
There is the nuclear approach which is in your App.css (or counterpart)
a{
text-decoration: none;
}
which prevents underline for all <a>
tags which is the root cause of this problem
Using FormData is the way to go as indicated by many answers. here is a bit of code that works great for this purpose. I also agree with the comment of nesting ajax blocks to complete complex circumstances. By including e.PreventDefault(); in my experience makes the code more cross browser compatible.
$('#UploadB1').click(function(e){
e.preventDefault();
if (!fileupload.valid()) {
return false;
}
var myformData = new FormData();
myformData.append('file', $('#uploadFile')[0].files[0]);
$("#UpdateMessage5").html("Uploading file ....");
$("#UpdateMessage5").css("background","url(../include/images/loaderIcon.gif) no-repeat right");
myformData.append('mode', 'fileUpload');
myformData.append('myid', $('#myid').val());
myformData.append('type', $('#fileType').val());
//formData.append('myfile', file, file.name);
$.ajax({
url: 'include/fetch.php',
method: 'post',
processData: false,
contentType: false,
cache: false,
data: myformData,
enctype: 'multipart/form-data',
success: function(response){
$("#UpdateMessage5").html(response); //.delay(2000).hide(1);
$("#UpdateMessage5").css("background","");
console.log("file successfully submitted");
},error: function(){
console.log("not okay");
}
});
});
Reference:https://docs.microsoft.com/en-us/sql/t-sql/functions/newid-transact-sql?view=sql-server-2017
-- Creating a table using NEWID for uniqueidentifier data type.
CREATE TABLE cust
(
CustomerID uniqueidentifier NOT NULL
DEFAULT newid(),
Company varchar(30) NOT NULL,
ContactName varchar(60) NOT NULL,
Address varchar(30) NOT NULL,
City varchar(30) NOT NULL,
StateProvince varchar(10) NULL,
PostalCode varchar(10) NOT NULL,
CountryRegion varchar(20) NOT NULL,
Telephone varchar(15) NOT NULL,
Fax varchar(15) NULL
);
GO
-- Inserting 5 rows into cust table.
INSERT cust
(CustomerID, Company, ContactName, Address, City, StateProvince,
PostalCode, CountryRegion, Telephone, Fax)
VALUES
(NEWID(), 'Wartian Herkku', 'Pirkko Koskitalo', 'Torikatu 38', 'Oulu', NULL,
'90110', 'Finland', '981-443655', '981-443655')
,(NEWID(), 'Wellington Importadora', 'Paula Parente', 'Rua do Mercado, 12', 'Resende', 'SP',
'08737-363', 'Brasil', '(14) 555-8122', '')
,(NEWID(), 'Cactus Comidas para Ilevar', 'Patricio Simpson', 'Cerrito 333', 'Buenos Aires', NULL,
'1010', 'Argentina', '(1) 135-5555', '(1) 135-4892')
,(NEWID(), 'Ernst Handel', 'Roland Mendel', 'Kirchgasse 6', 'Graz', NULL,
'8010', 'Austria', '7675-3425', '7675-3426')
,(NEWID(), 'Maison Dewey', 'Catherine Dewey', 'Rue Joseph-Bens 532', 'Bruxelles', NULL,
'B-1180', 'Belgium', '(02) 201 24 67', '(02) 201 24 68');
GO
Try this
If you are deploying your app into the root context (e.g. https://myapp.com/), set the base URL to /:
<head>
<base href="/">
...
</head>
Here is an example ...
select * from tablename where to_char(added_time, 'YYYY-MM-DD') = to_char( now(), 'YYYY-MM-DD' )
added_time is a column name which I converted to char for match
I propose an example to make it more clear, since angular.io/guide/component-styles states:
The shadow-piercing descendant combinator is deprecated and support is being removed from major browsers and tools. As such we plan to drop support in Angular (for all 3 of /deep/, >>> and ::ng-deep). Until then ::ng-deep should be preferred for a broader compatibility with the tools.
On app.component.scss
, import your *.scss
if needed. _colors.scss
has some common color values:
$button_ripple_red: #A41E34;
$button_ripple_white_text: #FFF;
Apply a rule to all components
All the buttons having btn-red
class will be styled.
@import `./theme/sass/_colors`;
// red background and white text
:host /deep/ button.red-btn {
color: $button_ripple_white_text;
background: $button_ripple_red;
}
Apply a rule to a single component
All the buttons having btn-red
class on app-login
component will be styled.
@import `./theme/sass/_colors`;
/deep/ app-login button.red-btn {
color: $button_ripple_white_text;
background: $button_ripple_red;
}
As using the String.substring
and String.lastIndex
in a one-liner is good, there are some issues in terms of being able to cope with certain file paths.
Take for example the following path:
a.b/c
Using the one-liner will result in:
a
That's incorrect.
The result should have been c
, but since the file lacked an extension, but the path had a directory with a .
in the name, the one-liner method was tricked into giving part of the path as the filename, which is not correct.
Need for checks
Inspired by skaffman's answer, I took a look at the FilenameUtils.removeExtension
method of the Apache Commons IO.
In order to recreate its behavior, I wrote a few tests the new method should fulfill, which are the following:
Path Filename -------------- -------- a/b/c c a/b/c.jpg c a/b/c.jpg.jpg c.jpg a.b/c c a.b/c.jpg c a.b/c.jpg.jpg c.jpg c c c.jpg c c.jpg.jpg c.jpg
(And that's all I've checked for -- there probably are other checks that should be in place that I've overlooked.)
The implementation
The following is my implementation for the removeExtension
method:
public static String removeExtension(String s) {
String separator = System.getProperty("file.separator");
String filename;
// Remove the path upto the filename.
int lastSeparatorIndex = s.lastIndexOf(separator);
if (lastSeparatorIndex == -1) {
filename = s;
} else {
filename = s.substring(lastSeparatorIndex + 1);
}
// Remove the extension.
int extensionIndex = filename.lastIndexOf(".");
if (extensionIndex == -1)
return filename;
return filename.substring(0, extensionIndex);
}
Running this removeExtension
method with the above tests yield the results listed above.
The method was tested with the following code. As this was run on Windows, the path separator is a \
which must be escaped with a \
when used as part of a String
literal.
System.out.println(removeExtension("a\\b\\c"));
System.out.println(removeExtension("a\\b\\c.jpg"));
System.out.println(removeExtension("a\\b\\c.jpg.jpg"));
System.out.println(removeExtension("a.b\\c"));
System.out.println(removeExtension("a.b\\c.jpg"));
System.out.println(removeExtension("a.b\\c.jpg.jpg"));
System.out.println(removeExtension("c"));
System.out.println(removeExtension("c.jpg"));
System.out.println(removeExtension("c.jpg.jpg"));
The results were:
c
c
c.jpg
c
c
c.jpg
c
c
c.jpg
The results are the desired results outlined in the test the method should fulfill.
I tried a few of the tricks listed here without any luck. Looks like something was getting cached by my terminal emulator (iTerm2) or session. The issue went away when I ran the command from a fresh terminal tab.
I'm using this since the begin and it always work. =)
System.setProperty("webdriver.chrome.driver", "C:\\pathto\\my\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get("http://www.google.com");