Inside controller inject Request object. So if you want to access request body inside controller method 'foo' do the following:
public function foo(Request $request){
$bodyContent = $request->getContent();
}
~
fixes major and minor numbers. It is used when you're ready to accept bug-fixes in your dependency, but don't want any potentially incompatible changes.
^
fixes the major number only. It is used when you're closely watching your dependencies and are ready to quickly change your code if minor release will be incompatible.
In addition to that, ^
is not supported by old npm versions, and should be used with caution.
So, ^
is a good default, but it's not perfect. I suggest to carefully pick and configure the semver operator that is most useful to you.
i think csrf only works with spring forms
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
change to form:form
tag and see it that works.
You can also get through it by the code below:
file=open(completefilepath,'r',encoding='utf8',errors="ignore")
file.read()
Based on semver, you can use
Hyphen Ranges X.Y.Z - A.B.C
1.2.3-2.3.4
Indicates >=1.2.3 <=2.3.4
X-Ranges
1.2.x
1.X
1.2.*
Tilde Ranges
~1.2.3
~1.2
Indicates allowing patch-level changes or minor version changes.
Caret Ranges ^1.2.3 ^0.2.5 ^0.0.4
Allows changes that do not modify the left-most non-zero digit in the [major, minor, patch] tuple
^1.2.x
(means >=1.2.0 <2.0.0)^0.0.x
(means >=0.0.0 <0.1.0)^0.0
(means >=0.0.0 <0.1.0)The thing on the right of <-
is a formula
object. It is often used to denote a statistical model, where the thing on the left of the ~
is the response and the things on the right of the ~
are the explanatory variables. So in English you'd say something like "Species depends on Sepal Length, Sepal Width, Petal Length and Petal Width".
The myFormula <-
part of that line stores the formula in an object called myFormula
so you can use it in other parts of your R code.
Other common uses of formula objects in R
The lattice
package uses them to specify the variables to plot.
The ggplot2
package uses them to specify panels for plotting.
The dplyr
package uses them for non-standard evaulation.
It is General sibling combinator
and is explained in @Salaman's answer very well.
What I did miss is Adjacent sibling combinator
which is +
and is closely related to ~
.
example would be
.a + .b {
background-color: #ff0000;
}
<ul>
<li class="a">1st</li>
<li class="b">2nd</li>
<li>3rd</li>
<li class="b">4th</li>
<li class="a">5th</li>
</ul>
.b
.a
.a
in HTMLIn example above it will mark 2nd li
but not 4th.
.a + .b {_x000D_
background-color: #ff0000;_x000D_
}
_x000D_
<ul>_x000D_
<li class="a">1st</li>_x000D_
<li class="b">2nd</li>_x000D_
<li>3rd</li>_x000D_
<li class="b">4th</li>_x000D_
<li class="a">5th</li>_x000D_
</ul>
_x000D_
~
is the bitwise complement operator in python which essentially calculates -x - 1
So a table would look like
i ~i
0 -1
1 -2
2 -3
3 -4
4 -5
5 -6
So for i = 0
it would compare s[0]
with s[len(s) - 1]
, for i = 1
, s[1]
with s[len(s) - 2]
.
As for your other question, this can be useful for a range of bitwise hacks.
It hides the intention of the code.
It's two single tilde operators, so it does a bitwise complement (bitwise not) twice. The operations take out each other, so the only remaining effect is the conversion that is done before the first operator is applied, i.e. converting the value to an integer number.
Some use it as a faster alternative to Math.floor
, but the speed difference is not that dramatic, and in most cases it's just micro optimisation. Unless you have a piece of code that really needs to be optimised, you should use code that descibes what it does instead of code that uses a side effect of a non-operation.
With optimisation of the JavaScript engine in browsers, the performance for operators and functions change. With current browsers, using ~~
instead of Math.floor
is somewhat faster in some browsers, and not faster at all in some browsers. If you really need that extra bit of performance, you would need to write different optimised code for each browser.
See: tilde vs floor
A second option to "nevets1219" is to open your CSV file in Notepad++ and do a convertion to ANSI.
Choose in the top menu : Encoding -> Convert to Ansi
Use square brackets instead of quotation marks:
IF [%1] == [] GOTO MyLabel
Parentheses are insecure: only use square brackets.
git status
does not always show the difference between master and origin/master even after a fetch.
If you want the combination git fetch origin && git status
to work, you need to specify the tracking information between the local branch and origin:
# git branch --set-upstream-to=origin/<branch> <branch>
For the master branch:
git branch --set-upstream-to=origin/master master
Simplistically:
~
specifies ancestors^
specifies parentsYou can specify one or more branches when merging. Then a commit has two or more parents and then ^
is useful to indicate parents.
Suppose you are on branch A and you have two more branches: B and C.
On each branch the three last commits are:
If now on branch A you execute the command:
git merge B C
then you are combining three branches together (here your merge commit has three parents)
and
~
indicates the n'th ancestor in the first branch, so
HEAD~
indicates A3HEAD~2
indicates A2HEAD~3
indicates A1^
indicates the n'th parent, so
HEAD^
indicates A3HEAD^2
indicates B3HEAD^3
indicates C3The next use of ~
or ^
next to each other is in the context of the commit designated by previous characters.
Notice 1:
HEAD~3
is always equal to: HEAD~~~
and to: HEAD^^^
(every indicates A1),and generally:
HEAD~n
is always equal to: HEAD~...~
(n times ~
) and to: HEAD^...^
(n times ^
).Notice 2:
HEAD^3
is not the same as HEAD^^^
(the first indicates C3 and the second indicates A1),and generally:
HEAD^1
is the same as HEAD^
,HEAD^n
is always not the same as HEAD^...^
(n times ~
).All the answers are complete. But Wanted to add one thing,
set FirstName=%~1
set LastName=%~2
This line should have worked, you needed a small change.
set "FirstName=%~1"
set "LastName=%~2"
Include the complete assignment within quotes. It will remove quotes without an issue. This is a prefered way of assignment which fixes unwanted issues with quotes in arguments.
This is a destructor. It's called when the object is destroyed (out of life scope or deleted).
To be clear, you have to use ~NameOfTheClass like for the constructor, other names are invalid.
It's possible you're seeing OpenDirectory/ActiveDirectory/LDAP users "automounted" into your home directory.
In *nix, ~
will resolve to your home directory. Likewise ~X
will resolve to 'user X'.
Similar to automount for directories, OpenDirectory/ActiveDirectory/LDAP is used in larger/corporate environments to automount user directories. These users may be actual people or they can be machine accounts created to provide various features.
If you type ~Tab you'll see a list of the users on your machine.
First we have to split the given digit into its binary digits and then reverse it by adding at the last binary digit.After this execution we have to give opposite sign to the previous digit that which we are finding the complent ~2=-3 Explanation: 2s binary form is 00000010 changes to 11111101 this is ones complement ,then complented 00000010+1=00000011 which is the binary form of three and with -sign I.e,-3
Line breaks character for NSString is \r
correct way to use [NSString StringWithFormat:@"%@\r%@",string1,string2];
\r ----> carriage return
Not sure if it's what you mean, but you can do this:
plot(1:10, xaxt = "n", xlab='Some Letters')
axis(1, at=1:10, labels=letters[1:10])
which then gives you the graph:
Stream is just an abstraction (or a wrapper) over a physical
stream of bytes. This physical
stream is called the base stream
. So there is always a base stream over which a stream wrapper is created and thus the wrapper is named after the base stream type ie FileStream
, MemoryStream
etc.
The advantage of the stream wrapper is that you get a unified api to interact with streams of any underlying type usb, file
etc.
Why would you treat data as stream - because data chunks are loaded on-demand, we can inspect/process the data as chunks rather than loading the entire data into memory. This is how most of the programs deal with big files, for eg encrypting an OS image file.
int.from_bytes( bytes, byteorder, *, signed=False )
doesn't work with me I used function from this website, it works well
https://coderwall.com/p/x6xtxq/convert-bytes-to-int-or-int-to-bytes-in-python
def bytes_to_int(bytes):
result = 0
for b in bytes:
result = result * 256 + int(b)
return result
def int_to_bytes(value, length):
result = []
for i in range(0, length):
result.append(value >> (i * 8) & 0xff)
result.reverse()
return result
try
Sub save()
ActiveWorkbook.SaveAS Filename:="C:\-docs\cmat\Desktop\New folder\" & Range("C5").Text & chr(32) & Range("C8").Text &".xls", FileFormat:= _
xlNormal, Password:="", WriteResPassword:="", ReadOnlyRecommended:=False _
, CreateBackup:=False
End Sub
If you want to save the workbook with the macros use the below code
Sub save()
ActiveWorkbook.SaveAs Filename:="C:\Users\" & Environ$("username") & _
"\Desktop\" & Range("C5").Text & Chr(32) & Range("C8").Text & ".xlsm", FileFormat:= _
xlOpenXMLWorkbookMacroEnabled, Password:=vbNullString, WriteResPassword:=vbNullString, _
ReadOnlyRecommended:=False, CreateBackup:=False
End Sub
if you want to save workbook with no macros and no pop-up use this
Sub save()
Application.DisplayAlerts = False
ActiveWorkbook.SaveAs Filename:="C:\Users\" & Environ$("username") & _
"\Desktop\" & Range("C5").Text & Chr(32) & Range("C8").Text & ".xls", _
FileFormat:=xlOpenXMLWorkbook, CreateBackup:=False
Application.DisplayAlerts = True
End Sub
Like Ray Toal mentioned it is as easy as:
Set<String> myConcurrentSet = ConcurrentHashMap.newKeySet();
I had the exact same issue. If you are using a relative path os.path.dirname(path) will only return the relative path. os.path.realpath does the trick:
>>> import os
>>> f = open('file.txt')
>>> os.path.realpath(f.name)
There's now a much simpler solution than when this question was originally asked, five years ago. A CSS Flexbox makes the two column layout originally asked for easy. This is the bare bones equivalent of the table in the original question:
<div style="display: flex">
<div>AAA</div>
<div>BBB</div>
</div>
One of the nice things about a Flexbox is that it lets you easily specify how child elements should shrink and grow to adjust to the container size. I will expand on the above example to make the box the full width of the page, make the left column a minimum of 75px wide, and grow the right column to capture the leftover space. I will also pull the style into its own proper block, assign some background colors so that the columns are apparent, and add legacy Flex support for some older browsers.
<style type="text/css">
.flexbox {
display: -ms-flex;
display: -webkit-flex;
display: flex;
width: 100%;
}
.left {
background: #a0ffa0;
min-width: 75px;
flex-grow: 0;
}
.right {
background: #a0a0ff;
flex-grow: 1;
}
</style>
...
<div class="flexbox">
<div class="left">AAA</div>
<div class="right">BBB</div>
</div>
Flex is relatively new, and so if you're stuck having to support IE 8 and IE 9 you can't use it. However, as of this writing, http://caniuse.com/#feat=flexbox indicates at least partial support by browsers used by 94.04% of the market.
late answer, but use this package to to check. Package Name: data_connection_checker
in you pubspec.yuml file:
dependencies:
data_connection_checker: ^0.3.4
create a file called connection.dart or any name you want. import the package:
import 'package:data_connection_checker/data_connection_checker.dart';
check if there is internet connection or not:
print(await DataConnectionChecker().hasConnection);
We had a website running with a specific identity in the apppool, only after giving that user read access to the folder containing the web.config would it work. We tracked this down after adding the 'everyone' user with read and everything worked fine.
In the current order? I'd say array_slice(). Since it's a built in function it will be faster than looping through the array while keeping track of an incrementing index until N.
You may find it easier to use the is
keyword:
if (mycontrol is TextBox)
Since Date
implements Comparable<Date>
, it is as easy as:
date1.compareTo(date2);
As the Comparable
contract stipulates, it will return a negative integer/zero/positive integer if date1
is considered less than/the same as/greater than date2
respectively (ie, before/same/after in this case).
Note that Date
has also .after()
and .before()
methods which will return booleans instead.
Slightly oversimplified: a lambda function is one that can be passed round to other functions and it's logic accessed.
In C# lambda syntax is often compiled to simple methods in the same way as anonymous delegates, but it can also be broken down and its logic read.
For instance (in C#3):
LinqToSqlContext.Where(
row => row.FieldName > 15 );
LinqToSql can read that function (x > 15) and convert it to the actual SQL to execute using expression trees.
The statement above becomes:
select ... from [tablename]
where [FieldName] > 15 --this line was 'read' from the lambda function
This is different from normal methods or anonymous delegates (which are just compiler magic really) because they cannot be read.
Not all methods in C# that use lambda syntax can be compiled to expression trees (i.e. actual lambda functions). For instance:
LinqToSqlContext.Where(
row => SomeComplexCheck( row.FieldName ) );
Now the expression tree cannot be read - SomeComplexCheck cannot be broken down. The SQL statement will execute without the where, and every row in the data will be put through SomeComplexCheck
.
Lambda functions should not be confused with anonymous methods. For instance:
LinqToSqlContext.Where(
delegate ( DataRow row ) {
return row.FieldName > 15;
} );
This also has an 'inline' function, but this time it's just compiler magic - the C# compiler will split this out to a new instance method with an autogenerated name.
Anonymous methods can't be read, and so the logic can't be translated out as it can for lambda functions.
I use this one:
find . -name ".git" -type d | sed 's/\/.git//' | xargs -P10 -I{} git -C {} pull
Universal: Updates all git repositories that are below current directory.
With the reference of Biswajit Roy: Dynamic Programming firstly plans then Go. and Greedy algorithm uses greedy choice, it firstly Go then continuously Plans.
To comment block with nested comments: substitute inner (block) comments from "--" to "++"
<!-- *********************************************************************
* IMPORTANT: To uncomment section
* sub inner comments "++" -> "--" & remove this comment
*********************************************************************
<head>
<title>My document's title</title> <++! My document's title ++>
<link rel=stylesheet href="mydoc.css" type="text/css">
</head>
<body>
<++! My document's important HTML stuff ++>
...
...
...
</body>
*********************************************************************
* IMPORTANT: To uncomment section
* sub inner comments "++" -> "--" & remove this comment
*********************************************************************
-->
Thus, the outer most comment ignores all "invalid" inner (block) comments.
There is probably another table with a foreign key referencing the primary key you are trying to change.
To find out which table caused the error you can run SHOW ENGINE INNODB STATUS
and then look at the LATEST FOREIGN KEY ERROR
section.
Be wary, too, of inheriting workspace settings in your projects for Java Compiler/Compliance settings. I had a project that was imported into Eclipse. Eclipse generated the project with a J2SE 1.4 JRE, compiler, and compliance settings.
When I went in and manually updated these settings and un-checked the "Enable project specific settings" box, I was still receiving build errors relating to 1.5 level compliance (even though the workspace settings were clearly 1.6). It wasn't until I re-checked the "Enable project specific settings" box and manually set the compiler/compliance levels to 1.6 did the errors go away.
You can use IN operator as below
select * from dbo.books where isbn IN
(select isbn from dbo.lending where lended_date between @fdate and @tdate)
Try to use this one:
::selection {
background: transparent;
}
And if you wish to specify not select inside a specific element, just put the element class or id before the selection rule, such as:
.ClassNAME::selection {
background: transparent;
}
#IdNAME::selection {
background: transparent;
}
You should create a custom exception that prototypically inherits from Error. For example:
function InvalidArgumentException(message) {
this.message = message;
// Use V8's native method if available, otherwise fallback
if ("captureStackTrace" in Error)
Error.captureStackTrace(this, InvalidArgumentException);
else
this.stack = (new Error()).stack;
}
InvalidArgumentException.prototype = Object.create(Error.prototype);
InvalidArgumentException.prototype.name = "InvalidArgumentException";
InvalidArgumentException.prototype.constructor = InvalidArgumentException;
This is basically a simplified version of what disfated posted above with the enhancement that stack traces work on Firefox and other browsers. It satisfies the same tests that he posted:
Usage:
throw new InvalidArgumentException();
var err = new InvalidArgumentException("Not yet...");
And it will behave is expected:
err instanceof InvalidArgumentException // -> true
err instanceof Error // -> true
InvalidArgumentException.prototype.isPrototypeOf(err) // -> true
Error.prototype.isPrototypeOf(err) // -> true
err.constructor.name // -> InvalidArgumentException
err.name // -> InvalidArgumentException
err.message // -> Not yet...
err.toString() // -> InvalidArgumentException: Not yet...
err.stack // -> works fine!
I'm loading 50,000 records in 15 or so seconds using Array Binding in ODP.NET
It works by repeatedly invoking a stored procedure you specify (and in which you can do updates/inserts/deletes), but it passes the multiple parameter values from .NET to the database in bulk.
Instead of specifying a single value for each parameter to the stored procedure you specify an array of values for each parameter.
Oracle passes the parameter arrays from .NET to the database in one go, and then repeatedly invokes the stored procedure you specify using the parameter values you specified.
http://www.oracle.com/technetwork/issue-archive/2009/09-sep/o59odpnet-085168.html
/Damian
The GeoCoordinate class (.NET Framework 4 and higher) already has GetDistanceTo
method.
var sCoord = new GeoCoordinate(sLatitude, sLongitude);
var eCoord = new GeoCoordinate(eLatitude, eLongitude);
return sCoord.GetDistanceTo(eCoord);
The distance is in meters.
You need to reference System.Device.
changing name of /bootstrap/cache/config.php to config.php.old doesn't work for me neither clearing cache with the commands artisan
And for some weird reason I can't change permission for the owner on the directories, so my solution was running my IDE (Visual Studio Code) as admin, and everything works.
My project is in an F:/ path of another disk.
Here is the code of TextScanner
public class TextScanner {
private static void readFile(String fileName) {
try {
File file = new File("/opt/pol/data22/ds_data118/0001/0025090290/2014/12/12/0029057983.ds");
Scanner scanner = new Scanner(file);
while (scanner.hasNext()) {
System.out.println(scanner.next());
}
scanner.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
if (args.length != 1) {
System.err.println("usage: java TextScanner1"
+ "file location");
System.exit(0);
}
readFile(args[0]);
}
}
It will print text with delimeters
WhatsApp does not have a API available for public use. As you put it, it's a closed system.
However, they provide several other ways in which your iPhone application can interact with WhatsApp: through custom URL schemes, share extension and through the Document Interaction API.
Use grep as follows:
grep -R "touch" .
-R
means recurse. If you would rather not go into the subdirectories, then skip it.
-i
means "ignore case". You might find this worth a try as well.
To avoid repeating what have been said multiple times, I am showing an alternative for those that need a cryptographically stronger pseudo-random number generator by using the SecureRandom class, which extends the class Random
. From source one can read:
This class provides a cryptographically strong random number generator (RNG). A cryptographically strong random number minimally complies with the statistical random number generator tests specified in FIPS 140-2, Security Requirements for Cryptographic Modules, section 4.9.1. Additionally, SecureRandom must produce non-deterministic output. Therefore any seed material passed to a SecureRandom object must be unpredictable, and all SecureRandom output sequences must be cryptographically strong, as described in RFC 1750: Randomness Recommendations for Security.
A caller obtains a SecureRandom instance via the no-argument constructor or one of the getInstance methods:
SecureRandom random = new SecureRandom();
Many SecureRandom implementations are in the form of a pseudo-random number generator (PRNG), which means they use a deterministic algorithm to produce a pseudo-random sequence from a true random seed. Other implementations may produce true random numbers, and yet others may use a combination of both techniques.
To generate a random number between a min
and max
values inclusive:
public static int generate(SecureRandom secureRandom, int min, int max) {
return min + secureRandom.nextInt((max - min) + 1);
}
for a given a min
(inclusive) and max
(exclusive) values:
return min + secureRandom.nextInt((max - min));
A running code example:
public class Main {
public static int generate(SecureRandom secureRandom, int min, int max) {
return min + secureRandom.nextInt((max - min) + 1);
}
public static void main(String[] arg) {
SecureRandom random = new SecureRandom();
System.out.println(generate(random, 0, 2 ));
}
}
Source such as stackoverflow, baeldung, geeksforgeeks provide comparisons between Random
and SecureRandom
classes.
From baeldung one can read:
The most common way of using SecureRandom is to generate int, long, float, double or boolean values:
int randomInt = secureRandom.nextInt();
long randomLong = secureRandom.nextLong();
float randomFloat = secureRandom.nextFloat();
double randomDouble = secureRandom.nextDouble();
boolean randomBoolean = secureRandom.nextBoolean();For generating int values we can pass an upper bound as a parameter:
int randomInt = secureRandom.nextInt(upperBound);
In addition, we can generate a stream of values for int, double and long:
IntStream randomIntStream = secureRandom.ints();
LongStream randomLongStream = secureRandom.longs();
DoubleStream randomDoubleStream = secureRandom.doubles();For all streams we can explicitly set the stream size:
IntStream intStream = secureRandom.ints(streamSize);
This class offers several other options (e.g., choosing the underlying random number generator) that are out of the scope of this question.
Another approach is using regex , as show below , you can use the empty regex pattern and achieve the same using ng-pattern
HTML :
<body ng-app="app" ng-controller="formController">
<form name="myform">
<input name="myfield" ng-model="somefield" ng-minlength="5" ng-pattern="mypattern" required>
<span ng-show="myform.myfield.$error.pattern">Please enter!</span>
<span ng-show="!myform.myfield.$error.pattern">great!</span>
</form>
Controller:@formController :
var App = angular.module('app', []);
App.controller('formController', function ($scope) {
$scope.mypattern = /^\s*$/g;
});
import math
from collections import namedtuple
Point = namedtuple("Point", ["x", "y"])
def get_angle(p1: Point, p2: Point) -> float:
"""Get the angle of this line with the horizontal axis."""
dx = p2.x - p1.x
dy = p2.y - p1.y
theta = math.atan2(dy, dx)
angle = math.degrees(theta) # angle is in (-180, 180]
if angle < 0:
angle = 360 + angle
return angle
For testing I let hypothesis generate test cases.
import hypothesis.strategies as s
from hypothesis import given
@given(s.floats(min_value=0.0, max_value=360.0))
def test_angle(angle: float):
epsilon = 0.0001
x = math.cos(math.radians(angle))
y = math.sin(math.radians(angle))
p1 = Point(0, 0)
p2 = Point(x, y)
assert abs(get_angle(p1, p2) - angle) < epsilon
Use setState
in your view to change employed
property of state. This is example of React render engine.
someFunctionWhichChangeParamEmployed(isEmployed) {
this.setState({
employed: isEmployed
});
}
getInitialState() {
return {
employed: true
}
},
render(){
if (this.state.employed) {
return (
<div>
<MyInput ref="job-title" name="job-title" />
</div>
);
} else {
return (
<div>
<span>Diff me!</span>
<MyInput ref="unemployment-reason" name="unemployment-reason" />
<MyInput ref="unemployment-duration" name="unemployment-duration" />
</div>
);
}
}
var ipAddress = "10.101.5.56";
var longAddress = long.Parse(string.Join("", ipAddress.Split('.').Select(x => x.PadLeft(3, '0'))));
Console.WriteLine(longAddress);
Output: 10101005056
You need to do that on the client side for instance with jQuery.
Let's say you want to retrieve HTML into div with ID mydiv
:
<h1>My page</h1>
<div id="mydiv">
<h2>This div is updated</h2>
</div>
You can update this part of the page with jQuery as follows:
$.get('/api/mydiv', function(data) {
$('#mydiv').html(data);
});
In the server-side you need to implement handler for requests coming to /api/mydiv
and return the fragment of HTML that goes inside mydiv.
See this Fiddle I made for you for a fun example using jQuery get with JSON response data: http://jsfiddle.net/t35F9/1/
>>> [[int(i) for i in line.strip().split(',')] for line in open('input.txt').readlines()]
[[995957, 16833579], [995959, 16777241], [995960, 16829368], [995961, 50431654]]
I just wrote a quick function to do this. I needed it to handle many forms so I made it so it will accept a string separated by ','.
//function to make sure that all of the required fields of a post are sent. Returns True for error and False for NO error
//accepts a string that is then parsed by "," into an array. The array is then checked for empty values.
function errorPOSTEmpty($stringOfFields) {
$error = false;
if(!empty($stringOfFields)) {
// Required field names
$required = explode(',',$stringOfFields);
// Loop over field names
foreach($required as $field) {
// Make sure each one exists and is not empty
if (empty($_POST[$field])) {
$error = true;
// No need to continue loop if 1 is found.
break;
}
}
}
return $error;
}
So you can enter this function in your code, and handle errors on a per page basis.
$postError = errorPOSTEmpty('login,password,confirm,name,phone,email');
if ($postError === true) {
...error code...
} else {
...vars set goto POSTing code...
}
In jinja2 templates (which flask uses), use
href="{{ url_for('static', filename='mainpage.css')}}"
The static
files are usually in the static
folder, though, unless configured otherwise.
Why not try find /usr/include/X11 -name Xlib.h
If there is a hit, you have Xlib.h
If not install it using sudo apt-get install libx11-dev
and you are good to go :)
Add an = at the beginning. That makes it a function rather than an entry.
You have to dispatch after the async request ends.
This would work:
export function bindComments(postId) {
return function(dispatch) {
return API.fetchComments(postId).then(comments => {
// dispatch
dispatch({
type: BIND_COMMENTS,
comments,
postId
});
});
};
}
Try the following way.
Select * from t1 where date(col_name)="8/3/2010"
Using an extencion to DateTime:
public enum eTimeFragment
{
hours,
minutes,
seconds,
milliseconds
}
public static DateTime ClearTimeFrom(this DateTime dateToClear, eTimeFragment etf)
{
DateTime dtRet = dateToClear;
switch (etf)
{
case eTimeFragment.hours:
dtRet = dateToClear.Date;
break;
case eTimeFragment.minutes:
dtRet = dateToClear.AddMinutes(dateToClear.Minute * -1);
dtRet = dtRet.ClearTimeFrom(eTimeFragment.seconds);
break;
case eTimeFragment.seconds:
dtRet = dateToClear.AddSeconds(dateToClear.Second * -1);
dtRet = dtRet.ClearTimeFrom(eTimeFragment.milliseconds);
break;
case eTimeFragment.milliseconds:
dtRet = dateToClear.AddMilliseconds(dateToClear.Millisecond * -1);
break;
}
return dtRet;
}
Use like this:
Console.WriteLine (DateTime.Now.ClearTimeFrom(eTimeFragment.hours))
this has to return: 2016-06-06 00:00:00.000
See Time Complexity. The python dict is a hashmap, its worst case is therefore O(n) if the hash function is bad and results in a lot of collisions. However that is a very rare case where every item added has the same hash and so is added to the same chain which for a major Python implementation would be extremely unlikely. The average time complexity is of course O(1).
The best method would be to check and take a look at the hashs of the objects you are using. The CPython Dict uses int PyObject_Hash (PyObject *o) which is the equivalent of hash(o)
.
After a quick check, I have not yet managed to find two tuples that hash to the same value, which would indicate that the lookup is O(1)
l = []
for x in range(0, 50):
for y in range(0, 50):
if hash((x,y)) in l:
print "Fail: ", (x,y)
l.append(hash((x,y)))
print "Test Finished"
CodePad (Available for 24 hours)
Python now comes with its own implementation of virtual environment, by the name of "venv". I would suggest using that, instead of virtualenv.
Quoting from venv - docs,
Deprecated since version 3.6: pyvenv was the recommended tool for creating virtual environments for Python 3.3 and 3.4, and is deprecated in Python 3.6.
Changed in version 3.5: The use of venv is now recommended for creating virtual environments.
For windows, to initiate venv on some project, open cmd:
python -m venv "c:\path\to\myenv"
(Would suggest using double quote around directory path if it contains any spaces. Ex: "C:/My Dox/Spaced Directory/Something")
Once venv is set up, you will see some new folders inside your project directory. One of them would be "Scripts".
To activate or invoke venv you need:
C:\> <venv>\Scripts\activate.bat
You can deactivate a virtual environment by typing “deactivate” in your shell. With this, you are now ready to install your project specific libraries, which will reside under the folder "Lib".
================================ Edit 1 ==================================== The scenario which will be discussed below is not what originally asked, just adding this in case someone use vscode with python extension
In case, you use vs code with its python extension, you might face an issue with its pylint which points to the global installation. In this case, pylint won't be able to see the modules that are installed in your virtual environment and hence will show errors while importing.
Here is a simple method to get past this.
cd Workspace\Scripts
.\Activate.ps1
code .
We are basically activating the environment first and then invoking vs-code so that pylint starts within the environment and can see all local packages.
You can do the following:
Load the data:
test <- read.csv(
"http://archive.ics.uci.edu/ml/machine-learning-databases/breast-cancer-wisconsin/breast-cancer-wisconsin.data",
header=FALSE)
Note that the default value of the header
argument for read.csv
is TRUE
so in order to get all lines you need to set it to FALSE
.
Add names to the different columns in the data.frame
names(test) <- c("A","B","C","D","E","F","G","H","I","J","K")
or alternative and faster as I understand (not reloading the entire dataset):
colnames(test) <- c("A","B","C","D","E","F","G","H","I","J","K")
Here is a useful string formatting function using regular expressions and captures:
function format (fmtstr) {
var args = Array.prototype.slice.call(arguments, 1);
return fmtstr.replace(/\{(\d+)\}/g, function (match, index) {
return args[index];
});
}
Strings can be formatted like C# String.Format:
var str = format('{0}, {1}!', 'Hello', 'world');
console.log(str); // prints "Hello, world!"
the format will place the correct variable in the correct spot, even if they appear out of order:
var str = format('{1}, {0}!', 'Hello', 'world');
console.log(str); // prints "world, Hello!"
Hope this helps!
I faced the same problem when i upgraded my Xcode to 7.3 and it showed me the same error in every project. The simplest solution that i found was to just the remove the apple account from Xcode and add it again.
To remove just go to Xcode > Preferences > Select the account and click on - sign.
and to add click on + sign and add the apple ID corresponding to your app.
After you add the account your problem would be solved.. If in case this still doesn't work . Then perform a next step of regenerating the profile (just click edit and then generate ) and then downloading your provisioning profile again and run it. I bet that would work .
Hope this helps. All the best
How can one get the dimensions of the screen in iOS?
The problem with the code that you posted is that you're counting on the view size to match that of the screen, and as you've seen that's not always the case. If you need the screen size, you should look at the object that represents the screen itself, like this:
CGRect screenRect = [[UIScreen mainScreen] bounds];
CGFloat screenWidth = screenRect.size.width;
CGFloat screenHeight = screenRect.size.height;
Update for split view: In comments, Dmitry asked:
How can I get the size of the screen in the split view?
The code given above reports the size of the screen, even in split screen mode. When you use split screen mode, your app's window changes. If the code above doesn't give you the information you expect, then like the OP, you're looking at the wrong object. In this case, though, you should look at the window instead of the screen, like this:
CGRect windowRect = self.view.window.frame;
CGFloat windowWidth = windowRect.size.width;
CGFloat windowHeight = windowRect.size.height;
let screenRect = UIScreen.main.bounds
let screenWidth = screenRect.size.width
let screenHeight = screenRect.size.height
// split screen
let windowRect = self.view.window?.frame
let windowWidth = windowRect?.size.width
let windowHeight = windowRect?.size.height
This error message appeared for me when I tried to debug two solutions at the same time as I wanted to visually compare the differences. Unchecking the Enable JavaScript Debugging for ASP.NET (Chrome and IE) option worked, but I am still confused why I could not debug more than one solution at a time. Since it is a known issue, maybe this will be address in an update from Visual Studio. Here is to hoping ....
Helpful method I created a while ago...
private static double round (double value, int precision) {
int scale = (int) Math.pow(10, precision);
return (double) Math.round(value * scale) / scale;
}
assuming you want to have a range between x to y
range(x,y+1)
>>> range(11,17)
[11, 12, 13, 14, 15, 16]
>>>
use list for 3.x support
I believe you can also do:
$sortDirection = 'desc';
$user->with(['comments' => function ($query) use ($sortDirection) {
$query->orderBy('column', $sortDirection);
}]);
That allows you to run arbitrary logic on each related comment record. You could have stuff in there like:
$query->where('timestamp', '<', $someTime)->orderBy('timestamp', $sortDirection);
C++ has no built-in concepts of interfaces. You can implement it using abstract classes which contains only pure virtual functions. Since it allows multiple inheritance, you can inherit this class to create another class which will then contain this interface (I mean, object interface :) ) in it.
An example would be something like this -
class Interface
{
public:
Interface(){}
virtual ~Interface(){}
virtual void method1() = 0; // "= 0" part makes this method pure virtual, and
// also makes this class abstract.
virtual void method2() = 0;
};
class Concrete : public Interface
{
private:
int myMember;
public:
Concrete(){}
~Concrete(){}
void method1();
void method2();
};
// Provide implementation for the first method
void Concrete::method1()
{
// Your implementation
}
// Provide implementation for the second method
void Concrete::method2()
{
// Your implementation
}
int main(void)
{
Interface *f = new Concrete();
f->method1();
f->method2();
delete f;
return 0;
}
src="/clock.js"
be careful it's root of the domain.
P.S. and please use lowercase for attribute names.
MSSQL requires that variables within procedures be DECLAREd and folks use the @Variable syntax (DECLARE @TEXT VARCHAR(25) = 'text'). Also, MS allows for declares within any block in the procedure, unlike mySQL which requires all the DECLAREs at the top.
While good on the command line, I feel using the "set = @variable" within stored procedures in mySQL is risky. There is no scope and variables live across scope boundaries. This is similar to variables in JavaScript being declared without the "var" prefix, which are then the global namespace and create unexpected collisions and overwrites.
I am hoping that the good folks at mySQL will allow DECLARE @Variable at various block levels within a stored procedure. Notice the @ (at sign). The @ sign prefix helps to separate variable names from table column names - as they are often the same. Of course, one can always add an "v" or "l_" prefix, but the @ sign is a handy and succinct way to have the variable name match the column you might be extracting the data from without clobbering it.
MySQL is new to stored procedures and they have done a good job for their first version. It will be a pleaure to see where they take it form here and to watch the server side aspects of the language mature.
Until React provides a better way, you can create a helper, useEffectAsync.js
:
import { useEffect } from 'react';
export default function useEffectAsync(effect, inputs) {
useEffect(() => {
effect();
}, inputs);
}
Now you can pass an async function:
useEffectAsync(async () => {
const items = await fetchSomeItems();
console.log(items);
}, []);
Update
If you choose this approach, note that it's bad form. I resort to this when I know it's safe, but it's always bad form and haphazard.
Suspense for Data Fetching, which is still experimental, will solve some of the cases.
In other cases, you can model the async results as events so that you can add or remove a listener based on the component life cycle.
Or you can model the async results as an Observable so that you can subscribe and unsubscribe based on the component life cycle.
The simplest is to do a PivotChart. Select your array of dates (with a header) and create a new Pivot Chart (Insert / PivotChart / Ok) Then on the field list window, drag and drop the date column in the Axis list first and then in the value list first.
Step 1:
Step 2:
In my case I was using ClassName
.
getComputedStyle( document.getElementsByClassName(this_id)) //error
It will also work without 2nd argument " "
.
Here is my complete running code :
function changeFontSize(target) {
var minmax = document.getElementById("minmax");
var computedStyle = window.getComputedStyle
? getComputedStyle(minmax) // Standards
: minmax.currentStyle; // Old IE
var fontSize;
if (computedStyle) { // This will be true on nearly all browsers
fontSize = parseFloat(computedStyle && computedStyle.fontSize);
if (target == "sizePlus") {
if(fontSize<20){
fontSize += 5;
}
} else if (target == "sizeMinus") {
if(fontSize>15){
fontSize -= 5;
}
}
minmax.style.fontSize = fontSize + "px";
}
}
onclick= "changeFontSize(this.id)"
Open cmd type adb shell
then press enter.
Type ls
to view files list.
To add to Preston's answer, here's the complete list of the HttpContent
derived classes available in the standard library:
Credit: https://pfelix.wordpress.com/2012/01/16/the-new-system-net-http-classes-message-content/
There's also a supposed ObjectContent
but I was unable to find it in ASP.NET Core
.
Of course, you could skip the whole HttpContent
thing all together with Microsoft.AspNet.WebApi.Client
extensions (you'll have to do an import to get it to work in ASP.NET Core for now: https://github.com/aspnet/Home/issues/1558) and then you can do things like:
var response = await client.PostAsJsonAsync("AddNewArticle", new Article
{
Title = "New Article Title",
Body = "New Article Body"
});
using JQuery:
myelement=$("#myelement")
[myelement.offset().left, myelement.offset().top, myelement.width(), myelement.height()]
One way would be with sed
. For example:
echo $name | sed -e 's?http://www\.??'
Normally the sed
regular expressions are delimited by `/', but you can use '?' since you're searching for '/'. Here's another bash trick. @DigitalTrauma's answer reminded me that I ought to suggest it. It's similar:
echo ${name#http://www.}
(DigitalTrauma also gets credit for reminding me that the "http://" needs to be handled.)
John Sansom and Ed Harper have great solutions. However, I was unable to get them to work when dealing with ID fields (i.e. Integers). I modified the split function below to CAST the values as integers so the table will join with primary key columns. I also commented the code and added a column for order, in case the delimited list order was significant.
CREATE FUNCTION [dbo].[fn_SplitInt]
(
@List nvarchar(4000),
@Delimiter char(1)= ','
)
RETURNS @Values TABLE
(
Position int IDENTITY PRIMARY KEY,
Number int
)
AS
BEGIN
-- set up working variables
DECLARE @Index INT
DECLARE @ItemValue nvarchar(100)
SELECT @Index = 1
-- iterate until we have no more characters to work with
WHILE @Index > 0
BEGIN
-- find first delimiter
SELECT @Index = CHARINDEX(@Delimiter,@List)
-- extract the item value
IF @Index > 0 -- if found, take the value left of the delimiter
SELECT @ItemValue = LEFT(@List,@Index - 1)
ELSE -- if none, take the remainder as the last value
SELECT @ItemValue = @List
-- insert the value into our new table
INSERT INTO @Values (Number) VALUES (CAST(@ItemValue AS int))
-- remove the found item from the working list
SELECT @List = RIGHT(@List,LEN(@List) - @Index)
-- if list is empty, we are done
IF LEN(@List) = 0 BREAK
END
RETURN
END
Use this function as previously noted with:
WHERE id IN (SELECT Number FROM dbo.fn_SplitInt(@sParameterString,','))
I for myself prefer Lukas Edger's solution.
But you might want to know there is also a function SYS_GUID which can be applied as a default value to a column and generate unique ids.
you can read more about pros and cons here
You can create a custom class for your panel heading. Using this css class you can style the panel heading. I have a simple Fiddle for this.
HTML:
<div class="panel panel-default">
<div class="panel-heading panel-heading-custom">
<h3 class="panel-title">Panel title</h3>
</div>
<div class="panel-body">
Panel content
</div>
</div>
CSS:
.panel-default > .panel-heading-custom {
background: #ff0000; color: #fff; }
Demo Link:
I think this is also a solution of this problem.
Change your document type from 'Encode in UTF-8' To 'Encode in UTF-8 without BOM'
I got resolved my problem by doing same changes.
If you want to log to STDOUT you can use any of the ways Laravel provides; for example (from wired00's answer):
Log::info('This is some useful information.');
The STDOUT magic can be done with the following (you are setting the file where info
messages go):
Log::useFiles('php://stdout', 'info');
Word of caution: this is strictly for debugging. Do no use anything in production you don't fully understand.
try with below on powershell:
Set-ExecutionPolicy -ExecutionPolicy Unrestricted
import-module [\path\]XMLHelpers.psm1
Instead of [] put the full path
You're probably returning an object that's on the stack. That is, return_Object()
probably looks like this:
Object& return_Object()
{
Object object_to_return;
// ... do stuff ...
return object_to_return;
}
If this is what you're doing, you're out of luck - object_to_return
has gone out of scope and been destructed at the end of return_Object
, so myObject
refers to a non-existent object. You either need to return by value, or return an Object
declared in a wider scope or new
ed onto the heap.
The max size for a column of type NVARCHAR(MAX)
is 2 GByte of storage.
Since NVARCHAR
uses 2 bytes per character, that's approx. 1 billion characters.
Leo Tolstoj's War and Peace is a 1'440 page book, containing about 600'000 words - so that might be 6 million characters - well rounded up. So you could stick about 166 copies of the entire War and Peace book into each NVARCHAR(MAX)
column.
Is that enough space for your needs? :-)
sed
is the stream editor, in that you can use |
(pipe) to send standard streams (STDIN and STDOUT specifically) through sed
and alter them programmatically on the fly, making it a handy tool in the Unix philosophy tradition; but can edit files directly, too, using the -i
parameter mentioned below.
Consider the following:
sed -i -e 's/few/asd/g' hello.txt
s/
is used to substitute the found expression few
with asd
:
The few, the brave.
The asd, the brave.
/g
stands for "global", meaning to do this for the whole line. If you leave off the /g
(with s/few/asd/
, there always needs to be three slashes no matter what) and few
appears twice on the same line, only the first few
is changed to asd
:
The few men, the few women, the brave.
The asd men, the few women, the brave.
This is useful in some circumstances, like altering special characters at the beginnings of lines (for instance, replacing the greater-than symbols some people use to quote previous material in email threads with a horizontal tab while leaving a quoted algebraic inequality later in the line untouched), but in your example where you specify that anywhere few
occurs it should be replaced, make sure you have that /g
.
The following two options (flags) are combined into one, -ie
:
-i
option is used to edit in place on the file hello.txt
.
-e
option indicates the expression/command to run, in this case s/
.
Note: It's important that you use -i -e
to search/replace. If you do -ie
, you create a backup of every file with the letter 'e' appended.
I think something like this would give you the current CultureInfo:
CultureInfo currentCulture = Thread.CurrentThread.CurrentCulture;
Is that what you're looking for?
If the date String does not include any value for hours, minutes and etc you cannot directly convert this to a LocalDateTime
. You can only convert it to a LocalDate
, because the string only represent the year,month and date components it would be the correct thing to do.
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyyMMdd");
LocalDate ld = LocalDate.parse("20180306", dtf); // 2018-03-06
Anyway you can convert this to LocalDateTime
.
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyyMMdd");
LocalDate ld = LocalDate.parse("20180306", dtf);
LocalDateTime ldt = LocalDateTime.of(ld, LocalTime.of(0,0)); // 2018-03-06T00:00
You could also use CEILING
which rounds up to an integer or desired multiple of significance
ie
=CEILING(A1,10)
rounds up to a multiple of 10
12340.0001
will become 12350
You can check if the error is of type WebException
and then inspect the response code;
if (e.Error.GetType().Name == "WebException")
{
WebException we = (WebException)e.Error;
HttpWebResponse response = (System.Net.HttpWebResponse)we.Response;
if (response.StatusCode==HttpStatusCode.NotFound)
System.Diagnostics.Debug.WriteLine("Not found!");
}
or
try
{
// send request
}
catch (WebException e)
{
// check e.Status as above etc..
}
each time you perform an insert operation on any model, cake internally fetchesthe last insert Id and Sets to Model->id attribute.
so one can access it directly by $Model->id;, no need to query again for lastInsertId.
The vblank_mode
environment variable does the trick. You should then get several hundreds FPS on modern hardware. And you are now able to compare the results with others.
$> vblank_mode=0 glxgears
Another way is to subtract 15 days from the current date and compare CreationTime
against that value:
$root = 'C:\root\folder'
$limit = (Get-Date).AddDays(-15)
Get-ChildItem $root -Recurse | ? {
-not $_.PSIsContainer -and $_.CreationTime -lt $limit
} | Remove-Item
You're looking in the wrong place. You should look up Windows Communication Framework.
WCF is used both on the client and on the server.
fprintf
This is related with streams where as printf
is a statement similar to fprintf
but not related to streams, that is fprintf
is file related
Instead of using
if(data !== null && data !== '' && data!==undefined) {
// do something
}
You can use below simple code
if(Boolean(value)){
// do something
}
Run
php -m -c
in your terminal, and then look for [Zend Modules]
. It should be somewhere there if it is loaded!
NB
If you're using Ubuntu, it may not show up here because you need to add the xdebug settings from /etc/php5/apache2/php.ini
into /etc/php5/cli/php.ini
. Mine are
[xdebug]
zend_extension = /usr/lib/php5/20121212/xdebug.so
xdebug.remote_enable=on
xdebug.remote_handler=dbgp
xdebug.remote_mode=req
xdebug.remote_host=localhost
xdebug.remote_port=9000
Another interesting way to listen file input changes is with a watch over the ng-model attribute of the input file. Off course FileModel is a custom directive.
Like this:
HTML -> <input type="file" file-model="change.fnEvidence">
JS Code ->
$scope.$watch('change.fnEvidence', function() {
alert("has changed");
});
Hope it can helps someone.
In addition to BoshWash's answer, here is the picture generated by his code:
Try this
$("div#date").text().trim().replace(/\W/g,'/');
Look a regular expression http://regexone.com/lesson/misc_meta_characters
enjoy us ;-)
They're different characters. \r
is carriage return, and \n
is line feed.
On "old" printers, \r
sent the print head back to the start of the line, and \n
advanced the paper by one line. Both were therefore necessary to start printing on the next line.
Obviously that's somewhat irrelevant now, although depending on the console you may still be able to use \r
to move to the start of the line and overwrite the existing text.
More importantly, Unix tends to use \n
as a line separator; Windows tends to use \r\n
as a line separator and Macs (up to OS 9) used to use \r
as the line separator. (Mac OS X is Unix-y, so uses \n
instead; there may be some compatibility situations where \r
is used instead though.)
For more information, see the Wikipedia newline article.
EDIT: This is language-sensitive. In C# and Java, for example, \n
always means Unicode U+000A, which is defined as line feed. In C and C++ the water is somewhat muddier, as the meaning is platform-specific. See comments for details.
Google is using this to detect whether the device is online or in captive portal.
Shill, the connection manager for Chromium OS, attempts to detect services that are within a captive portal whenever a service transitions to the ready state. This determination of being in a captive portal or being online is done by attempting to retrieve the webpage http://clients3.google.com/generate_204. This well known URL is known to return an empty page with an HTTP status 204. If for any reason the web page is not returned, or an HTTP response other than 204 is received, then shill marks the service as being in the portal state.
Here is the relevant explanation from the Google Chrome Privacy Whitepaper:
In the event that Chrome detects SSL connection timeouts, certificate errors, or other network issues that might be caused by a captive portal (a hotel's WiFi network, for instance), Chrome will make a cookieless request to http://www.gstatic.com/generate_204 and check the response code. If that request is redirected, Chrome will open the redirect target in a new tab on the assumption that it's a login page. Requests to the captive portal detection page are not logged.
More info: http://www.chromium.org/chromium-os/chromiumos-design-docs/network-portal-detection
In case you have auto increment in the table and need to access it.. you can use the following approach... Do test before using because getGeneratedKeys() in Statement because it depends on driver used. The below code is tested on Maria DB 10.0.12 and Maria JDBC driver 1.2
Remember that increasing batch size improves performance only to a certain extent... for my setup increasing batch size above 500 was actually degrading the performance.
public Connection getConnection(boolean autoCommit) throws SQLException {
Connection conn = dataSource.getConnection();
conn.setAutoCommit(autoCommit);
return conn;
}
private void testBatchInsert(int count, int maxBatchSize) {
String querySql = "insert into batch_test(keyword) values(?)";
try {
Connection connection = getConnection(false);
PreparedStatement pstmt = null;
ResultSet rs = null;
boolean success = true;
int[] executeResult = null;
try {
pstmt = connection.prepareStatement(querySql, Statement.RETURN_GENERATED_KEYS);
for (int i = 0; i < count; i++) {
pstmt.setString(1, UUID.randomUUID().toString());
pstmt.addBatch();
if ((i + 1) % maxBatchSize == 0 || (i + 1) == count) {
executeResult = pstmt.executeBatch();
}
}
ResultSet ids = pstmt.getGeneratedKeys();
for (int i = 0; i < executeResult.length; i++) {
ids.next();
if (executeResult[i] == 1) {
System.out.println("Execute Result: " + i + ", Update Count: " + executeResult[i] + ", id: "
+ ids.getLong(1));
}
}
} catch (Exception e) {
e.printStackTrace();
success = false;
} finally {
if (rs != null) {
rs.close();
}
if (pstmt != null) {
pstmt.close();
}
if (connection != null) {
if (success) {
connection.commit();
} else {
connection.rollback();
}
connection.close();
}
}
} catch (SQLException e) {
e.printStackTrace();
}
}
Agree with Sachin. Just one improvement, use connect_ex instead of connect, which can avoid try except
>>> def port_check(ip_port):
... s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
... s.settimeout(1)
... r = s.connect_ex(ip_port)
... return r == 0
...
>>> port_check(loc)
True
>>> port_check(loc_x)
False
>>> loc
('10.3.157.24', 6443)
>>>
The correct parameter to set the maximum length is:
SET @@group_concat_max_len = value_numeric;
value_numeric
must be > 1024; by default the group_concat_max_len
value is 1024.
You can do a casting. For example, if exists one method with this definition, and you know that this method is returning a List:
Collection<String> getStrings();
And after invoke it, you need the first element, you can do it like this:
List<String> listString = (List) getStrings();
String firstElement = (listString.isEmpty() ? null : listString.get(0));
You can try something similar to this :
String s = "65";
byte value = Byte.valueOf(s);
Use the Byte.ValueOf()
method for all the elements in the String array to convert them into Byte values.
Simplest ways to mock an HttpServletRequest
:
Create an anonymous subclass:
HttpServletRequest mock = new HttpServletRequest ()
{
private final Map<String, String[]> params = /* whatever */
public Map<String, String[]> getParameterMap()
{
return params;
}
public String getParameter(String name)
{
String[] matches = params.get(name);
if (matches == null || matches.length == 0) return null;
return matches[0];
}
// TODO *many* methods to implement here
};
Use jMock, Mockito, or some other general-purpose mocking framework:
HttpServletRequest mock = context.mock(HttpServletRequest.class); // jMock
HttpServletRequest mock2 = Mockito.mock(HttpServletRequest.class); // Mockito
Use HttpUnit's ServletUnit and don't mock the request at all.
As @????? ????????? said: the sizes of Writer have to match with the frame from the camera or files.
You can use such code to check if your camera is (640, 480) or not:
print(int(cap.get(3)), int(cap.get(4)))
For myself, I found my camera is (1280, 720) and replaced (640, 480) with (1280, 720). Then it can save videos.
Gmail requires port 465, and also it's the code from phpmailer :)
I figured out what went wrong. In the proxy configuration of my box, an extra http://
got prefixed to "proxy server with http".
Example..
http://http://proxy.mycollege.com
and that has created problems. Corrected that, and it works perfectly.
Thanks @WhiteCoffee and @ChrisBint for your suggestions!
You can use the --prefer-source
flag for composer to checkout external packages with the VCS information (if any available). You can simply revert to the original state. Also if you issue the composer update
command composer will detect any changes you made locally and ask if you want to discard them.
Your .gitignore file is related to your root project (ZF2 skeleton) and it prevents the vendor dir (where your third party libs are) from committing to your own VCS. The ignore file is unrelated to the git repo's of your vendors.
I have much better solution without need of any JavaScript. It is fully responsive, and I use it a lot. You often need to fit an image of any aspect ratio to a container element with a specified aspect ratio. And having whole this thing fully responsive is a must.
/* For this demo only */_x000D_
.container {_x000D_
max-width: 300px;_x000D_
margin: 0 auto;_x000D_
}_x000D_
.img-frame {_x000D_
box-shadow: 3px 3px 6px rgba(0, 0, 0, .15);_x000D_
background: #ee0;_x000D_
margin: 20px auto;_x000D_
}_x000D_
_x000D_
/* This is for responsive container with specified aspect ratio */_x000D_
.aspect-ratio {_x000D_
position: relative;_x000D_
}_x000D_
.aspect-ratio-1-1 {_x000D_
padding-bottom: 100%;_x000D_
}_x000D_
.aspect-ratio-4-3 {_x000D_
padding-bottom: 75%;_x000D_
}_x000D_
.aspect-ratio-16-9 {_x000D_
padding-bottom: 56.25%;_x000D_
}_x000D_
_x000D_
/* This is the key part - position and fit the image to the container */_x000D_
.fit-img {_x000D_
position: absolute;_x000D_
top: 0;_x000D_
right: 0;_x000D_
bottom: 0;_x000D_
left: 0;_x000D_
margin: auto;_x000D_
max-width: 80%;_x000D_
max-height: 90%_x000D_
}_x000D_
.fit-img-bottom {_x000D_
top: auto;_x000D_
}_x000D_
.fit-img-tight {_x000D_
max-width: 100%;_x000D_
max-height: 100%_x000D_
}
_x000D_
<div class="container">_x000D_
_x000D_
<div class="aspect-ratio aspect-ratio-1-1 img-frame">_x000D_
<img src="//placehold.it/400x300" class="fit-img" alt="sample">_x000D_
</div>_x000D_
_x000D_
<div class="aspect-ratio aspect-ratio-4-3 img-frame">_x000D_
<img src="//placehold.it/400x300" class="fit-img fit-img-tight" alt="sample">_x000D_
</div>_x000D_
_x000D_
<div class="aspect-ratio aspect-ratio-16-9 img-frame">_x000D_
<img src="//placehold.it/400x400" class="fit-img" alt="sample">_x000D_
</div>_x000D_
_x000D_
_x000D_
<div class="aspect-ratio aspect-ratio-16-9 img-frame">_x000D_
<img src="//placehold.it/300x400" class="fit-img fit-img-bottom" alt="sample">_x000D_
</div>_x000D_
_x000D_
</div>
_x000D_
You can set max-width and max height independently; the image will respect the smallest one (depending on the values and aspect ratio of the image). You can also set image to be aligned as you want (for example, for a product picture on an infinite white background you can position it to center bottom easily).
The Context contains many path functions: Context.getXXXPath()
One of them is android.content.Context.getDatabasePath(String dbname) that returns the absolute path of a database called dbname.
Context ctx = this; // for Activity, or Service. Otherwise simply get the context.
String dbname = "mydb.db";
Path dbpath = ctx.getDatabasePath(dbname);
The returned path, in this case, would be something like:
/data/data/com.me.myapp/databases/mydb.db
Note that this path is autogenerated if using SQLiteOpenHelper to open the DB.
In my case, originally the following error was occurring:
Cannot read configuration file due to insufficient permissions
I fixed the error by using the proposed solution and restarted the application through IIS Manager
. The original error was gone but the application was taking forever to load. I gave the permissions to IIS_IUSRS
again but this time to the whole deployment folder. After this, the application was able to load though an error was showing up:
This configuration section cannot be used at this path
After resolving the above-mentioned error using the solution, the application was finally loading without giving any error.
I don't know if I got you right, but, as I understand, you could use an additional hidden field with the value "add tag" and let the button have the desired text.
You can use this:
//The color RGB #85CC4B
let newColor = UIColor(red: CGFloat(0x85)/255
,green: CGFloat(0xCC)/255
,blue: CGFloat(0x4B)/255
,alpha: 1.0)
Another way to find out if a program is installed is by using the which
command. It will show the path of the program you're searching for. For example if when your searching for apache you can use the following command:
$ which apache2ctl
/usr/sbin/apache2ctl
And if you searching for PHP try this:
$ which php
/usr/bin/php
If the which
command doesn't give any result it means the software is not installed (or is not in the current $PATH
):
$ which php
$
string[] files =
Directory.GetFiles(txtPath.Text, "*ProfileHandler.cs", SearchOption.AllDirectories);
That last parameter effects exactly what you're referring to. Set it to AllDirectories for every file including in subfolders, and set it to TopDirectoryOnly if you only want to search in the directory given and not subfolders.
Refer to MDSN for details: https://msdn.microsoft.com/en-us/library/ms143316(v=vs.110).aspx
If your mongoDB server(remote server)'s version is greater then 4.0.3, then you will face this issue. Hence you should replace your current mongo-client shell with below mongo :
sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv 9DA31620334BD75D9DCB49F368818C72E52529D4
echo "deb [ arch=amd64,arm64 ] https://repo.mongodb.org/apt/ubuntu xenial/mongodb-org/4.0 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-4.0.list
sudo apt-get update
sudo apt-get install -y mongodb-org
Then you mongo client will be able to connect your remove mongodb
You'll need the cookie plugin, which provides several additional signatures to the cookie function.
$.cookie('cookie_name', 'cookie_value')
stores a transient cookie (only exists within this session's scope, while $.cookie('cookie_name', 'cookie_value', 'cookie_expiration")
creates a cookie that will last across sessions - see http://www.stilbuero.de/2006/09/17/cookie-plugin-for-jquery/ for more information on the JQuery cookie plugin.
If you want to set cookies that are used for the entire site, you'll need to use JavaScript like this:
document.cookie = "name=value; expires=date; domain=domain; path=path; secure"
When buffer size gets full. There are several options you can try:
1) Increase the size of the DBMS_OUTPUT buffer to 1,000,000
2) Try filtering the data written to the buffer - possibly there is a loop that writes to DBMS_OUTPUT and you do not need this data.
3) Call ENABLE at various checkpoints within your code. Each call will clear the buffer.
DBMS_OUTPUT.ENABLE(NULL) will default to 20000 for backwards compatibility Oracle documentation on dbms_output
You can also create your custom output display.something like below snippets
create or replace procedure cust_output(input_string in varchar2 )
is
out_string_in long default in_string;
string_lenth number;
loop_count number default 0;
begin
str_len := length(out_string_in);
while loop_count < str_len
loop
dbms_output.put_line( substr( out_string_in, loop_count +1, 255 ) );
loop_count := loop_count +255;
end loop;
end;
Link -Ref :Alternative to dbms_output.putline @ By: Alexander
ctrl + w, w as mentioned can be used for navigating from pane to pane.
Now you can select a particular change alone and paste it to the other pane as follows.Here I am giving an eg as if I wanted to change my piece of code from pane 1 to pane 2 and currently my cursor is in pane1
Use Shift-v to highlight a line and use up or down keys to select the piece of code you require and continue from step 3 written below to paste your changes in the other pane.
Use visual mode and then change it
1 click 'v' this will take you to visual mode 2 use up or down key to select your required code 3 click on ,Esc' escape key 4 Now use 'yy' to copy or 'dd' to cut the change 5 do 'ctrl + w, w' to navigate to pane2 6 click 'p' to paste your change where you require
I think you can use db.collection.distinct(fields,query)
You will be able to get the distinct values in your case for NetworkID.
It should be something like this :
Db.collection.distinct('NetworkID')
My company has about 24million images come in from manufacturers every month. I was looking for a fast solution to ensure that the images we upload to our catalog are new images.
I want to say that I have searched the internet far and wide to attempt to find an ideal solution. I even developed my own edge detection algorithm.
I have evaluated speed and accuracy of multiple models.
My images, which have white backgrounds, work extremely well with phashing. Like redcalx said, I recommend phash or ahash. DO NOT use MD5 Hashing or anyother cryptographic hashes. Unless, you want only EXACT image matches. Any resizing or manipulation that occurs between images will yield a different hash.
For phash/ahash, Check this out: imagehash
I wanted to extend *redcalx'*s post by posting my code and my accuracy.
What I do:
from PIL import Image
from PIL import ImageFilter
import imagehash
img1=Image.open(r"C:\yourlocation")
img2=Image.open(r"C:\yourlocation")
if img1.width<img2.width:
img2=img2.resize((img1.width,img1.height))
else:
img1=img1.resize((img2.width,img2.height))
img1=img1.filter(ImageFilter.BoxBlur(radius=3))
img2=img2.filter(ImageFilter.BoxBlur(radius=3))
phashvalue=imagehash.phash(img1)-imagehash.phash(img2)
ahashvalue=imagehash.average_hash(img1)-imagehash.average_hash(img2)
totalaccuracy=phashvalue+ahashvalue
Here are some of my results:
item1 item2 totalsimilarity
desk1 desk1 3
desk1 phone1 22
chair1 desk1 17
phone1 chair1 34
Hope this helps!
It's simple, use $.getJSON()
function and in your URL just include
callback=?
as a parameter. That will convert the call to JSONP which is necessary to make cross-domain calls. More info: http://api.jquery.com/jQuery.getJSON/
This is how I was able to trigger a button click when the page loads.
<li ng-repeat="a in array">
<a class="button" id="btn" ng-click="function(a)" index="$index" on-load-clicker>
{{a.name}}
</a>
</li>
A simple directive that takes the index from the ng-repeat and uses a condition to call the first button in the index and click it when the page loads.
angular
.module("myApp")
.directive('onLoadClicker', function ($timeout) {
return {
restrict: 'A',
scope: {
index: '=index'
},
link: function($scope, iElm) {
if ($scope.index == 0) {
$timeout(function() {
iElm.triggerHandler('click');
}, 0);
}
}
};
});
This was the only way I was able to even trigger an auto click programmatically in the first place. angular.element(document.querySelector('#btn')).click();
Did not work from the controller so making this simple directive seems most effective if you are trying to run a click on page load and you can specify which button to click by passing in the index. I got help through this stack-overflow answer from another post reference: https://stackoverflow.com/a/26495541/4684183 onLoadClicker Directive.
From MySQL docs:
A character set is a set of symbols and encodings. A collation is a set of rules for comparing characters in a character set. Let's make the distinction clear with an example of an imaginary character set.
Suppose that we have an alphabet with four letters: 'A', 'B', 'a', 'b'. We give each letter a number: 'A' = 0, 'B' = 1, 'a' = 2, 'b' = 3. The letter 'A' is a symbol, the number 0 is the encoding for 'A', and the combination of all four letters and their encodings is a character set.
Now, suppose that we want to compare two string values, 'A' and 'B'. The simplest way to do this is to look at the encodings: 0 for 'A' and 1 for 'B'. Because 0 is less than 1, we say 'A' is less than 'B'. Now, what we've just done is apply a collation to our character set. The collation is a set of rules (only one rule in this case): "compare the encodings." We call this simplest of all possible collations a binary collation.
But what if we want to say that the lowercase and uppercase letters are equivalent? Then we would have at least two rules: (1) treat the lowercase letters 'a' and 'b' as equivalent to 'A' and 'B'; (2) then compare the encodings. We call this a case-insensitive collation. It's a little more complex than a binary collation.
In real life, most character sets have many characters: not just 'A' and 'B' but whole alphabets, sometimes multiple alphabets or eastern writing systems with thousands of characters, along with many special symbols and punctuation marks. Also in real life, most collations have many rules: not just case insensitivity but also accent insensitivity (an "accent" is a mark attached to a character as in German 'ö') and multiple-character mappings (such as the rule that 'ö' = 'OE' in one of the two German collations).
if you are using Maven 2.0.8+, then it will be very simple, run mvndebug from the console, and connect to it via Remote Debug Java Application with port 8000.
I assume you are using windows. Open the command prompt and type ipconfig
and find out your local address (on your pc) it should look something like 192.168.1.13
or 192.168.0.5
where the end digit is the one that changes. It should be next to IPv4 Address.
If your WAMP does not use virtual hosts the next step is to enter that IP address on your phones browser ie http://192.168.1.13
If you have a virtual host then you will need root to edit the hosts file.
If you want to test the responsiveness / mobile design of your website you can change your user agent in chrome or other browsers to mimic a mobile.
See http://googlesystem.blogspot.co.uk/2011/12/changing-user-agent-new-google-chrome.html.
Edit: Chrome dev tools now has a mobile debug tool where you can change the size of the viewport, spoof user agents, connections (4G, 3G etc).
If you get forbidden access then see this question WAMP error: Forbidden You don't have permission to access /phpmyadmin/ on this server. Basically, change the occurrances of deny,allow
to allow,deny
in the httpd.conf
file. You can access this by the WAMP menu.
To eliminate possible causes of the issue for now set your config file to
<Directory />
Options FollowSymLinks
AllowOverride All
Order allow,deny
Allow from all
<RequireAll>
Require all granted
</RequireAll>
</Directory>
As thatis working for my windows PC, if you have the directory config block as well change that also to allow all.
Config file that fixed the problem:
https://gist.github.com/samvaughton/6790739
Problem was that the /www apache directory config block still had deny set as default and only allowed from localhost.
This type of operation is exactly what aggregate
was designed for:
d <- read.table(text=
'Name Month Rate1 Rate2
Aira 1 12 23
Aira 2 18 73
Aira 3 19 45
Ben 1 53 19
Ben 2 22 87
Ben 3 19 45
Cat 1 22 87
Cat 2 67 43
Cat 3 45 32', header=TRUE)
aggregate(d[, 3:4], list(d$Name), mean)
Group.1 Rate1 Rate2
1 Aira 16.33333 47.00000
2 Ben 31.33333 50.33333
3 Cat 44.66667 54.00000
Here we aggregate columns 3 and 4 of data.frame d
, grouping by d$Name
, and applying the mean
function.
Or, using a formula interface:
aggregate(. ~ Name, d[-2], mean)
Google Play does not allow you to publish an app signed with your debug keystore. If you try to upload such an APK, Google Play will fail with the message "You uploaded an APK that was signed in debug mode. You need to sign your APK in release mode."
However, if you try to upload an update which is signed with the debug keystore, you will not see this message; Google Play will display the message shown in the question, referring to SHA1 fingerprints.
So firstly, check whether you signed the app with your debug key by mistake.
You can check which certificates the original APK and update APK were signed with by using these commands, using the Java keytool
:
keytool -list -printcert -jarfile original.apk
keytool -list -printcert -jarfile update.apk
This shows you detailed information about the how an APK was signed, for example:
Owner: CN=My App, O=My Company, L=Somewhere, C=DE
Issuer: CN=My App, O=My Company, L=Somewhere, C=DE
Serial number: 4790b086
Valid from: Mon Nov 11 15:01:28 GMT 2013 until: Fri Mar 29 16:01:28 BST 2041
Certificate fingerprints:
MD5: A3:2E:67:AF:74:3A:BD:DD:A2:A9:0D:CA:6C:D4:AF:20
SHA1: A6:E7:CE:64:17:45:0F:B4:C7:FC:76:43:90:04:DC:A7:84:EF:33:E9
SHA256: FB:6C:59:9E:B4:58:E3:62:AD:81:42:...:09:FC:BC:FE:E7:40:53:C3:D8:14:4F
Signature algorithm name: SHA256withRSA
Version: 3
The important parts to note here — for each APK — are the SHA1 fingerprint value, the Owner identity value, and the Valid from/until dates.
If that keytool
command doesn't work (the -jarfile
option requires Java 7), you can get more basic information via the jarsigner
command:
jarsigner -verify -verbose:summary -certs original.apk
jarsigner -verify -verbose:summary -certs update.apk
This unfortunately does not show the SHA1 fingerprint, but does show the X.509 owner identity, along with the certificate expiry dates. For example:
sm 4642892 Thu Apr 17 10:57:44 CEST 2014 classes.dex (and 412 more)
X.509, CN=My App, O=My Company, L=Somewhere, C=DE
[certificate is valid from 11/11/13 12:12 to 29/03/41 12:12]
[CertPath not validated: Path does not chain with any of the trust anchors]
You can ignore any "CertPath not validated" message, along with warnings about certificate chains or timestamps; they're not relevant in this case.
If the Owner/X.509 identity value is CN=Android Debug, O=Android, C=US
, then you have signed the APK with your debug key, not the original release key
If the SHA1 fingerprint value is different between the original and update APKs, then you did not use the same signing key for both APKs
If the Owner/X.509 identity values are different, or the certificate expiry dates differ between the two APKs, then you did not use the same signing key for both APKs
Note that even if the Owner/X.509 values are identical between the two certificates, this doesn't mean that the certificates are identical — if anything else does not match — such as the fingerprint values — then the certificates are different.
If the two APKs have different certificate information, then you must find the original keystore, i.e. the file with the first SHA1 fingerprint value that Google Play (or keytool
) told you.
Search through all the keystore files you can find on your computer, and in any backups you have, until you have the one with the correct SHA1 fingerprint:
keytool -list -keystore my-release.keystore
Just press Enter if prompted for the password — you don't necessarily have to enter it if you just want to quickly check the SHA1 value.
If you cannot find the original keystore, you will never be able to publish any updates to this particular app.
Android mentions this explicitly on the Signing Your Application page:
Warning: Keep your keystore and private key in a safe and secure place, and ensure that you have secure backups of them. If you publish an app to Google Play and then lose the key with which you signed your app, you will not be able to publish any updates to your app, since you must always sign all versions of your app with the same key.
After the first release of an APK, all subsequent releases must be signed with the exact same key.
No. This is not possible. The APK only contains public information, and not your private key information.
No. Even if you do find the original, you can't sign an APK with key A, then sign the next update with both keys A and B, then sign the next update after that with only key B.
Signing an APK (or any JAR file) with multiple keys is technically possible, but Google Play no longer accepts APKs with multiple signatures.
Attempting to do so will result in the message "Your APK has been signed with multiple certificates. Please only sign it with one certificate and upload it again."
You will have to build your app with a new application ID (e.g. change from "com.example.myapp" to "com.example.myapp2") and create a brand new listing on Google Play.
Possibly you will also have to change your code so that people can install the new app even if they have the old app installed, e.g. you need to make sure that you don't have conflicting content providers.
You will lose your existing install base, reviews etc., and will have to find a way to get your existing customers to uninstall the old app and install the new version.
Again, ensure you have secure backups of the keystore and password(s) you use for this version.
jsFiddle:http://jsfiddle.net/7Laf8/1302/
I hope this answers your question.
.wrapper {_x000D_
text-align: center;_x000D_
display: inline-block;_x000D_
position: absolute;_x000D_
top: 50%;_x000D_
left: 50%;_x000D_
}
_x000D_
<div class="wrapper">_x000D_
<button class="button">Hello</button>_x000D_
<button class="button">Another One</button>_x000D_
</div>
_x000D_
Supposing you use sql server:
WHERE StartTime BETWEEN DATEADD(HOUR, -1, GetDate())
AND DATEADD(HOUR, 1, GetDate())
This question is quite old but here goes anyway. If you're trying to get just the previous month and the day does not matter you can use this:
$date = '2014-01-03';
$dateTime = new DateTime($date);
$lastMonth = $dateTime->modify('-' . $dateTime->format('d') . ' days')->format('F Y');
echo $lastMonth; // 'December 2013'
override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
super.touchesBegan(touches, withEvent: event)
let touch : UITouch = touches.anyObject() as UITouch
if touch.view.isKindOfClass(UIPickerView)
{
}
}
Edit
As pointed out in @Kevin's answer, the correct way would be to use optional type cast operator as?
. You can read more about it on the section Optional Chaining
sub section Downcasting
.
Edit 2
As pointed on the other answer by user @KPM, using the is
operator is the right way to do it.
def quit(self):
self.root.destroy()
Add parentheses after destroy
to call the method.
When you use command=self.root.destroy
you pass the method to Tkinter.Button
without the parentheses because you want Tkinter.Button
to store the method for future calling, not to call it immediately when the button is created.
But when you define the quit
method, you need to call self.root.destroy()
in the body of the method because by then the method has been called.
def Range(*argSequence):
if len(argSequence) == 3:
imin = argSequence[0]; imax = argSequence[1]; di = argSequence[2]
i = imin; iList = []
while i <= imax:
iList.append(i)
i += di
return iList
if len(argSequence) == 2:
return Range(argSequence[0], argSequence[1], 1)
if len(argSequence) == 1:
return Range(1, argSequence[0], 1)
Please note the first letter of Range is capital. This naming method is not encouraged for functions in Python. You can change Range to something like drange or frange if you want. The "Range" function behaves just as you want it to. You can check it's manual here [ http://reference.wolfram.com/language/ref/Range.html ].
Sub Datainput()
'Checkbox values are 0 (false), 1 (true), 2 (changed or grey)
If activesheet.CheckBoxes("Check Box 1").value = 1 then
Msgbox ("Yay")
Else: Msgbox("Aww")
End if
End Sub
Thanks! This solved a similar problem I had with a data attribute inside a Div.
<div id="prop_sample" data-want="data I want">data I do not want</div>
Use this xpath: //*[@id="prop_sample"]/@data-want
Hope this helps someone else!
+----------------+-----------------------------+---------------------------+
| | val | var |
+----------------+-----------------------------+---------------------------+
| Reference type | Immutable(once initialized | Mutable(can able to change|
| | can't be reassigned) | value) |
+----------------+-----------------------------+---------------------------+
| Example | val n = 20 | var n = 20 |
+----------------+-----------------------------+---------------------------+
| In Java | final int n = 20; | int n = 20; |
+----------------+-----------------------------+---------------------------+
TensorFlow 2.3.0 works fine with CUDA 11. But you have to install tf-nightly-gpu (after you installed tensorflow and CUDA 11): https://pypi.org/project/tf-nightly-gpu/
Try:
pip install tf-nightly-gpu
Afterwards you'll get the message in your console:
I tensorflow/stream_executor/platform/default/dso_loader.cc:48] Successfully opened dynamic library cudart64_110.dll
Okay, A housemate took a look at it and figured it out:
func addCategory() {
var popoverContent = self.storyboard?.instantiateViewControllerWithIdentifier("NewCategory") as UIViewController
var nav = UINavigationController(rootViewController: popoverContent)
nav.modalPresentationStyle = UIModalPresentationStyle.Popover
var popover = nav.popoverPresentationController
popoverContent.preferredContentSize = CGSizeMake(500,600)
popover.delegate = self
popover.sourceView = self.view
popover.sourceRect = CGRectMake(100,100,0,0)
self.presentViewController(nav, animated: true, completion: nil)
}
That's the way.
You don't talk to the popover itself anymore, you talk to the view controller inside of it to set the content size, by calling the property preferredContentSize
i got very good results using a user function from http://php.net/manual/de/function.mime-content-type.php @''john dot howard at prismmg dot com 26-Oct-2009 03:43''
function get_mime_type($filename, $mimePath = '../etc') { ...
which doesnt use finfo, exec or deprecated function
works well also with remote ressources!
obj= Model.objects.filter(testfield=12).order_by('-id')[:1]
is the right solution
Add two jar in libs directory in your project. Follow below information. In particular, I think you need to:
I found this second step was necessary as I was hitting the exact same error as you when trying to use the sample code. The first step was necessary to avoid a NoClassDefFoundError in com.google.android.gms.R$styleable in my real project.
I also needed to do a Clean build and Uninstall the app from the device (from an earlier test attempt) before the sample code worked.
thanks your help very much.
This is how I accomplished reading a table in javascript. Basically I drilled down into the rows and then I was able to drill down into the individual cells for each row. This should give you an idea
//gets table
var oTable = document.getElementById('myTable');
//gets rows of table
var rowLength = oTable.rows.length;
//loops through rows
for (i = 0; i < rowLength; i++){
//gets cells of current row
var oCells = oTable.rows.item(i).cells;
//gets amount of cells of current row
var cellLength = oCells.length;
//loops through each cell in current row
for(var j = 0; j < cellLength; j++){
/* get your cell info here */
/* var cellVal = oCells.item(j).innerHTML; */
}
}
UPDATED - TESTED SCRIPT
<table id="myTable">
<tr>
<td>A1</td>
<td>A2</td>
<td>A3</td>
</tr>
<tr>
<td>B1</td>
<td>B2</td>
<td>B3</td>
</tr>
</table>
<script>
//gets table
var oTable = document.getElementById('myTable');
//gets rows of table
var rowLength = oTable.rows.length;
//loops through rows
for (i = 0; i < rowLength; i++){
//gets cells of current row
var oCells = oTable.rows.item(i).cells;
//gets amount of cells of current row
var cellLength = oCells.length;
//loops through each cell in current row
for(var j = 0; j < cellLength; j++){
// get your cell info here
var cellVal = oCells.item(j).innerHTML;
alert(cellVal);
}
}
</script>
If all other solutions did not work for your device try this guide how to make a truly universal adb and fastboot driver out of Google USB driver. The resulting driver works for adb
, recovery
and fastboot
modes in all versions of Windows.
You can go for identifying a list of elements with xPath:
//td[text() = ' Color Digest ']/following-sibling::td[1]
This will give you a list of two elements, than you can use the 2nd element as your intended one. For example:
List<WebElement> elements = driver.findElements(By.xpath("//td[text() = ' Color Digest ']/following-sibling::td[1]"))
Now, you can use the 2nd element as your intended element, which is elements.get(1)
To mark a lambda async, simply prepend async
before its argument list:
// Add a command to delete the current Group
contextMenu.Commands.Add(new UICommand("Delete this Group", async (contextMenuCmd) =>
{
SQLiteUtils slu = new SQLiteUtils();
await slu.DeleteGroupAsync(groupName);
}));
Implicit Wait
An implicit wait is to tell WebDriver to poll the DOM for a certain amount of time when trying to find an element or elements if they are not immediately available. The default setting is 0. Once set, the implicit wait is set for the life of the WebDriver object instance.
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
Explicit Wait + Expected Conditions
An explicit waits is code you define to wait for a certain condition to occur before proceeding further in the code. The worst case of this is Thread.sleep(), which sets the condition to an exact time period to wait. There are some convenience methods provided that help you write code that will wait only as long as required. WebDriverWait in combination with ExpectedCondition is one way this can be accomplished.
WebDriverWait wait = new WebDriverWait(driver, 10);
WebElement element = wait.until(
ExpectedConditions.visibilityOfElementLocated(By.id("someid")));
jQuery simple solution.
Should be triggered by user's click.
$("<textarea/>").appendTo("body").val(text).select().each(function () {
document.execCommand('copy');
}).remove();
Aggregated List of Libraries
Here's the version like the ggplot2 one I gave only in base R. I copied some from @nullglob.
generate the data
carrots <- rnorm(100000,5,2)
cukes <- rnorm(50000,7,2.5)
You don't need to put it into a data frame like with ggplot2. The drawback of this method is that you have to write out a lot more of the details of the plot. The advantage is that you have control over more details of the plot.
## calculate the density - don't plot yet
densCarrot <- density(carrots)
densCuke <- density(cukes)
## calculate the range of the graph
xlim <- range(densCuke$x,densCarrot$x)
ylim <- range(0,densCuke$y, densCarrot$y)
#pick the colours
carrotCol <- rgb(1,0,0,0.2)
cukeCol <- rgb(0,0,1,0.2)
## plot the carrots and set up most of the plot parameters
plot(densCarrot, xlim = xlim, ylim = ylim, xlab = 'Lengths',
main = 'Distribution of carrots and cucumbers',
panel.first = grid())
#put our density plots in
polygon(densCarrot, density = -1, col = carrotCol)
polygon(densCuke, density = -1, col = cukeCol)
## add a legend in the corner
legend('topleft',c('Carrots','Cucumbers'),
fill = c(carrotCol, cukeCol), bty = 'n',
border = NA)
For those who found this page looking for a way to do this in IAR, try this:
#pragma diag_suppress=Pe177
void foo1( void )
{
/* The following line of code would normally provoke diagnostic
message #177-D: variable "x" was declared but never referenced.
Instead, we have suppressed this warning throughout the entire
scope of foo1().
*/
int x;
}
#pragma diag_default=Pe177
See http://infocenter.arm.com/help/index.jsp?topic=/com.arm.doc.dui0472m/chr1359124244797.html for reference.
this questions is linked with the question How to write binary data file on C and plot it using Gnuplot by CAMILO HG. I know that the real problem have two parts: 1) Write the binary data file, 2) Plot it using Gnuplot.
The first part has been very clearly answered here, so I do not have something to add.
For the second, the easy way is send the people to the Gnuplot manual, and I sure someone find a good answer, but I do not find it in the web, so I am going to explain one solution (which must be in the real question, but I new in stackoverflow and I can not answer there):
After write your binary data file using fwrite()
, you should create a very simple program in C, a reader. The reader only contains the same structure as the writer, but you use fread()
instead fwrite()
. So it is very ease to generate this program: copy in the reader.c
file the writing part of your original code and change write for read (and "wb" for "rb"). In addition, you could include some checks for the data, for example, if the length of the file is correct. And finally, your program need to print the data in the standard output using a printf()
.
For be clear: your program run like this
$ ./reader data.dat
X_position Y_position (it must be a comment for Gnuplot)*
1.23 2.45
2.54 3.12
5.98 9.52
Okey, with this program, in Gnuplot you only need to pipe the standard output of the reader to the Gnuplot, something like this:
plot '< ./reader data.dat'
This line, run the program reader, and the output is connected with Gnuplot and it plot the data.
*Because Gnuplot is going to read the output of the program, you must know what can Gnuplot read and plot and what can not.
There could be a potential problem that leads to the StaleElementReferenceException that no one mentioned so far (in regard to actions).
I explain it in Javascript, but it's the same in Java.
This won't work:
let actions = driver.actions({ bridge: true })
let a = await driver.findElement(By.css('#a'))
await actions.click(a).perform() // this leads to a DOM change, #b will be removed and added again to the DOM.
let b = await driver.findElement(By.css('#b'))
await actions.click(b).perform()
But instantiating the actions again will solve it:
let actions = driver.actions({ bridge: true })
let a = await driver.findElement(By.css('#a'))
await actions.click(a).perform() // this leads to a DOM change, #b will be removed and added again to the DOM.
actions = driver.actions({ bridge: true }) // new
let b = await driver.findElement(By.css('#b'))
await actions.click(b).perform()
Thank you drifty0pine!
The first solution, it´s works!
[a relative link](../../some/dir/filename.md)
[Link to file in another dir on same drive](/another/dir/filename.md)
[Link to file in another dir on a different drive](/D:/dir/filename.md)
but I had need put more ../
until the folder where was my file, like this:
[FileToOpen](../../../../folderW/folderX/folderY/folderZ/FileToOpen.txt)
Correct me if I'm wrong (I'm not), but the offset from UTC changes with daylight saving time. So you should use
tz = str.format('{0:+06.2f}', float(time.altzone) / 3600)
I also believe that the sign should be different:
tz = str.format('{0:+06.2f}', -float(time.altzone) / 3600)
I could be wrong, but I don't think so.
For those that are not familiar:
sudo chown -R YOUR_COMPUTER_USER_NAME PATH_OF_FILE
sprintf() is designed to handle far more than just strings, strcat() is specialist. But I suspect that you are sweating the small stuff. C strings are fundamentally inefficient in ways that make the differences between these two proposed methods insignificant. Read "Back to Basics" by Joel Spolsky for the gory details.
This is an instance where C++ generally performs better than C. For heavy weight string handling using std::string is likely to be more efficient and certainly safer.
[edit]
[2nd edit]Corrected code (too many iterations in C string implementation), timings, and conclusion change accordingly
I was surprised at Andrew Bainbridge's comment that std::string was slower, but he did not post complete code for this test case. I modified his (automating the timing) and added a std::string test. The test was on VC++ 2008 (native code) with default "Release" options (i.e. optimised), Athlon dual core, 2.6GHz. Results:
C string handling = 0.023000 seconds
sprintf = 0.313000 seconds
std::string = 0.500000 seconds
So here strcat() is faster by far (your milage may vary depending on compiler and options), despite the inherent inefficiency of the C string convention, and supports my original suggestion that sprintf() carries a lot of baggage not required for this purpose. It remains by far the least readable and safe however, so when performance is not critical, has little merit IMO.
I also tested a std::stringstream implementation, which was far slower again, but for complex string formatting still has merit.
Corrected code follows:
#include <ctime>
#include <cstdio>
#include <cstring>
#include <string>
void a(char *first, char *second, char *both)
{
for (int i = 0; i != 1000000; i++)
{
strcpy(both, first);
strcat(both, " ");
strcat(both, second);
}
}
void b(char *first, char *second, char *both)
{
for (int i = 0; i != 1000000; i++)
sprintf(both, "%s %s", first, second);
}
void c(char *first, char *second, char *both)
{
std::string first_s(first) ;
std::string second_s(second) ;
std::string both_s(second) ;
for (int i = 0; i != 1000000; i++)
both_s = first_s + " " + second_s ;
}
int main(void)
{
char* first= "First";
char* second = "Second";
char* both = (char*) malloc((strlen(first) + strlen(second) + 2) * sizeof(char));
clock_t start ;
start = clock() ;
a(first, second, both);
printf( "C string handling = %f seconds\n", (float)(clock() - start)/CLOCKS_PER_SEC) ;
start = clock() ;
b(first, second, both);
printf( "sprintf = %f seconds\n", (float)(clock() - start)/CLOCKS_PER_SEC) ;
start = clock() ;
c(first, second, both);
printf( "std::string = %f seconds\n", (float)(clock() - start)/CLOCKS_PER_SEC) ;
return 0;
}
If you create your own adapter, there is one notable abstract function:
public void registerDataSetObserver(DataSetObserver observer) {
...
}
You can use the given observers to notify the system to update:
private ArrayList<DataSetObserver> observers = new ArrayList<DataSetObserver>();
public void registerDataSetObserver(DataSetObserver observer) {
observers.add(observer);
}
public void notifyDataSetChanged(){
for (DataSetObserver observer: observers) {
observer.onChanged();
}
}
Though aren't you glad there are things like the SimpleAdapter and ArrayAdapter and you don't have to do all that?
Set that particular column's Visible
property = false
dataGridView[ColumnName or Index].Visible = false;
Edit
sorry missed the Columns
Property
dataGridView.Columns[ColumnName or Index].Visible = false;
It's creating a size 0
bitfield if the condition is false, but a size -1
(-!!1
) bitfield if the condition is true/non-zero. In the former case, there is no error and the struct is initialized with an int member. In the latter case, there is a compile error (and no such thing as a size -1
bitfield is created, of course).
Working with Windows environment variables is always a horrible experience. Recently, I found an amazing tool called Rapid Environment Editor, which gives an awesomely simple GUI for managing them.
If you use chocolatey, you can install it using choco install rapidee
. Otherwise, take a look at http://www.rapidee.com/en/download
Re-reading this, it sounds like a paid shill, but I swear I'm not! It's just been one of the most useful utilities in my toolkit for a while and I'm surprised no one seems to know about it.
The problem is likely that you are calling URLEncoder.encode() on something that already is a URI.
You can use block (/***/) or single line comment (//) for each line. You should use "#" in sh command.
Block comment
/* _x000D_
post {_x000D_
success {_x000D_
mail to: "[email protected]", _x000D_
subject:"SUCCESS: ${currentBuild.fullDisplayName}", _x000D_
body: "Yay, we passed."_x000D_
}_x000D_
failure {_x000D_
mail to: "[email protected]", _x000D_
subject:"FAILURE: ${currentBuild.fullDisplayName}", _x000D_
body: "Boo, we failed."_x000D_
}_x000D_
}_x000D_
*/
_x000D_
Single Line
// post {_x000D_
// success {_x000D_
// mail to: "[email protected]", _x000D_
// subject:"SUCCESS: ${currentBuild.fullDisplayName}", _x000D_
// body: "Yay, we passed."_x000D_
// }_x000D_
// failure {_x000D_
// mail to: "[email protected]", _x000D_
// subject:"FAILURE: ${currentBuild.fullDisplayName}", _x000D_
// body: "Boo, we failed."_x000D_
// }_x000D_
// }
_x000D_
Comment in 'sh' command
stage('Unit Test') {_x000D_
steps {_x000D_
ansiColor('xterm'){_x000D_
sh '''_x000D_
npm test_x000D_
# this is a comment in sh_x000D_
'''_x000D_
}_x000D_
}_x000D_
}
_x000D_
The procedure shown at http://off-topic.biz/en/eclipse-hangs-at-startup-showing-only-the-splash-screen/ worked for me:
In other answers:
eclipse -clean -clearPersistedState
is mentioned - which seems to have the same or even better effect.
Here is a script for MacOS (using Macports) and Linux (tested on Ubuntu with Eclipse Equinox) to do the start with an an optional kill of the running eclipse. You might want to adapt the script to your needs. If you add new platforms please edit the script right in this answer.
#!/bin/bash
# WF 2014-03-14
#
# ceclipse:
# start Eclipse cleanly
#
# this script calls eclipse with -clean and -clearPersistedState
# if an instance of eclipse is already running the user is asked
# if it should be killed first and if answered yes the process will be killed
#
# usage: ceclipse
#
#
# error
#
# show an error message and exit
#
# params:
# 1: l_msg - the message to display
error() {
local l_msg="$1"
echo "error: $l_msg" 1>&2
exit 1
}
#
# autoinstall
#
# check that l_prog is available by calling which
# if not available install from given package depending on Operating system
#
# params:
# 1: l_prog: The program that shall be checked
# 2: l_linuxpackage: The apt-package to install from
# 3: l_macospackage: The MacPorts package to install from
#
autoinstall() {
local l_prog=$1
local l_linuxpackage=$2
local l_macospackage=$3
echo "checking that $l_prog is installed on os $os ..."
which $l_prog
if [ $? -eq 1 ]
then
case $os in
# Mac OS
Darwin)
echo "installing $l_prog from MacPorts package $l_macospackage"
sudo port install $l_macospackage
;;
# e.g. Ubuntu/Fedora/Debian/Suse
Linux)
echo "installing $l_prog from apt-package $l_linuxpackage"
sudo apt-get install $l_linuxpackage
;;
# git bash (Windows)
MINGW32_NT-6.1)
error "$l_prog ist not installed"
;;
*)
error "unknown operating system $os"
esac
fi
}
# global operating system variable
os=`uname`
# first set
# eclipse_proc - the name of the eclipse process to look for
# eclipse_app - the name of the eclipse application to start
case $os in
# Mac OS
Darwin)
eclipse_proc="Eclipse.app"
eclipse_app="/Applications/eclipse/Eclipse.app/Contents/MacOS/eclipse"
;;
# e.g. Ubuntu/Fedora/Debian/Suse
Linux)
eclipse_proc="/usr/lib/eclipse//plugins/org.eclipse.equinox.launcher_1.2.0.dist.jar"
eclipse_app=`which eclipse`
;;
# git bash (Windows)
MINGW32_NT-6.1)
eclipse_app=`which eclipse`
error "$os not implemented yet"
;;
*)
error "unknown operating system $os"
esac
# check that pgrep is installed or install it
autoinstall pgrep procps
# check whether eclipse process is running
# first check that we only find one process
echo "looking for $eclipse_proc process"
pgrep -fl "$eclipse_proc"
# can't use -c option on MacOS - use platform independent approach
#eclipse_count=`pgrep -cfl "$eclipse_proc"`
eclipse_count=`pgrep -fl "$eclipse_proc" | wc -l | tr -d ' '`
# check how many processes matched
case $eclipse_count in
# no eclipse - do nothing
0) ;;
# exactly one - offer to kill it
1)
echo "Eclipse is running - shall i kill and restart it with -clean? y/n?"
read answer
case $answer in
y|Y) ;;
*) error "aborted ..." ;;
esac
echo "killing current $eclipse_proc"
pkill -f "$eclipse_proc"
;;
# multiple - this is bogus
*) error "$eclipse_count processes matching $eclipse_proc found - please adapt $0";;
esac
tmp=/tmp/eclipse$$
echo "starting eclipse cleanly ... using $tmp for nohup.out"
mkdir -p $tmp
cd $tmp
# start eclipse with clean options
nohup $eclipse_app -clean -clearPersistedState&
If you're using mongoid, the document-to-object wrapper, you can do the following in Ruby. (Assuming your model is User)
User.all.to_a[rand(User.count)]
In my .irbrc, I have
def rando klass
klass.all.to_a[rand(klass.count)]
end
so in rails console, I can do, for example,
rando User
rando Article
to get documents randomly from any collection.
I wanted a solution for Gnu sort on Windows, but none of the above solutions worked for me on the command line.
Using Lloyd's clue, the following batch file (.bat) worked for me.
Type the tab character within the double quotes.
C:\>cat foo.bat
sort -k3 -t" " tabfile.txt
That's not a jQuery function - it's the regular Array.join function.
It converts an array to a string, putting the argument between each element.
Have a look at jQuery, a cross-browser library that will make your life a lot easier.
var msg = 'abc';
$('#msg').val(msg);
$('#sp_100').attr('checked', 'checked');
The UnsupportedClassVersionError
means that you are probably using (installed) an older version of Java as used to create the JAR.
Go to java.sun.com page, download and install a newer JRE (Java Runtime Environment).
if you want/need to develop with Java, you will need the JDK which includes the JRE.
Check your home folder ~/.gradle/gradle.properties
. Sometimes if you have gradle.properties
in home directory it takes details from the there. Either you can change that or delete the files. Then it will take required details from your local folder.
I just had the same issue with Netbeans 8.2 and trying to connect to mySQL server on a Mac OS machine. The only thing that worked for me was to add the following to the url of the connection string: &serverTimezone=UTC (or if you are connecting via Hibernate.cfg.xml then escape the & as &) Not surprisingly I found the solution on this stack overflow post also:
MySQL JDBC Driver 5.1.33 - Time Zone Issue
Best Regards, Claudio
If you're looking for lightweight and are already familiar with django-style declarative models, check out peewee: https://github.com/coleifer/peewee
Example:
import datetime
from peewee import *
class Blog(Model):
name = CharField()
class Entry(Model):
blog = ForeignKeyField(Blog)
title = CharField()
body = TextField()
pub_date = DateTimeField(default=datetime.datetime.now)
# query it like django
Entry.filter(blog__name='Some great blog')
# or programmatically for finer-grained control
Entry.select().join(Blog).where(Blog.name == 'Some awesome blog')
Check the docs for more examples.
If you dont want to hard-code the cell addresses you can use the ROW()
function.
eg: =AVERAGE(INDIRECT("A" & ROW()), INDIRECT("C" & ROW()))
Its probably not the best way to do it though! Using Auto-Fill and static columns like @JaiGovindani suggests would be much better.
You can find <div>
by id
, look at it's style.display
property and toggle it from none
to block
and vice versa.
function showDiv(Div) {_x000D_
var x = document.getElementById(Div);_x000D_
if(x.style.display=="none") {_x000D_
x.style.display = "block";_x000D_
} else {_x000D_
x.style.display = "none";_x000D_
}_x000D_
}
_x000D_
<div id="welcomeDiv" style="display:none;" class="answer_list">WELCOME</div>_x000D_
<input type="button" name="answer" value="Show Div" onclick="showDiv('welcomeDiv')" />
_x000D_
UPDATE: Turned my solution into a stand-alone python script.
This solution has saved me more than once. Hopefully others find it useful. This python script will find any jupyter kernel using more than cpu_threshold
CPU and prompts the user to send a SIGINT
to the kernel (KeyboardInterrupt). It will keep sending SIGINT
until the kernel's cpu usage goes below cpu_threshold
. If there are multiple misbehaving kernels it will prompt the user to interrupt each of them (ordered by highest CPU usage to lowest). A big thanks goes to gcbeltramini for writing code to find the name of a jupyter kernel using the jupyter api. This script was tested on MACOS with python3 and requires jupyter notebook, requests, json and psutil.
Put the script in your home directory and then usage looks like:
python ~/interrupt_bad_kernels.py
Interrupt kernel chews cpu.ipynb; PID: 57588; CPU: 2.3%? (y/n) y
Script code below:
from os import getpid, kill
from time import sleep
import re
import signal
from notebook.notebookapp import list_running_servers
from requests import get
from requests.compat import urljoin
import ipykernel
import json
import psutil
def get_active_kernels(cpu_threshold):
"""Get a list of active jupyter kernels."""
active_kernels = []
pids = psutil.pids()
my_pid = getpid()
for pid in pids:
if pid == my_pid:
continue
try:
p = psutil.Process(pid)
cmd = p.cmdline()
for arg in cmd:
if arg.count('ipykernel'):
cpu = p.cpu_percent(interval=0.1)
if cpu > cpu_threshold:
active_kernels.append((cpu, pid, cmd))
except psutil.AccessDenied:
continue
return active_kernels
def interrupt_bad_notebooks(cpu_threshold=0.2):
"""Interrupt active jupyter kernels. Prompts the user for each kernel."""
active_kernels = sorted(get_active_kernels(cpu_threshold), reverse=True)
servers = list_running_servers()
for ss in servers:
response = get(urljoin(ss['url'].replace('localhost', '127.0.0.1'), 'api/sessions'),
params={'token': ss.get('token', '')})
for nn in json.loads(response.text):
for kernel in active_kernels:
for arg in kernel[-1]:
if arg.count(nn['kernel']['id']):
pid = kernel[1]
cpu = kernel[0]
interrupt = input(
'Interrupt kernel {}; PID: {}; CPU: {}%? (y/n) '.format(nn['notebook']['path'], pid, cpu))
if interrupt.lower() == 'y':
p = psutil.Process(pid)
while p.cpu_percent(interval=0.1) > cpu_threshold:
kill(pid, signal.SIGINT)
sleep(0.5)
if __name__ == '__main__':
interrupt_bad_notebooks()
this modified code should work
p = ggplot(mydataf, aes(x = foo)) +
geom_bar(aes(y = (..count..)/sum(..count..))) +
scale_y_continuous(formatter = 'percent')
if your data has NAs and you dont want them to be included in the plot, pass na.omit(mydataf) as the argument to ggplot.
hope this helps.
The != operator most certainly does exist! It is an alias for the standard <>
operator.
Perhaps your fields are not actually empty strings, but instead NULL
?
To compare to NULL
you can use IS NULL
or IS NOT NULL
or the null safe equals operator <=>
.
For example, You have next things:
A link to open your app: http://example.com
The package name of your app: com.example.mypackage
Then you need to do next:
Add an intent filter to your Activity (Can be any activity you want. For more info check the documentation).
<activity
android:name=".MainActivity">
<intent-filter android:label="@string/filter_title_view_app_from_web">
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<!-- Accepts URIs that begin with "http://example.com" -->
<data
android:host="example.com"
android:scheme="http" />
</intent-filter>
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
Create a HTML file to test the link or use this methods.
Open your Activity directly (just open your Activity, without a choosing dialog).
Open this link with browser or your programm (by choosing dialog).
Use Mobile Chrome to test
That's it.
And its not necessary to publish app in market to test deep linking =)
Also, for more information, check documentation and useful presentation.
You could just do a simple extension like:
import UIKit
// MARK: - Mixed string utils and helpers
extension String {
/**
Encode a String to Base64
:returns:
*/
func toBase64()->String{
let data = self.dataUsingEncoding(NSUTF8StringEncoding)
return data!.base64EncodedStringWithOptions(NSDataBase64EncodingOptions(rawValue: 0))
}
}
iOS 7 and up
Just be aware that on Unix/Linux your username/password can be seen by anyone that can run "ps -ef" command if you place it directly on the command line . Could be a big security issue (or turn into a big security issue).
I usually recommend creating a file or using here document so you can protect the username/password from being viewed with "ps -ef" command in Unix/Linux. If the username/password is contained in a script file or sql file you can protect using appropriate user/group read permissions. Then you can keep the user/pass inside the file like this in a shell script:
sqlplus -s /nolog <<EOF
connect user/pass
select blah;
quit
EOF
If you does not want to use an extra view just for underlines. Add this style on your textView
.
style="?android:listSeparatorTextViewStyle"
Just down side is it will add extra properties like
android:textStyle="bold"
android:textAllCaps="true"
which you can easily override.
Put this in an initializer
class Hash
def filter(*args)
return nil if args.try(:empty?)
if args.size == 1
args[0] = args[0].to_s if args[0].is_a?(Symbol)
self.select {|key| key.to_s.match(args.first) }
else
self.select {|key| args.include?(key)}
end
end
end
Then you can do
{a: "1", b: "b", c: "c", d: "d"}.filter(:a, :b) # => {a: "1", b: "b"}
or
{a: "1", b: "b", c: "c", d: "d"}.filter(/^a/) # => {a: "1"}
Have the element display as a block:
display: block;
The two above it is not run.
The table edit button:
<a data-toggle="modal" type="edit" id="{{$b->id}}" data-id="{{$b->id}}" data-target="#form_edit_masterbank" data-bank_nama="{{ $b->bank_nama }}" data-bank_accnama="{{ $b->bank_accnama }}" data-bank_accnum="{{ $b->bank_accnum }}" data-active="{{ $b->active }}" data-logobank="{{asset('components/images/user/masterbank/')}}/{{$b->images}}" href="#" class="edit edit-masterbank" ><i class="fa fa-edit" ></i></a>
and then in JavaScript:
$('.imagepreview555').attr('src', logobank);
and then in HTML:
<img src="" class="imagepreview555" style="width: 100%;" />
Not it runs.
run the following
/usr/local/tomcat/bin/catalina.sh version
its response will be something like:
Using CATALINA_BASE: /usr/local/tomcat
Using CATALINA_HOME: /usr/local/tomcat
Using CATALINA_TMPDIR: /var/tmp/
Using JRE_HOME: /usr
Using CLASSPATH: /usr/local/tomcat/bin/bootstrap.jar:/usr/local/tomcat/bin/tomcat-juli.jar
Using CATALINA_PID: /var/catalina.pid
Server version: Apache Tomcat/7.0.30
Server built: Sep 27 2012 05:13:37
Server number: 7.0.30.0
OS Name: Linux
OS Version: 2.6.32-504.3.3.el6.x86_64
Architecture: amd64
JVM Version: 1.7.0_60-b19
JVM Vendor: Oracle Corporation
=ROUND((TODAY()-A1)/365,0)
will provide number of years between date in cell A1 and today's date
Is this what you're looking for?
if (request instanceof HttpServletRequest) {
String url = ((HttpServletRequest)request).getRequestURL().toString();
String queryString = ((HttpServletRequest)request).getQueryString();
}
To Reconstruct:
System.out.println(url + "?" + queryString);
Info on HttpServletRequest.getRequestURL()
and HttpServletRequest.getQueryString()
.
I got the same error.
On my view I was overriding get_form_kwargs() like this:
class UserAccountView(FormView):
form_class = UserAccountForm
success_url = '/'
template_name = 'user_account/user-account.html'
def get_form_kwargs(self):
kwargs = super(UserAccountView, self).get_form_kwargs()
kwargs.update({'user': self.request.user})
return kwargs
But on my form I failed to override the init() method. Once I did it. Problem solved
class UserAccountForm(forms.Form):
first_name = forms.CharField(label='Your first name', max_length=30)
last_name = forms.CharField(label='Your last name', max_length=30)
email = forms.EmailField(max_length=75)
def __init__(self, *args, **kwargs):
user = kwargs.pop('user')
super(UserAccountForm, self).__init__(*args, **kwargs)
If you need a Unix timestamp from a shell script (Bourne family: sh, ksh, bash, zsh, ...), this should work on any Unix machine as unlike the other suggestions (perl, haskell, ruby, python, GNU date), it is based on a POSIX standard command and feature.
PATH=`getconf PATH` awk 'BEGIN {srand();print srand()}'
To convert a string to a stream you need to decide which encoding the bytes in the stream should have to represent that string - for example you can:
MemoryStream mStrm= new MemoryStream( Encoding.UTF8.GetBytes( contents ) );
MSDN references:
you can put everything in a block and easily write any code that you wish in that block just exactly the below code :
@{
bool isUserConnected = string.IsNullOrEmpty(Model.CreatorFullName);
if (isUserConnected)
{ // meaning that the viewing user has not been saved
<div>
<div> click to join us </div>
<a id="login" href="javascript:void(0);" style="display: inline; ">join</a>
</div>
}
}
it helps you to have at first a cleaner code and also you can prevent your page from loading many times different blocks of codes
I am sure that you probably wanted the answer that @GSerg gave. There is also a worksheet function called rows
that will give you the number of rows.
So, if you have a named data range called Data
that has 7 rows, then =ROWS(Data)
will show 7 in that cell.
May be this is alltime multiple connection open issue, you are somewhere in your code opening connections and not closing them properly. use
using (SqlConnection con = new SqlConnection(connectionString))
{
con.Open();
}
Refer this article: http://msdn.microsoft.com/en-us/library/ms254507(v=vs.80).aspx, The Using block in Visual Basic or C# automatically disposes of the connection when the code exits the block, even in the case of an unhandled exception.
I had to use a HTTP connection, because on HTTPS there is default file size limit.
curl -i -X 'POST' -F 'file=@/home/testeincremental.xlsx' 'http://example.com/upload.aspx?user=example&password=example123&type=XLSX'
This happened to me when deleting some Equinox package from my plugins
directory, make sure this is not the case.
The three best way to do it using a single line of code
import cv2
import numpy as np
img = cv2.imread('Imgs/Saint_Roch_new/data/Point_4_Face.jpg')
dim = (256, 256)
resizedLena = cv2.resize(img, dim, interpolation = cv2.INTER_LINEAR)
X, Y = resizedLena, resizedLena
# Methode 1: Using Numpy (hstack, vstack)
Fusion_Horizontal = np.hstack((resizedLena, Y, X))
Fusion_Vertical = np.vstack((newIMG, X))
cv2.imshow('Fusion_Vertical using vstack', Fusion_Vertical)
cv2.waitKey(0)
# Methode 2: Using Numpy (contanate)
Fusion_Vertical = np.concatenate((resizedLena, X, Y), axis=0)
Fusion_Horizontal = np.concatenate((resizedLena, X, Y), axis=1)
cv2.imshow("Fusion_Horizontal usung concatenate", Fusion_Horizontal)
cv2.waitKey(0)
# Methode 3: Using OpenCV (vconcat, hconcat)
Fusion_Vertical = cv2.vconcat([resizedLena, X, Y])
Fusion_Horizontal = cv2.hconcat([resizedLena, X, Y])
cv2.imshow("Fusion_Horizontal Using hconcat", Fusion_Horizontal)
cv2.waitKey(0)
For the following steps worked in my case:
1 On eclipse, right click on the desired project Maven -> Disable Maven Nature
2 Right click again then go to Properties. Delete every evidence of external Maven dependency leaving only JRE System Library.
3 Right click one more time on the project then go to Configure -> Convert to Maven Project
it worked for me also
Use two single-quotes
SQL> SELECT 'D''COSTA' name FROM DUAL;
NAME
-------
D'COSTA
Alternatively, use the new (10g+) quoting method:
SQL> SELECT q'$D'COSTA$' NAME FROM DUAL;
NAME
-------
D'COSTA
This is absolutely possible. Although you shouldn't do it unless you know what you are dealing with. Took me about 2 days to figure it out. Here is a stored procedure where i enter: ---database name (schema name is "_" for readability) ---table name ---column ---column data type (column added is always null, otherwise you won't be able to insert) ---the position of the new column.
Since I'm working with tables from SAM toolkit (and some of them have > 80 columns) , the typical variable won't be able to contain the query. That forces the need of external file. Now be careful where you store that file and who has access on NTFS and network level.
Cheers!
USE [master]
GO
/****** Object: StoredProcedure [SP_Set].[TrasferDataAtColumnLevel] Script Date: 8/27/2014 2:59:30 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [SP_Set].[TrasferDataAtColumnLevel]
(
@database varchar(100),
@table varchar(100),
@column varchar(100),
@position int,
@datatype varchar(20)
)
AS
BEGIN
set nocount on
exec ('
declare @oldC varchar(200), @oldCDataType varchar(200), @oldCLen int,@oldCPos int
create table Test ( dummy int)
declare @columns varchar(max) = ''''
declare @columnVars varchar(max) = ''''
declare @columnsDecl varchar(max) = ''''
declare @printVars varchar(max) = ''''
DECLARE MY_CURSOR CURSOR LOCAL STATIC READ_ONLY FORWARD_ONLY FOR
select column_name, data_type, character_maximum_length, ORDINAL_POSITION from ' + @database + '.INFORMATION_SCHEMA.COLUMNS where table_name = ''' + @table + '''
OPEN MY_CURSOR FETCH NEXT FROM MY_CURSOR INTO @oldC, @oldCDataType, @oldCLen, @oldCPos WHILE @@FETCH_STATUS = 0 BEGIN
if(@oldCPos = ' + @position + ')
begin
exec(''alter table Test add [' + @column + '] ' + @datatype + ' null'')
end
if(@oldCDataType != ''timestamp'')
begin
set @columns += @oldC + '' , ''
set @columnVars += ''@'' + @oldC + '' , ''
if(@oldCLen is null)
begin
if(@oldCDataType != ''uniqueidentifier'')
begin
set @printVars += '' print convert('' + @oldCDataType + '',@'' + @oldC + '')''
set @columnsDecl += ''@'' + @oldC + '' '' + @oldCDataType + '', ''
exec(''alter table Test add ['' + @oldC + ''] '' + @oldCDataType + '' null'')
end
else
begin
set @printVars += '' print convert(varchar(50),@'' + @oldC + '')''
set @columnsDecl += ''@'' + @oldC + '' '' + @oldCDataType + '', ''
exec(''alter table Test add ['' + @oldC + ''] '' + @oldCDataType + '' null'')
end
end
else
begin
if(@oldCLen < 0)
begin
set @oldCLen = 4000
end
set @printVars += '' print @'' + @oldC
set @columnsDecl += ''@'' + @oldC + '' '' + @oldCDataType + ''('' + convert(character,@oldCLen) + '') , ''
exec(''alter table Test add ['' + @oldC + ''] '' + @oldCDataType + ''('' + @oldCLen + '') null'')
end
end
if exists (select column_name from INFORMATION_SCHEMA.COLUMNS where table_name = ''Test'' and column_name = ''dummy'')
begin
alter table Test drop column dummy
end
FETCH NEXT FROM MY_CURSOR INTO @oldC, @oldCDataType, @oldCLen, @oldCPos END CLOSE MY_CURSOR DEALLOCATE MY_CURSOR
set @columns = reverse(substring(reverse(@columns), charindex('','',reverse(@columns)) +1, len(@columns)))
set @columnVars = reverse(substring(reverse(@columnVars), charindex('','',reverse(@columnVars)) +1, len(@columnVars)))
set @columnsDecl = reverse(substring(reverse(@columnsDecl), charindex('','',reverse(@columnsDecl)) +1, len(@columnsDecl)))
set @columns = replace(replace(REPLACE(@columns, '' '', ''''), char(9) + char(9),'' ''), char(9), '''')
set @columnVars = replace(replace(REPLACE(@columnVars, '' '', ''''), char(9) + char(9),'' ''), char(9), '''')
set @columnsDecl = replace(replace(REPLACE(@columnsDecl, '' '', ''''), char(9) + char(9),'' ''),char(9), '''')
set @printVars = REVERSE(substring(reverse(@printVars), charindex(''+'',reverse(@printVars))+1, len(@printVars)))
create table query (id int identity(1,1), string varchar(max))
insert into query values (''declare '' + @columnsDecl + ''
DECLARE MY_CURSOR CURSOR LOCAL STATIC READ_ONLY FORWARD_ONLY FOR '')
insert into query values (''select '' + @columns + '' from ' + @database + '._.' + @table + ''')
insert into query values (''OPEN MY_CURSOR FETCH NEXT FROM MY_CURSOR INTO '' + @columnVars + '' WHILE @@FETCH_STATUS = 0 BEGIN '')
insert into query values (@printVars )
insert into query values ( '' insert into Test ('')
insert into query values (@columns)
insert into query values ( '') values ( '' + @columnVars + '')'')
insert into query values (''FETCH NEXT FROM MY_CURSOR INTO '' + @columnVars + '' END CLOSE MY_CURSOR DEALLOCATE MY_CURSOR'')
declare @path varchar(100) = ''C:\query.sql''
declare @query varchar(500) = ''bcp "select string from query order by id" queryout '' + @path + '' -t, -c -S '' + @@servername + '' -T''
exec master..xp_cmdshell @query
set @query = ''sqlcmd -S '' + @@servername + '' -i '' + @path
EXEC xp_cmdshell @query
set @query = ''del '' + @path
exec xp_cmdshell @query
drop table ' + @database + '._.' + @table + '
select * into ' + @database + '._.' + @table + ' from Test
drop table query
drop table Test ')
END
https://golang.org/src/time/format.go specified
For parsing time 15
is used for Hours, 04
is used for minutes, 05
for seconds.
For parsing Date 11
, Jan
, January
is for months, 02
, Mon
, Monday
for Day of the month, 2006
for year and of course MST
for zone
But you can use this layout as well, which I find very simple. "Mon Jan 2 15:04:05 MST 2006"
const layout = "Mon Jan 2 15:04:05 MST 2006"
userTimeString := "Fri Dec 6 13:05:05 CET 2019"
t, _ := time.Parse(layout, userTimeString)
fmt.Println("Server: ", t.Format(time.RFC850))
//Server: Friday, 06-Dec-19 13:05:05 CET
mumbai, _ := time.LoadLocation("Asia/Kolkata")
mumbaiTime := t.In(mumbai)
fmt.Println("Mumbai: ", mumbaiTime.Format(time.RFC850))
//Mumbai: Friday, 06-Dec-19 18:35:05 IST
IMPORTANT
Starting from Java 9 you cannot longer use reflection unless the package-info.java opens the module to reflection access.
By default reflection access to all packages in the module is denied.
I know this is a late answer but this works for me:
TimeSpan dateDifference = new TimeSpan(0,0,0, (int)endTime.Subtract(beginTime).TotalSeconds);
dateDifference should now exclude the parts smaller than a second. Works in .net 2.0 too.
You can look into the regex module (the fuzzy section). I don't know if you can get the actual differences, but at least you can specify allowed number of different types of changes like insert, delete, and substitutions:
import regex
sequence = 'afrykanerskojezyczny'
queries = [ 'afrykanerskojezycznym', 'afrykanerskojezyczni',
'nieafrykanerskojezyczni' ]
for q in queries:
m = regex.search(r'(%s){e<=2}'%q, sequence)
print 'match' if m else 'nomatch'
Grouped boxplots, towards subtle academic publication styling... (source)
(Left) Python 2.7.12 Matplotlib v1.5.3. (Right) Python 3.7.3. Matplotlib v3.1.0.
Code:
import numpy as np
import matplotlib.pyplot as plt
# --- Your data, e.g. results per algorithm:
data1 = [5,5,4,3,3,5]
data2 = [6,6,4,6,8,5]
data3 = [7,8,4,5,8,2]
data4 = [6,9,3,6,8,4]
# --- Combining your data:
data_group1 = [data1, data2]
data_group2 = [data3, data4]
# --- Labels for your data:
labels_list = ['a','b']
xlocations = range(len(data_group1))
width = 0.3
symbol = 'r+'
ymin = 0
ymax = 10
ax = plt.gca()
ax.set_ylim(ymin,ymax)
ax.set_xticklabels( labels_list, rotation=0 )
ax.grid(True, linestyle='dotted')
ax.set_axisbelow(True)
ax.set_xticks(xlocations)
plt.xlabel('X axis label')
plt.ylabel('Y axis label')
plt.title('title')
# --- Offset the positions per group:
positions_group1 = [x-(width+0.01) for x in xlocations]
positions_group2 = xlocations
plt.boxplot(data_group1,
sym=symbol,
labels=['']*len(labels_list),
positions=positions_group1,
widths=width,
# notch=False,
# vert=True,
# whis=1.5,
# bootstrap=None,
# usermedians=None,
# conf_intervals=None,
# patch_artist=False,
)
plt.boxplot(data_group2,
labels=labels_list,
sym=symbol,
positions=positions_group2,
widths=width,
# notch=False,
# vert=True,
# whis=1.5,
# bootstrap=None,
# usermedians=None,
# conf_intervals=None,
# patch_artist=False,
)
plt.savefig('boxplot_grouped.png')
plt.savefig('boxplot_grouped.pdf') # when publishing, use high quality PDFs
#plt.show() # uncomment to show the plot.
As you might be aware of, Maven is a build automation tool provided by Apache which does more than dependency management. We can make it as a peer of Ant and Makefile which downloads all of the dependencies required.
On a mvn install
, it frames a dependency tree based on the project configuration pom.xml
on all the sub projects under the super pom.xml
(the root POM) and downloads/compiles all the needed components in a directory called .m2
under the user's folder. These dependencies will have to be resolved for the project to be built without any errors, and mvn install
is one utility that could download most of the dependencies.
Further, there are other utils within Maven like dependency:resolve
which can be used separately in any specific cases. The build life cycle of the mvn is as below: LifeCycle Bindings
process-resources
compile
process-test-resources
test-compile
test
package
install
deploy
The test phase of this mvn can be ignored by using a flag -DskipTests=true
.
In HTML in <input>
field write: (keypress)="onlyNumberKey($event)"
and in ts file write:
onlyNumberKey(event) {
return (event.charCode == 8 || event.charCode == 0) ? null : event.charCode >= 48 && event.charCode <= 57;
}
In addition to the string operations (MOVS/INS/STOS/CMPS/SCASB/W/D/Q etc.) mentioned in the other answers, I wanted to add that there are also more "modern" x86 assembly instructions that implicitly use at least EDI/RDI:
The SSE2 MASKMOVDQU
(and the upcoming AVX VMASKMOVDQU
) instruction selectively write bytes from an XMM register to memory pointed to by EDI/RDI.