When the branch is no remote branch you can push your local branch direct to the remote.
git checkout master
git push origin master
or when you have a dev branch
git checkout dev
git push origin dev
or when the remote branch exists
git branch dev -t origin/dev
There are some other posibilites to push a remote branch.
bool isPow2 = ((x & ~(x-1))==x)? !!x : 0;
You can use XRegExp, an augmented, extensible, cross-browser implementation of regular expressions, including support for additional syntax, flags, and methods:
s
, to make dot match all characters (aka dotall or singleline mode), and x
, for free-spacing and comments (aka extended mode).I would like to present another answer to this as the currently accepted answer doesn't work for me (I use LibreOffice). This solution should work in Excel, LibreOffice and OpenOffice:
First, insert a new row at the beginning of the sheet. Within that row, define the names you need:
Then, in the menu bar, go to View -> Freeze Cells -> Freeze First Row. It'll look like this now:
Now whenever you scroll down in the document, the first row will be "pinned" to the top:
Here is a quote about package level visibility from an interview with James Gosling, the creator of Java:
Bill Venners: Java has four access levels. The default is package. I have always wondered if making package access default was convenient because the three keywords that people from C++ already knew about were private, protected, and public. Or if you had some particular reason that you felt package access should be the default.
James Gosling: A package is generally a set of things that are kind of written together. So generically I could have done one of two things. One was force you always to put in a keyword that gives you the domain. Or I could have had a default value. And then the question is, what makes a sensible default? And I tend to go for what is the least dangerous thing.
So public would have been a really bad thing to make the default. Private would probably have been a bad thing to make a default, if only because people actually don't write private methods that often. And same thing with protected. And in looking at a bunch of code that I had, I decided that the most common thing that was reasonably safe was in the package. And C++ didn't have a keyword for that, because they didn't have a notion of packages.
But I liked it rather than the friends notion, because with friends you kind of have to enumerate who all of your friends are, and so if you add a new class to a package, then you generally end up having to go to all of the classes in that package and update their friends, which I had always found to be a complete pain in the butt.
But the friends list itself causes sort of a versioning problem. And so there was this notion of a friendly class. And the nice thing that I was making that the default -- I'll solve the problem so what should the keyword be?
For a while there actually was a friendly keyword. But because all the others start with "P," it was "phriendly" with a "PH." But that was only in there for maybe a day.
You mentioned in another comment that you aren't expecting your get_userdata() function to return an stdClass object? If that is the case, you should mind this line in that function:
return $query->row();
Here, the CodeIgniter database object "$query" has its row() method called which returns an stdClass. Alternately, you could run row_array() which returns the same data in array form.
Anyway, I strongly suspect that this isn't the root cause of the problem. Can you give us some more details, perhaps? Play around with some things and let us know how it goes. We can't play with your code, so it's hard to say exactly what's going on.
We can use Angular event bindings to respond to any DOM event. The syntax is simple. We surround the DOM event name in parentheses and assign a quoted template statement to it. -- reference
Since change
is on the list of standard DOM events, we can use it:
(change)="saverange()"
In your particular case, since you're using NgModel, you could break up the two-way binding like this instead:
[ngModel]="range" (ngModelChange)="saverange($event)"
Then
saverange(newValue) {
this.range = newValue;
this.Platform.ready().then(() => {
this.rootRef.child("users").child(this.UserID).child('range').set(this.range)
})
}
However, with this approach saverange()
is called with every keystroke, so you're probably better off using (change)
.
In case of bettercodes.org, the solution is more poetic - the only problem may be in rights assigned to the project members. Simple members don't have write rights! Please make sure that you have the Moderator or Administrator rights. This needs to be set at bettercodes.org at the project settings by an Administrator, of course.
Why not set sample.png
as background image of text
or h2
css class? This will give effect as you have written over an image.
This is impossible to answer and has been brought up many many times before. Do a search, read those threads, then pick the framework you and your team have experience with.
This concerns Java versions 7 and earlier.
To quote a good answer to the same question:
If you want it back as a string later, you can call getPath(). Indeed, if you really wanted to mimic Path.Combine, you could just write something like:
public static String combine (String path1, String path2) {
File file1 = new File(path1);
File file2 = new File(file1, path2);
return file2.getPath();
}
If you use another view
make sure to use view.getContext()
instead of this
or getApplicationContext()
The preceding answers that I tried do not allow for automatic expansion (autocompletion) of subdirectories of the aliased directory.
However, if you push the directory that you want to alias onto the dirs
stack...
$ pushd ~/my/aliased/dir
...you can then type dirs -v
to see its numeric position in the stack:
0 ~/my/aliased/dir
1 ~/Downloads
2 /media/usbdrive
and refer to it using that number for most if not all commands that expect a directory parameter:
$ mv foo.txt ~0
You can even use Tab to show the immediate subdirectories of the "aliased" directory:
$ cd ~0/<Tab>
child_dir1 child_dir2
From the ansible docs: If a required variable has not been set, you can skip or fail using Jinja2’s defined test. For example:
tasks:
- shell: echo "I've got '{{ foo }}' and am not afraid to use it!"
when: foo is defined
- fail: msg="Bailing out. this play requires 'bar'"
when: bar is not defined
So in your case, when: deployed_revision is not defined
should work
The "uni" in unistd stands for "UNIX" - you won't find it on a Windows system.
Most widely used, portable libraries should offer alternative builds or detect the platform and only try to use headers/functions that will be provided, so it's worth checking documentation to see if you've missed some build step - e.g. perhaps running "make" instead of loading a ".sln" Visual C++ solution file.
If you need to fix it yourself, remove the include and see which functions are actually needed, then try to find a Windows equivalent.
I'm not sure about g++, but if you're using GNU Make then "make -j N" (where N is the number of threads make can create) will allow make to run multple g++ jobs at the same time (so long as the files do not depend on each other).
Since the back button is a function of the browser, it can be difficult to change the default functionality. There are some work arounds though. Take a look at this article:
http://www.irt.org/script/311.htm
Typically, the need to disable the back button is a good indicator of a programming issue/flaw. I would look for an alternative method like setting a session variable or a cookie that stores whether the form has already been submitted.
Your query should work fine, but you have to use the alias parent
to show the values of the parent table like this:
select
CONCAT(user.user_fname, ' ', user.user_lname) AS 'User Name',
CONCAT(parent.user_fname, ' ', parent.user_lname) AS 'Parent Name'
from users as user
inner join users as parent on parent.user_parent_id = user.user_id
where user.user_id = $_GET[id];
You can use SET
in cmd
To show the current variable, just SET
is enough
To show certain variable such as 'PATH', use SET PATH
.
For help, type set /?
.
This works for me.
var selecteditems = [];
$("#Div").find("input:checked").each(function (i, ob) {
selecteditems.push($(ob).val());
});
- Can someone give a simple definition of what
Record
is?
A Record<K, T>
is an object type whose property keys are K
and whose property values are T
. That is, keyof Record<K, T>
is equivalent to K
, and Record<K, T>[K]
is (basically) equivalent to T
.
- Is
Record<K,T>
merely a way of saying "all properties on this object will have typeT
"? Probably not all objects, sinceK
has some purpose...
As you note, K
has a purpose... to limit the property keys to particular values. If you want to accept all possible string-valued keys, you could do something like Record<string, T>
, but the idiomatic way of doing that is to use an index signature like { [k: string]: T }
.
- Does the
K
generic forbid additional keys on the object that are notK
, or does it allow them and just indicate that their properties are not transformed toT
?
It doesn't exactly "forbid" additional keys: after all, a value is generally allowed to have properties not explicitly mentioned in its type... but it wouldn't recognize that such properties exist:
declare const x: Record<"a", string>;
x.b; // error, Property 'b' does not exist on type 'Record<"a", string>'
and it would treat them as excess properties which are sometimes rejected:
declare function acceptR(x: Record<"a", string>): void;
acceptR({a: "hey", b: "you"}); // error, Object literal may only specify known properties
and sometimes accepted:
const y = {a: "hey", b: "you"};
acceptR(y); // okay
With the given example:
type ThreeStringProps = Record<'prop1' | 'prop2' | 'prop3', string>
Is it exactly the same as this?:
type ThreeStringProps = {prop1: string, prop2: string, prop3: string}
Yes!
Hope that helps. Good luck!
If the memory of the Mat mat
is continuous (all its data is continuous), you can directly get its data to a 1D array:
std::vector<uchar> array(mat.rows*mat.cols*mat.channels());
if (mat.isContinuous())
array = mat.data;
Otherwise, you have to get its data row by row, e.g. to a 2D array:
uchar **array = new uchar*[mat.rows];
for (int i=0; i<mat.rows; ++i)
array[i] = new uchar[mat.cols*mat.channels()];
for (int i=0; i<mat.rows; ++i)
array[i] = mat.ptr<uchar>(i);
UPDATE: It will be easier if you're using std::vector
, where you can do like this:
std::vector<uchar> array;
if (mat.isContinuous()) {
// array.assign(mat.datastart, mat.dataend); // <- has problems for sub-matrix like mat = big_mat.row(i)
array.assign(mat.data, mat.data + mat.total()*mat.channels());
} else {
for (int i = 0; i < mat.rows; ++i) {
array.insert(array.end(), mat.ptr<uchar>(i), mat.ptr<uchar>(i)+mat.cols*mat.channels());
}
}
p.s.: For cv::Mat
s of other types, like CV_32F
, you should do like this:
std::vector<float> array;
if (mat.isContinuous()) {
// array.assign((float*)mat.datastart, (float*)mat.dataend); // <- has problems for sub-matrix like mat = big_mat.row(i)
array.assign((float*)mat.data, (float*)mat.data + mat.total()*mat.channels());
} else {
for (int i = 0; i < mat.rows; ++i) {
array.insert(array.end(), mat.ptr<float>(i), mat.ptr<float>(i)+mat.cols*mat.channels());
}
}
UPDATE2: For OpenCV Mat data continuity, it can be summarized as follows:
imread()
, clone()
, or a constructor will always be continuous.Please check out this code snippet for demonstration.
I had the same issue with firefox 38.
After using following version dependencies, I could resolve the issue.
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
<version>2.53.0</version>
</dependency>
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-firefox-driver</artifactId>
<version>2.53.0</version>
</dependency>
Just want to share another option:
# mark two objects to be deleted
session.delete(obj1)
session.delete(obj2)
# commit (or flush)
session.commit()
http://docs.sqlalchemy.org/en/latest/orm/session_basics.html#deleting
In this example, the following codes shall works fine:
obj = User.query.filter_by(id=123).one()
session.delete(obj)
session.commit()
For anything below Honeycomb (API Level 11) you'll have to use setLayoutParams(...)
.
If you can limit your support to Honeycomb and up you can use the setX(...)
, setY(...)
, setLeft(...)
, setTop(...)
, etc.
Python supports a "bignum" integer type which can work with arbitrarily large numbers. In Python 2.5+, this type is called long
and is separate from the int
type, but the interpreter will automatically use whichever is more appropriate. In Python 3.0+, the int
type has been dropped completely.
That's just an implementation detail, though — as long as you have version 2.5 or better, just perform standard math operations and any number which exceeds the boundaries of 32-bit math will be automatically (and transparently) converted to a bignum.
You can find all the gory details in PEP 0237.
Try setting the charset on your Content-Type:
httpCon.setRequestProperty( "Content-Type", "multipart/form-data; charset=UTF-8; boundary=" + boundary );
Simple example:
var userID = data.id;
localStorage.setItem('userID',JSON.stringify(userID));
If you have an unsorted vector, then you can simply swap with the last vector element then resize()
.
With an ordered container, you'll be best off with ?std::vector::erase()
. Note that there is a std::remove()
defined in <algorithm>
, but that doesn't actually do the erasing. (Read the documentation carefully).
Back to the roots, i use this:
<meta http-equiv="refresh" content="0; url=YOURFILEURL"/>
Maybe not WC3 conform but works perfect on all browsers, no HTML5/JQUERY/Javascript.
Greetings Tom :)
if you are calling from static
method, use :
TestGameTable.class.getClassLoader().getResource("dice.jpg");
Assuming the upper is the upper bound and lower is the lower bound, then you can make a random number, r, between the two bounds with:
int r = (int) (Math.random() * (upper - lower)) + lower;
Yet another non-bash-4 (i.e., bash 3, Mac-compatible) way:
val_of_key() {
case $1 in
'A1') echo 'aaa';;
'B2') echo 'bbb';;
'C3') echo 'ccc';;
*) echo 'zzz';;
esac
}
for x in 'A1' 'B2' 'C3' 'D4'; do
y=$(val_of_key "$x")
echo "$x => $y"
done
Prints:
A1 => aaa
B2 => bbb
C3 => ccc
D4 => zzz
The function with the case
acts like an associative array. Unfortunately it cannot use return
, so it has to echo
its output, but this is not a problem, unless you are a purist that shuns forking subshells.
strip
does nothing but, removes the the whitespace in your string. If you want to remove the extra whitepace from front and back of your string, you can use strip.
The example string which can illustrate that is this:
In [2]: x = "something \t like \t this"
In [4]: x.split('\t')
Out[4]: ['something ', ' like ', ' this']
See, even after splitting with \t
there is extra whitespace in first and second items which can be removed using strip in your code.
I get same issue but I was getting error below error when run regsvr32 MSCOMCTL.OCX
The module "MSCOMCTL.OCX" was loaded but the call to DllRegisterServer failed with error code 0x8002801c.
When I run CMD.EXE as Administrator, then it solved my issue.
Some Times VB6.EXE also need o run as administrator to access some registry issue.
Good Luck.
Basically React.useState(0)
magically sees that it should return the tuple count
and setCount
(a method to change count
). The parameter useState
takes sets the initial value of count
.
const [count, setCount] = React.useState(0);
const [count2, setCount2] = React.useState(0);
// increments count by 1 when first button clicked
function handleClick(){
setCount(count + 1);
}
// increments count2 by 1 when second button clicked
function handleClick2(){
setCount2(count2 + 1);
}
return (
<div>
<h2>A React counter made with the useState Hook!</h2>
<p>You clicked {count} times</p>
<p>You clicked {count2} times</p>
<button onClick={handleClick}>
Click me
</button>
<button onClick={handleClick2}>
Click me2
</button>
);
Based off Enmanuel Duran's example, but shows two counters and writes lambda functions as normal functions, so some people might understand it easier.
Note: MDN gives a method using a while loop:
var indices = [];
var array = ['a', 'b', 'a', 'c', 'a', 'd'];
var element = 'a';
var idx = array.indexOf(element);
while (idx != -1) {
indices.push(idx);
idx = array.indexOf(element, idx + 1);
}
I wouldn't say it's any better than other answers. Just interesting.
it is easy! you are downloading the binary file?. download the rpm latest package openssl-1.0.1e-30.el6.x86_64 check what was the current version using rpm -q openssl. if this is older then do rpm -U openssl-1.0.1e-30.el6.x86_64 . if yum is configured updated this package in the repo and do yum update openssl if your repo in RHN do simply yum update openssl-1.0.1g is very old and valnuarable
Use below marco and remove the space.
#define TRIMWHITESPACE(string) [string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]]
in other file call TRIM :
NSString *strEmail;
strEmail = TRIM(@" this is the test.");
May it will help you...
This is a limit of the C++ compiler. If you put the function in the header, all the cpp files where it can be inlined can see the "source" of your function and the inlining can be done by the compiler. Otherwhise the inlining would have to be done by the linker (each cpp file is compiled in an obj file separately). The problem is that it would be much more difficult to do it in the linker. A similar problem exists with "template" classes/functions. They need to be instantiated by the compiler, because the linker would have problem instantiating (creating a specialized version of) them. Some newer compiler/linker can do a "two pass" compilation/linking where the compiler does a first pass, then the linker does its work and call the compiler to resolve unresolved things (inline/templates...)
document.getElementById("something").innerHTML = "<img src=\"something\" onmouseover=\"change('ex1')\" />";
OR
document.getElementById("something").innerHTML = '<img src="something" onmouseover="change(\'ex1\')" />';
It should be working...
Sample code to set the rightbutton
on a NavigationBar
.
UIBarButtonItem *rightButton = [[UIBarButtonItem alloc] initWithTitle:@"Done"
style:UIBarButtonItemStyleDone target:nil action:nil];
UINavigationItem *item = [[UINavigationItem alloc] initWithTitle:@"Title"];
item.rightBarButtonItem = rightButton;
item.hidesBackButton = YES;
[bar pushNavigationItem:item animated:NO];
But normally you would have a NavigationController
, enabling you to write:
UIBarButtonItem *rightButton = [[UIBarButtonItem alloc] initWithTitle:@"Done"
style:UIBarButtonItemStyleDone target:nil action:nil];
self.navigationItem.rightBarButtonItem = rightButton;
Here is a demo code where there is pagination + Filtering with AngularJS :
https://codepen.io/lamjaguar/pen/yOrVym
JS :
var app=angular.module('myApp', []);
// alternate - https://github.com/michaelbromley/angularUtils/tree/master/src/directives/pagination
// alternate - http://fdietz.github.io/recipes-with-angular-js/common-user-interface-patterns/paginating-through-client-side-data.html
app.controller('MyCtrl', ['$scope', '$filter', function ($scope, $filter) {
$scope.currentPage = 0;
$scope.pageSize = 10;
$scope.data = [];
$scope.q = '';
$scope.getData = function () {
// needed for the pagination calc
// https://docs.angularjs.org/api/ng/filter/filter
return $filter('filter')($scope.data, $scope.q)
/*
// manual filter
// if u used this, remove the filter from html, remove above line and replace data with getData()
var arr = [];
if($scope.q == '') {
arr = $scope.data;
} else {
for(var ea in $scope.data) {
if($scope.data[ea].indexOf($scope.q) > -1) {
arr.push( $scope.data[ea] );
}
}
}
return arr;
*/
}
$scope.numberOfPages=function(){
return Math.ceil($scope.getData().length/$scope.pageSize);
}
for (var i=0; i<65; i++) {
$scope.data.push("Item "+i);
}
// A watch to bring us back to the
// first pagination after each
// filtering
$scope.$watch('q', function(newValue,oldValue){ if(oldValue!=newValue){
$scope.currentPage = 0;
}
},true);
}]);
//We already have a limitTo filter built-in to angular,
//let's make a startFrom filter
app.filter('startFrom', function() {
return function(input, start) {
start = +start; //parse to int
return input.slice(start);
}
});
HTML :
<div ng-app="myApp" ng-controller="MyCtrl">
<input ng-model="q" id="search" class="form-control" placeholder="Filter text">
<select ng-model="pageSize" id="pageSize" class="form-control">
<option value="5">5</option>
<option value="10">10</option>
<option value="15">15</option>
<option value="20">20</option>
</select>
<ul>
<li ng-repeat="item in data | filter:q | startFrom:currentPage*pageSize | limitTo:pageSize">
{{item}}
</li>
</ul>
<button ng-disabled="currentPage == 0" ng-click="currentPage=currentPage-1">
Previous
</button> {{currentPage+1}}/{{numberOfPages()}}
<button ng-disabled="currentPage >= getData().length/pageSize - 1" ng-click="currentPage=currentPage+1">
Next
</button>
</div>
Go for this as it will give you both standard and performance.
$('#myDiv').click(function(){
//Some code
});
As the second method is simple JavaScript code and is faster than jQuery. But here performance will be approximately the same.
For a 64-bit JVM running in a 64-bit OS on a 64-bit machine, is there any limit besides the theoretical limit of 2^64 bytes or 16 exabytes?
You also have to take hardware limits into account. While pointers may be 64bit current CPUs can only address a less than 2^64 bytes worth of virtual memory.
With uncompressed pointers the hotspot JVM needs a continuous chunk of virtual address space for its heap. So the second hurdle after hardware is the operating system providing such a large chunk, not all OSes support this.
And the third one is practicality. Even if you can have that much virtual memory it does not mean the CPUs support that much physical memory, and without physical memory you will end up swapping, which will adversely affect the performance of the JVM because the GCs generally have to touch a large fraction of the heap.
As other answers mention compressed oops: By bumping the object alignment higher than 8 bytes the limits with compressed oops can be increased beyond 32GB
The standard Ubuntu install seems to put the various Java versions in /usr/lib/jvm
. The javac
, java you find in your path will softlink to this.
There's no issue with installing your own Java version anywhere you like, as long as you set the JAVA_HOME
environment variable and make sure to have the new Java bin
on your path.
A simple way to do this is to have the Java home exist as a softlink, so that if you want to upgrade or switch versions you only have to change the directory that this points to - e.g.:
/usr/bin/java --> /opt/jdk/bin/java,
/opt/jdk --> /opt/jdk1.6.011
Almost all Magento Models have a corresponding Collection object that can be used to fetch multiple instances of a Model.
To instantiate a Product collection, do the following
$collection = Mage::getModel('catalog/product')->getCollection();
Products are a Magento EAV style Model, so you'll need to add on any additional attributes that you want to return.
$collection = Mage::getModel('catalog/product')->getCollection();
//fetch name and orig_price into data
$collection->addAttributeToSelect('name');
$collection->addAttributeToSelect('orig_price');
There's multiple syntaxes for setting filters on collections. I always use the verbose one below, but you might want to inspect the Magento source for additional ways the filtering methods can be used.
The following shows how to filter by a range of values (greater than AND less than)
$collection = Mage::getModel('catalog/product')->getCollection();
$collection->addAttributeToSelect('name');
$collection->addAttributeToSelect('orig_price');
//filter for products whose orig_price is greater than (gt) 100
$collection->addFieldToFilter(array(
array('attribute'=>'orig_price','gt'=>'100'),
));
//AND filter for products whose orig_price is less than (lt) 130
$collection->addFieldToFilter(array(
array('attribute'=>'orig_price','lt'=>'130'),
));
While this will filter by a name that equals one thing OR another.
$collection = Mage::getModel('catalog/product')->getCollection();
$collection->addAttributeToSelect('name');
$collection->addAttributeToSelect('orig_price');
//filter for products who name is equal (eq) to Widget A, or equal (eq) to Widget B
$collection->addFieldToFilter(array(
array('attribute'=>'name','eq'=>'Widget A'),
array('attribute'=>'name','eq'=>'Widget B'),
));
A full list of the supported short conditionals (eq,lt, etc.) can be found in the _getConditionSql
method in lib/Varien/Data/Collection/Db.php
Finally, all Magento collections may be iterated over (the base collection class implements on of the the iterator interfaces). This is how you'll grab your products once filters are set.
$collection = Mage::getModel('catalog/product')->getCollection();
$collection->addAttributeToSelect('name');
$collection->addAttributeToSelect('orig_price');
//filter for products who name is equal (eq) to Widget A, or equal (eq) to Widget B
$collection->addFieldToFilter(array(
array('attribute'=>'name','eq'=>'Widget A'),
array('attribute'=>'name','eq'=>'Widget B'),
));
foreach ($collection as $product) {
//var_dump($product);
var_dump($product->getData());
}
Try:
With DependencedIncidents AS
(
SELECT INC.[RecTime],INC.[SQL] AS [str] FROM
(
SELECT A.[RecTime] As [RecTime],X.[SQL] As [SQL] FROM [EventView] AS A
CROSS JOIN [Incident] AS X
WHERE
patindex('%' + A.[Col] + '%', X.[SQL]) > 0
) AS INC
),
lalala AS
(
SELECT INC.[RecTime],INC.[SQL] AS [str] FROM
(
SELECT A.[RecTime] As [RecTime],X.[SQL] As [SQL] FROM [EventView] AS A
CROSS JOIN [Incident] AS X
WHERE
patindex('%' + A.[Col] + '%', X.[SQL]) > 0
) AS INC
)
And yes, you can reference common table expression inside common table expression definition. Even recursively. Which leads to some very neat tricks.
After having this problem myself, I found a solution that works for me:
Error message:
ssh -v [email protected]
OpenSSH_5.8p1, OpenSSL 1.0.0d 8 Feb 2011
debug1: Connecting to github.com [207.97.227.239] port 22.
debug1: connect to address 207.97.227.239 port 22: Connection timed out
ssh: connect to host github.com port 22: Connection timed out
ssh: connect to host github.com port 22: Bad file number
You will only see the bad file number message when on windows using the MINGGW shell. Linux users will just get Timed out.
Problem:
SSH is probably blocked on port 22. You can see this by typing
$nmap -sS github.com -p 22
Starting Nmap 5.35DC1 ( http://nmap.org ) at 2011-11-05 10:53 CET
Nmap scan report for github.com (207.97.227.239)
Host is up (0.10s latency).
PORT STATE SERVICE
22/tcp ***filtered*** ssh
Nmap done: 1 IP address (1 host up) scanned in 2.63 seconds
As you can see the state is Filtered, which means something is blocking it. You can solve this by performing an SSH to port 443 (your firewall / isp will not block this). It is also important that you need to ssh to "ssh.github.com" instead of github.com. Otherwise, you will report to the webserver instead of the ssh server. Below are all the steps needed to solve this problem.
Solution:
(First of all make sure you generated your keys like explained on http://help.github.com/win-set-up-git/)
create file ~/.ssh/config (ssh config file located in your user directory.
On windows probably %USERPROFILE%\.ssh\config
Paste the following code in it:
Host github.com
User git
Hostname ssh.github.com
PreferredAuthentications publickey
IdentityFile ~/.ssh/id_rsa
Port 443
Save the file.
Perform ssh like usual:
$ssh -T github.com
$Enter passphrase for key '.......... (you can smile now :))
Note that I do not have to supply the username or port number.
Since C++11 you could use std::put_time
from iomanip
header:
#include <iostream>
#include <iomanip>
#include <ctime>
int main()
{
auto t = std::time(nullptr);
auto tm = *std::localtime(&t);
std::cout << std::put_time(&tm, "%d-%m-%Y %H-%M-%S") << std::endl;
}
std::put_time
is a stream manipulator, therefore it could be used together with std::ostringstream
in order to convert the date to a string:
#include <iostream>
#include <iomanip>
#include <ctime>
#include <sstream>
int main()
{
auto t = std::time(nullptr);
auto tm = *std::localtime(&t);
std::ostringstream oss;
oss << std::put_time(&tm, "%d-%m-%Y %H-%M-%S");
auto str = oss.str();
std::cout << str << std::endl;
}
In C++ copying the object means cloning. There is no any special cloning in the language.
As the standard suggests, after copying you should have 2 identical copies of the same object.
There are 2 types of copying: copy constructor when you create object on a non initialized space and copy operator where you need to release the old state of the object (that is expected to be valid) before setting the new state.
I'm not really a fan of the most-upvoted answer here (in part because it seems like it isn't correct since it should continue
if it reads a null terminator in either string--but not both strings at once--and it doesn't do this), so I wrote my own.
strncmp()
, and has been tested with numerous test cases, as shown below.It is identical to strncmp()
except:
strncmp()
has undefined behavior if either string is a null ptr (see: https://en.cppreference.com/w/cpp/string/byte/strncmp).INT_MIN
as a special sentinel error value if either input string is a NULL
ptr.LIMITATIONS: Note that this code works on the original 7-bit ASCII character set only (decimal values 0 to 127, inclusive), NOT on unicode characters, such as unicode character encodings UTF-8 (the most popular), UTF-16, and UTF-32.
Here is the code only (no comments):
int strncmpci(const char * str1, const char * str2, size_t num)
{
int ret_code = 0;
size_t chars_compared = 0;
if (!str1 || !str2)
{
ret_code = INT_MIN;
return ret_code;
}
while ((chars_compared < num) && (*str1 || *str2))
{
ret_code = tolower((int)(*str1)) - tolower((int)(*str2));
if (ret_code != 0)
{
break;
}
chars_compared++;
str1++;
str2++;
}
return ret_code;
}
Fully-commented version:
/// \brief Perform a case-insensitive string compare (`strncmp()` case-insensitive) to see
/// if two C-strings are equal.
/// \note 1. Identical to `strncmp()` except:
/// 1. It is case-insensitive.
/// 2. The behavior is NOT undefined (it is well-defined) if either string is a null
/// ptr. Regular `strncmp()` has undefined behavior if either string is a null ptr
/// (see: https://en.cppreference.com/w/cpp/string/byte/strncmp).
/// 3. It returns `INT_MIN` as a special sentinel value for certain errors.
/// - Posted as an answer here: https://stackoverflow.com/a/55293507/4561887.
/// - Aided/inspired, in part, by `strcicmp()` here:
/// https://stackoverflow.com/a/5820991/4561887.
/// \param[in] str1 C string 1 to be compared.
/// \param[in] str2 C string 2 to be compared.
/// \param[in] num max number of chars to compare
/// \return A comparison code (identical to `strncmp()`, except with the addition
/// of `INT_MIN` as a special sentinel value):
///
/// INT_MIN (usually -2147483648 for int32_t integers) Invalid arguments (one or both
/// of the input strings is a NULL pointer).
/// <0 The first character that does not match has a lower value in str1 than
/// in str2.
/// 0 The contents of both strings are equal.
/// >0 The first character that does not match has a greater value in str1 than
/// in str2.
int strncmpci(const char * str1, const char * str2, size_t num)
{
int ret_code = 0;
size_t chars_compared = 0;
// Check for NULL pointers
if (!str1 || !str2)
{
ret_code = INT_MIN;
return ret_code;
}
// Continue doing case-insensitive comparisons, one-character-at-a-time, of `str1` to `str2`, so
// long as 1st: we have not yet compared the requested number of chars, and 2nd: the next char
// of at least *one* of the strings is not zero (the null terminator for a C-string), meaning
// that string still has more characters in it.
// Note: you MUST check `(chars_compared < num)` FIRST or else dereferencing (reading) `str1` or
// `str2` via `*str1` and `*str2`, respectively, is undefined behavior if you are reading one or
// both of these C-strings outside of their array bounds.
while ((chars_compared < num) && (*str1 || *str2))
{
ret_code = tolower((int)(*str1)) - tolower((int)(*str2));
if (ret_code != 0)
{
// The 2 chars just compared don't match
break;
}
chars_compared++;
str1++;
str2++;
}
return ret_code;
}
Download the entire sample code, with unit tests, from my eRCaGuy_hello_world repository here: "strncmpci.c":
(this is just a snippet)
int main()
{
printf("-----------------------\n"
"String Comparison Tests\n"
"-----------------------\n\n");
int num_failures_expected = 0;
printf("INTENTIONAL UNIT TEST FAILURE to show what a unit test failure looks like!\n");
EXPECT_EQUALS(strncmpci("hey", "HEY", 3), 'h' - 'H');
num_failures_expected++;
printf("------ beginning ------\n\n");
const char * str1;
const char * str2;
size_t n;
// NULL ptr checks
EXPECT_EQUALS(strncmpci(NULL, "", 0), INT_MIN);
EXPECT_EQUALS(strncmpci("", NULL, 0), INT_MIN);
EXPECT_EQUALS(strncmpci(NULL, NULL, 0), INT_MIN);
EXPECT_EQUALS(strncmpci(NULL, "", 10), INT_MIN);
EXPECT_EQUALS(strncmpci("", NULL, 10), INT_MIN);
EXPECT_EQUALS(strncmpci(NULL, NULL, 10), INT_MIN);
EXPECT_EQUALS(strncmpci("", "", 0), 0);
EXPECT_EQUALS(strncmp("", "", 0), 0);
str1 = "";
str2 = "";
n = 0;
EXPECT_EQUALS(strncmpci(str1, str2, n), 0);
EXPECT_EQUALS(strncmp(str1, str2, n), 0);
str1 = "hey";
str2 = "HEY";
n = 0;
EXPECT_EQUALS(strncmpci(str1, str2, n), 0);
EXPECT_EQUALS(strncmp(str1, str2, n), 0);
str1 = "hey";
str2 = "HEY";
n = 3;
EXPECT_EQUALS(strncmpci(str1, str2, n), 0);
EXPECT_EQUALS(strncmp(str1, str2, n), 'h' - 'H');
str1 = "heY";
str2 = "HeY";
n = 3;
EXPECT_EQUALS(strncmpci(str1, str2, n), 0);
EXPECT_EQUALS(strncmp(str1, str2, n), 'h' - 'H');
str1 = "hey";
str2 = "HEdY";
n = 3;
EXPECT_EQUALS(strncmpci(str1, str2, n), 'y' - 'd');
EXPECT_EQUALS(strncmp(str1, str2, n), 'h' - 'H');
str1 = "heY";
str2 = "hEYd";
n = 3;
EXPECT_EQUALS(strncmpci(str1, str2, n), 0);
EXPECT_EQUALS(strncmp(str1, str2, n), 'e' - 'E');
str1 = "heY";
str2 = "heyd";
n = 6;
EXPECT_EQUALS(strncmpci(str1, str2, n), -'d');
EXPECT_EQUALS(strncmp(str1, str2, n), 'Y' - 'y');
str1 = "hey";
str2 = "hey";
n = 6;
EXPECT_EQUALS(strncmpci(str1, str2, n), 0);
EXPECT_EQUALS(strncmp(str1, str2, n), 0);
str1 = "hey";
str2 = "heyd";
n = 6;
EXPECT_EQUALS(strncmpci(str1, str2, n), -'d');
EXPECT_EQUALS(strncmp(str1, str2, n), -'d');
str1 = "hey";
str2 = "heyd";
n = 3;
EXPECT_EQUALS(strncmpci(str1, str2, n), 0);
EXPECT_EQUALS(strncmp(str1, str2, n), 0);
str1 = "hEY";
str2 = "heyYOU";
n = 3;
EXPECT_EQUALS(strncmpci(str1, str2, n), 0);
EXPECT_EQUALS(strncmp(str1, str2, n), 'E' - 'e');
str1 = "hEY";
str2 = "heyYOU";
n = 10;
EXPECT_EQUALS(strncmpci(str1, str2, n), -'y');
EXPECT_EQUALS(strncmp(str1, str2, n), 'E' - 'e');
str1 = "hEYHowAre";
str2 = "heyYOU";
n = 10;
EXPECT_EQUALS(strncmpci(str1, str2, n), 'h' - 'y');
EXPECT_EQUALS(strncmp(str1, str2, n), 'E' - 'e');
EXPECT_EQUALS(strncmpci("nice to meet you.,;", "NICE TO MEET YOU.,;", 100), 0);
EXPECT_EQUALS(strncmp( "nice to meet you.,;", "NICE TO MEET YOU.,;", 100), 'n' - 'N');
EXPECT_EQUALS(strncmp( "nice to meet you.,;", "nice to meet you.,;", 100), 0);
EXPECT_EQUALS(strncmpci("nice to meet you.,;", "NICE TO UEET YOU.,;", 100), 'm' - 'u');
EXPECT_EQUALS(strncmp( "nice to meet you.,;", "nice to uEET YOU.,;", 100), 'm' - 'u');
EXPECT_EQUALS(strncmp( "nice to meet you.,;", "nice to UEET YOU.,;", 100), 'm' - 'U');
EXPECT_EQUALS(strncmpci("nice to meet you.,;", "NICE TO MEET YOU.,;", 5), 0);
EXPECT_EQUALS(strncmp( "nice to meet you.,;", "NICE TO MEET YOU.,;", 5), 'n' - 'N');
EXPECT_EQUALS(strncmpci("nice to meet you.,;", "NICE eo UEET YOU.,;", 5), 0);
EXPECT_EQUALS(strncmp( "nice to meet you.,;", "nice eo uEET YOU.,;", 5), 0);
EXPECT_EQUALS(strncmpci("nice to meet you.,;", "NICE eo UEET YOU.,;", 100), 't' - 'e');
EXPECT_EQUALS(strncmp( "nice to meet you.,;", "nice eo uEET YOU.,;", 100), 't' - 'e');
EXPECT_EQUALS(strncmpci("nice to meet you.,;", "nice-eo UEET YOU.,;", 5), ' ' - '-');
EXPECT_EQUALS(strncmp( "nice to meet you.,;", "nice-eo UEET YOU.,;", 5), ' ' - '-');
if (globals.error_count == num_failures_expected)
{
printf(ANSI_COLOR_GRN "All unit tests passed!" ANSI_COLOR_OFF "\n");
}
else
{
printf(ANSI_COLOR_RED "FAILED UNIT TESTS! NUMBER OF UNEXPECTED FAILURES = %i"
ANSI_COLOR_OFF "\n", globals.error_count - num_failures_expected);
}
assert(globals.error_count == num_failures_expected);
return globals.error_count;
}
$ gcc -Wall -Wextra -Werror -ggdb -std=c11 -o ./bin/tmp strncmpci.c && ./bin/tmp ----------------------- String Comparison Tests ----------------------- INTENTIONAL UNIT TEST FAILURE to show what a unit test failure looks like! FAILED at line 250 in function main! strncmpci("hey", "HEY", 3) != 'h' - 'H' a: strncmpci("hey", "HEY", 3) is 0 b: 'h' - 'H' is 32 ------ beginning ------ All unit tests passed!
Check out this issue. I think the bug will be resolved when new template precompilation logic will be implemented. For now I think the best you can do is to wrap your template into <div class="root">
and style this div
:
@Component({ ... })
@View({
template: `
<div class="root">
<h2>Hello Angular2!</h2>
<p>here is your template</p>
</div>
`,
styles: [`
.root {
background: blue;
}
`],
...
})
class SomeComponent {}
See this plunker
I resolved my trouble in correcting the "Additional Library Directory", this one was wrong in indicating "$(SolutionDir)\Release", I changed it in "$(SolutionDir)\$(IntDir)"
To correct it, open your project properties -> Configuration Properties -> Linker -> General -> Additional Library Directory
I hope this will help some poeples with the same trouble ;)
The following is inspired by Simon's answer. It's self-contained (doesn't require a separate format file), which makes it great for inclusion into .bashrc
.
curl_time() {
curl -so /dev/null -w "\
namelookup: %{time_namelookup}s\n\
connect: %{time_connect}s\n\
appconnect: %{time_appconnect}s\n\
pretransfer: %{time_pretransfer}s\n\
redirect: %{time_redirect}s\n\
starttransfer: %{time_starttransfer}s\n\
-------------------------\n\
total: %{time_total}s\n" "$@"
}
Futhermore, it should work with all arguments that curl
normally takes, since the "$@"
just passes them through. For example, you can do:
curl_time -X POST -H "Content-Type: application/json" -d '{"key": "val"}' https://postman-echo.com/post
Output:
namelookup: 0,125000s
connect: 0,250000s
appconnect: 0,609000s
pretransfer: 0,609000s
redirect: 0,000000s
starttransfer: 0,719000s
-------------------------
total: 0,719000s
The nearest equivalents would be icode and bcode as used by scalac, view Miguel Garcia's site on the Scalac optimiser for more information, here: http://magarciaepfl.github.io/scala/
You might also consider Java bytecode itself to be your intermediate representation, given that bytecode is the ultimate output of scalac.
Or perhaps the true intermediate is something that the JIT produces before it finally outputs native instructions?
Ultimately though... There's no single place that you can point at an claim "there's the intermediate!". Scalac works in phases that successively change the abstract syntax tree, every single phase produces a new intermediate. The whole thing is like an onion, and it's very hard to try and pick out one layer as somehow being more significant than any other.
If you get this problem using HTTP GET in IE I solved this issue by setting the cache: false. As I used the same url for both HTML and json requests it hit the cache instead of doing a json call.
$.ajax({
url: '/Test/Something/',
type: 'GET',
dataType: 'json',
cache: false,
data: { viewID: $("#view").val() },
success: function (data) {
alert(data);
},
error: function (data) {
debugger;
alert("Error");
}
});
Going down your list:
Utf32String
class as part of my MiscUtil library, should you ever want it. (It's not been very thoroughly tested, mind you.)There's more on my Unicode page and tips for debugging Unicode problems.
The other big resource of code is unicode.org which contains more information than you'll ever be able to work your way through - possibly the most useful bit is the code charts.
A simple implementation could consist of:
Every time you write data, you advance the write pointer and increment the counter. When you read data, you increase the read pointer and decrement the counter. If either pointer reaches n, set it to zero.
You can't write if counter = n. You can't read if counter = 0.
You can have multiple sizes of icons in the same file. I routinely create favicons (.ico
file) that are 48, 32, and 16 pixels. You can add in any size image you want. The question is, will the iPhone use an ico
file?
ico
also supports transparency, but I'm not sure if it's an alpha channel like PNG; probably more like GIF where it's on or it's off.
Try this
typeof(IFoo).IsAssignableFrom(typeof(BarClass));
This will tell you whether BarClass(Derived)
implements IFoo(SomeType)
or not
In JAVA, values like:
Is assumed as double and not float.
You can also perform a cast in order to solve the problem:
float b = (float) 3.5
;
Another solution:
float b = 3.5f
;
In Python 2.7:
a = 13.949999999999999
output = float("%0.2f"%a)
print output
The alert method blocks execution until the user closes it:
use the confirm function:
if (confirm('Some message')) {
alert('Thanks for confirming');
} else {
alert('Why did you press cancel? You should have confirmed');
}
When using bindParam()
you must pass in a variable, not a constant. So before that line you need to create a variable and set it to null
$myNull = null;
$stmt->bindParam(':v1', $myNull, PDO::PARAM_NULL);
You would get the same error message if you tried:
$stmt->bindParam(':v1', 5, PDO::PARAM_NULL);
What do you mean by "version number"? It is quite common to tag a commit with a version number and then use
$ git describe --tags
to identify the current HEAD w.r.t. any tags. If you mean you want to know the hash of the current HEAD, you probably want:
$ git rev-parse HEAD
or for the short revision hash:
$ git rev-parse --short HEAD
It is often sufficient to do:
$ cat .git/refs/heads/${branch-master}
but this is not reliable as the ref may be packed.
This is usually caused when using a build system like Apache Ant that only compiles java files when the java file is newer than the class file. If a method signature changes and classes were using the old version things may not be compiled correctly. The usual fix is to do a full rebuild (usually "ant clean" then "ant").
Sometimes this can also be caused when compiling against one version of a library but running against a different version.
one solution could be to find a way of pulling the numbers from the string and placing them in a column of just numbers the using the =MEDIAN() function giving the new number column as the range
System.currentTimeMillis()
does give you the number of milliseconds since January 1, 1970 00:00:00 UTC. The reason you see local times might be because you convert a Date
instance to a string before using it. You can use DateFormat
s to convert Date
s to String
s in any timezone:
DateFormat df = DateFormat.getTimeInstance();
df.setTimeZone(TimeZone.getTimeZone("gmt"));
String gmtTime = df.format(new Date());
The database's built-in catalog views provide the information to do this. Try this query:
SELECT
(
dp.state_desc + ' ' +
dp.permission_name collate latin1_general_cs_as +
' ON ' + '[' + s.name + ']' + '.' + '[' + o.name + ']' +
' TO ' + '[' + dpr.name + ']'
) AS GRANT_STMT
FROM sys.database_permissions AS dp
INNER JOIN sys.objects AS o ON dp.major_id=o.object_id
INNER JOIN sys.schemas AS s ON o.schema_id = s.schema_id
INNER JOIN sys.database_principals AS dpr ON dp.grantee_principal_id=dpr.principal_id
WHERE dpr.name NOT IN ('public','guest')
-- AND o.name IN ('My_Procedure') -- Uncomment to filter to specific object(s)
-- AND dp.permission_name='EXECUTE' -- Uncomment to filter to just the EXECUTEs
This will spit out a bunch of commands (GRANT/DENY) for each of the permissions in the database. From this, you can copy-and-paste them into another query window and execute, to generate the same permissions that were in place on the original. For example:
GRANT EXECUTE ON [Exposed].[EmployeePunchoutReservationRetrieve] TO [CustomerAgentRole]
GRANT EXECUTE ON [Exposed].[EmployeePunchoutReservationStore] TO [CustomerAgentRole]
GRANT EXECUTE ON [Exposed].[EmployeePunchoutSendOrderLogStore] TO [CustomerAgentRole]
GRANT EXECUTE ON [Exposed].[EmployeeReportSubscriptions] TO [CustomerAgentRole]
Note the bottom line, commented out, that's filtering on permission_name. Un-commenting that line will cause the query to only spit out the EXECUTE permissions (i.e., those for stored procedures).
If you are using select as inline to other component, then you can also use like given below.
<select onChange={(val) => this.handlePeriodChange(val.target.value)} className="btn btn-sm btn-outline-secondary dropdown-toggle">
<option value="TODAY">Today</option>
<option value="THIS_WEEK" >This Week</option>
<option value="THIS_MONTH">This Month</option>
<option value="THIS_YEAR">This Year</option>
<option selected value="LAST_AVAILABLE_DAY">Last Availabe NAV Day</option>
</select>
And on the component where select is used, define the function to handle onChange like below:
handlePeriodChange(selVal) {
this.props.handlePeriodChange(selVal);
}
// GET DATE & TIME IN ANY FORMAT
import java.util.Calendar;
import java.text.SimpleDateFormat;
public static final String DATE_FORMAT_NOW = "yyyy-MM-dd HH:mm:ss";
public static String now() {
Calendar cal = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT_NOW);
return sdf.format(cal.getTime());
}
Taken from here
What about something like this:
First resample the data frame into 1D intervals. This takes the mean of the values for all duplicate days. Use the fill_method
option to fill in missing date values. Next, pass the resampled frame into pd.rolling_mean
with a window of 3 and min_periods=1 :
pd.rolling_mean(df.resample("1D", fill_method="ffill"), window=3, min_periods=1)
favorable unfavorable other
enddate
2012-10-25 0.495000 0.485000 0.025000
2012-10-26 0.527500 0.442500 0.032500
2012-10-27 0.521667 0.451667 0.028333
2012-10-28 0.515833 0.450000 0.035833
2012-10-29 0.488333 0.476667 0.038333
2012-10-30 0.495000 0.470000 0.038333
2012-10-31 0.512500 0.460000 0.029167
2012-11-01 0.516667 0.456667 0.026667
2012-11-02 0.503333 0.463333 0.033333
2012-11-03 0.490000 0.463333 0.046667
2012-11-04 0.494000 0.456000 0.043333
2012-11-05 0.500667 0.452667 0.036667
2012-11-06 0.507333 0.456000 0.023333
2012-11-07 0.510000 0.443333 0.013333
UPDATE: As Ben points out in the comments, with pandas 0.18.0 the syntax has changed. With the new syntax this would be:
df.resample("1d").sum().fillna(0).rolling(window=3, min_periods=1).mean()
{% for source in sources %}
<tr>
<td>{{ source }}</td>
<td>
{% ifequal title source %}
Just now!
{% endifequal %}
</td>
</tr>
{% endfor %}
or
{% for source in sources %}
<tr>
<td>{{ source }}</td>
<td>
{% if title == source %}
Just now!
{% endif %}
</td>
</tr>
{% endfor %}
Simplest way is to use dimensions in % or em. Just change the base font size everything will change.
Less
@media (max-width: @screen-xs) {
body{font-size: 10px;}
}
@media (max-width: @screen-sm) {
body{font-size: 14px;}
}
h5{
font-size: 1.4rem;
}
Look at all the ways at https://stackoverflow.com/a/21981859/406659
You could use viewport units (vh,vw...) but they dont work on Android < 4.4
This works in Python 2.x.
For Python 3 look in the docs:
import urllib.request
with urllib.request.urlopen("http://www.python.org") as url:
s = url.read()
# I'm guessing this would output the html source code ?
print(s)
To delete rows from a table, you need to provide selection criteria that identify the rows to the delete()
method. The mechanism works the same as the selection arguments to the query()
method. It divides the selection specification into a selection clause(where clause) and selection arguments.
SQLiteDatabase db = this.getWritableDatabase();
// Define 'where' part of query.
String selection = Contract.COLUMN_COMPANY_ID + " =? and "
+ Contract.CLOUMN_TYPE +" =? ";
// Specify arguments in placeholder order.
String[] selectionArgs = { cid,mode };
// Issue SQL statement.
int deletedRows = db.delete(Contract.TABLE_NAME,
selection, selectionArgs);
return deletedRows;// no.of rows deleted.
The return value for the delete()
method indicates the number of rows that were deleted from the database.
try the following:
<iframe name="" src="" width="100%" style="height: 100em"/>
it worked for me
Since setEditable(false)
is deprecated, use textView.setKeyListener(null);
to make editText non-clickable.
With JUnit5 and @DataJpaTest
test will look like (kotlin code):
@DataJpaTest
@ExtendWith(value = [SpringExtension::class])
class ActivityJpaTest {
@Autowired
lateinit var entityManager: TestEntityManager
@Autowired
lateinit var myEntityRepository: MyEntityRepository
@Test
fun shouldSaveEntity() {
// when
val savedEntity = myEntityRepository.save(MyEntity(1, "test")
// then
Assertions.assertNotNull(entityManager.find(MyEntity::class.java, savedEntity.id))
}
}
You could use TestEntityManager
from org.springframework.boot.test.autoconfigure.orm.jpa.TestEntityManager
package in order to validate entity state.
ARIA (Accessible Rich Internet Applications) defines a way to make Web content and Web applications more accessible to people with disabilities.
The hidden
attribute is new in HTML5 and tells browsers not to display the element. The aria-hidden
property tells screen-readers if they should ignore the element. Have a look at the w3 docs for more details:
https://www.w3.org/WAI/PF/aria/states_and_properties#aria-hidden
Using these standards can make it easier for disabled people to use the web.
Better solution is to add a new property "Fonts provided by application
" to your info.plist
file.
Then, you can use your custom font like normal UIFont
.
The best way to get the id of the entity you added is like this:
public int InsertEntity(Entity factor)
{
Db.Entities.Add(factor);
Db.SaveChanges();
var id = factor.id;
return id;
}
Once I found what format it was looking for in the connection string, it worked just fine like this with Oracle.ManagedDataAccess. Without having to mess around with anything separately.
DATA SOURCE=DSDSDS:1521/ORCL;
Ctrl+Alt+? / ? add cursors above and below the current line. Still nowhere near as good as sublime or brackets though. I can't see anything equivalent to Ctrl+D in sublime in the keyboard shortcuts file.
I think the code below
<item name="android:actionMenuTextAppearance">@style/MyActionBar.MenuTextStyle</item>
must be in MyAppTheme
section.
A quick & concise difference overview :
attr_accessor
is an easy way to create read and write accessors in your class. It is used when you do not have a column in your database, but still want to show a field in your forms. This field is a“virtual attribute”
in a Rails model.virtual attribute – an attribute not corresponding to a column in the database.
attr_accessible
is used to identify attributes that are accessible by your controller methods makes a property available for mass-assignment.. It will only allow access to the attributes that you specify, denying the rest.
I faced the same issue. After some searching on the Internet found the below article. Then realized that I was logged as a user different from the user that I had used to setup SVN under, a permission issue basically.
I made a function to get a vector of queries and do a transaction, maybe someone will find out it useful:
function transaction ($con, $Q){
mysqli_query($con, "START TRANSACTION");
for ($i = 0; $i < count ($Q); $i++){
if (!mysqli_query ($con, $Q[$i])){
echo 'Error! Info: <' . mysqli_error ($con) . '> Query: <' . $Q[$i] . '>';
break;
}
}
if ($i == count ($Q)){
mysqli_query($con, "COMMIT");
return 1;
}
else {
mysqli_query($con, "ROLLBACK");
return 0;
}
}
Yes, I think hashing the file would be the best way if you have to compare several files and store hashes for later comparison. As hash can clash, a byte-by-byte comparison may be done depending on the use case.
Generally byte-by-byte comparison would be sufficient and efficient, which filecmp module already does + other things too.
See http://docs.python.org/library/filecmp.html e.g.
>>> import filecmp
>>> filecmp.cmp('file1.txt', 'file1.txt')
True
>>> filecmp.cmp('file1.txt', 'file2.txt')
False
Speed consideration: Usually if only two files have to be compared, hashing them and comparing them would be slower instead of simple byte-by-byte comparison if done efficiently. e.g. code below tries to time hash vs byte-by-byte
Disclaimer: this is not the best way of timing or comparing two algo. and there is need for improvements but it does give rough idea. If you think it should be improved do tell me I will change it.
import random
import string
import hashlib
import time
def getRandText(N):
return "".join([random.choice(string.printable) for i in xrange(N)])
N=1000000
randText1 = getRandText(N)
randText2 = getRandText(N)
def cmpHash(text1, text2):
hash1 = hashlib.md5()
hash1.update(text1)
hash1 = hash1.hexdigest()
hash2 = hashlib.md5()
hash2.update(text2)
hash2 = hash2.hexdigest()
return hash1 == hash2
def cmpByteByByte(text1, text2):
return text1 == text2
for cmpFunc in (cmpHash, cmpByteByByte):
st = time.time()
for i in range(10):
cmpFunc(randText1, randText2)
print cmpFunc.func_name,time.time()-st
and the output is
cmpHash 0.234999895096
cmpByteByByte 0.0
Here's the whole code snippet needed:
$queried_object = get_queried_object();
$term_id = $queried_object->term_id;
You say that the matrices are the same dimensions, and yet you are trying to perform matrix multiplication on them. Multiplication of matrices with the same dimension is only possible if they are square. In your case, you get an assertion error, because the dimensions are not square. You have to be careful when multiplying matrices, as there are two possible meanings of multiply.
Matrix multiplication is where two matrices are multiplied directly. This operation multiplies matrix A of size [a x b] with matrix B of size [b x c] to produce matrix C of size [a x c]. In OpenCV it is achieved using the simple *
operator:
C = A * B
Element-wise multiplication is where each pixel in the output matrix is formed by multiplying that pixel in matrix A by its corresponding entry in matrix B. The input matrices should be the same size, and the output will be the same size as well. This is achieved using the mul()
function:
output = A.mul(B);
Let assume i am having a RestController
with GET/POST/PUT/DELETE
operations and i have to write unit test using spring boot.I will just share code of RestController class and respective unit test.Wont be sharing any other related code to the controller ,can have assumption on that.
@RestController
@RequestMapping(value = “/myapi/myApp” , produces = {"application/json"})
public class AppController {
@Autowired
private AppService service;
@GetMapping
public MyAppResponse<AppEntity> get() throws Exception {
MyAppResponse<AppEntity> response = new MyAppResponse<AppEntity>();
service.getApp().stream().forEach(x -> response.addData(x));
return response;
}
@PostMapping
public ResponseEntity<HttpStatus> create(@RequestBody AppRequest request) throws Exception {
//Validation code
service.createApp(request);
return ResponseEntity.ok(HttpStatus.OK);
}
@PutMapping
public ResponseEntity<HttpStatus> update(@RequestBody IDMSRequest request) throws Exception {
//Validation code
service.updateApp(request);
return ResponseEntity.ok(HttpStatus.OK);
}
@DeleteMapping
public ResponseEntity<HttpStatus> delete(@RequestBody AppRequest request) throws Exception {
//Validation
service.deleteApp(request.id);
return ResponseEntity.ok(HttpStatus.OK);
}
}
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = Main.class)
@WebAppConfiguration
public abstract class BaseTest {
protected MockMvc mvc;
@Autowired
WebApplicationContext webApplicationContext;
protected void setUp() {
mvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
}
protected String mapToJson(Object obj) throws JsonProcessingException {
ObjectMapper objectMapper = new ObjectMapper();
return objectMapper.writeValueAsString(obj);
}
protected <T> T mapFromJson(String json, Class<T> clazz)
throws JsonParseException, JsonMappingException, IOException {
ObjectMapper objectMapper = new ObjectMapper();
return objectMapper.readValue(json, clazz);
}
}
public class AppControllerTest extends BaseTest {
@MockBean
private IIdmsService service;
private static final String URI = "/myapi/myApp";
@Override
@Before
public void setUp() {
super.setUp();
}
@Test
public void testGet() throws Exception {
AppEntity entity = new AppEntity();
List<AppEntity> dataList = new ArrayList<AppEntity>();
AppResponse<AppEntity> dataResponse = new AppResponse<AppEntity>();
entity.setId(1);
entity.setCreated_at("2020-02-21 17:01:38.717863");
entity.setCreated_by(“Abhinav Kr”);
entity.setModified_at("2020-02-24 17:01:38.717863");
entity.setModified_by(“Jyoti”);
dataList.add(entity);
dataResponse.setData(dataList);
Mockito.when(service.getApp()).thenReturn(dataList);
RequestBuilder requestBuilder = MockMvcRequestBuilders.get(URI)
.accept(MediaType.APPLICATION_JSON);
MvcResult mvcResult = mvc.perform(requestBuilder).andReturn();
MockHttpServletResponse response = mvcResult.getResponse();
String expectedJson = this.mapToJson(dataResponse);
String outputInJson = mvcResult.getResponse().getContentAsString();
assertEquals(HttpStatus.OK.value(), response.getStatus());
assertEquals(expectedJson, outputInJson);
}
@Test
public void testCreate() throws Exception {
AppRequest request = new AppRequest();
request.createdBy = 1;
request.AppFullName = “My App”;
request.appTimezone = “India”;
String inputInJson = this.mapToJson(request);
Mockito.doNothing().when(service).createApp(Mockito.any(AppRequest.class));
service.createApp(request);
Mockito.verify(service, Mockito.times(1)).createApp(request);
RequestBuilder requestBuilder = MockMvcRequestBuilders.post(URI)
.accept(MediaType.APPLICATION_JSON).content(inputInJson)
.contentType(MediaType.APPLICATION_JSON);
MvcResult mvcResult = mvc.perform(requestBuilder).andReturn();
MockHttpServletResponse response = mvcResult.getResponse();
assertEquals(HttpStatus.OK.value(), response.getStatus());
}
@Test
public void testUpdate() throws Exception {
AppRequest request = new AppRequest();
request.id = 1;
request.modifiedBy = 1;
request.AppFullName = “My App”;
request.appTimezone = “Bharat”;
String inputInJson = this.mapToJson(request);
Mockito.doNothing().when(service).updateApp(Mockito.any(AppRequest.class));
service.updateApp(request);
Mockito.verify(service, Mockito.times(1)).updateApp(request);
RequestBuilder requestBuilder = MockMvcRequestBuilders.put(URI)
.accept(MediaType.APPLICATION_JSON).content(inputInJson)
.contentType(MediaType.APPLICATION_JSON);
MvcResult mvcResult = mvc.perform(requestBuilder).andReturn();
MockHttpServletResponse response = mvcResult.getResponse();
assertEquals(HttpStatus.OK.value(), response.getStatus());
}
@Test
public void testDelete() throws Exception {
AppRequest request = new AppRequest();
request.id = 1;
String inputInJson = this.mapToJson(request);
Mockito.doNothing().when(service).deleteApp(Mockito.any(Integer.class));
service.deleteApp(request.id);
Mockito.verify(service, Mockito.times(1)).deleteApp(request.id);
RequestBuilder requestBuilder = MockMvcRequestBuilders.delete(URI)
.accept(MediaType.APPLICATION_JSON).content(inputInJson)
.contentType(MediaType.APPLICATION_JSON);
MvcResult mvcResult = mvc.perform(requestBuilder).andReturn();
MockHttpServletResponse response = mvcResult.getResponse();
assertEquals(HttpStatus.OK.value(), response.getStatus());
}
}
What does the UDF EntityHasProfile() do?
Typically you could do something like this with a LEFT JOIN:
SELECT EntityId, EntityName, CASE WHEN EntityProfileIs IS NULL THEN 0 ELSE 1 END AS Has Profile
FROM Entities
LEFT JOIN EntityProfiles
ON EntityProfiles.EntityId = Entities.EntityId
This should eliminate a need for a costly scalar UDF call - in my experience, scalar UDFs should be a last resort for most database design problems in SQL Server - they are simply not good performers.
Works for every binary, not only java:
file - < $(which java) # heavyly bashic
cat `which java` | file - # universal
You simply need to start mysql
and feed it with the content of db.sql
:
mysql -u user -p < db.sql
In Android Studio open:
File > Project Structure
and check if JDK location points to your JDK 1.8 directory.
Note: you can use compileSdkVersion 24
.
It works trust me. For this to work first download latest JDK from Oracle.
I would simply look for a $_GET
variable and redirect the user if it's not correct.
<?php
$pass = $_GET['pass'];
if($pass != 'my-secret-password') {
header('Location: http://www.staggeringbeauty.com/');
}
?>
Now, if this page is located at say: http://example.com/secrets/files.php
You can now access it with: http://example.com/secrets/files.php?pass=my-secret-password
Keep in mind that this isn't the most efficient or secure way, but nonetheless it is a easy and fast way. (Also, I know my answer is outdated but someone else looking at this question may find it valuable)
http://www.eclipse.org/cdt/ ^Give that a try
I have not used the CDT for eclipse but I do use Eclipse Java for Ubuntu 12.04 and it works wonders.
This is a huge topic, with answers from 3 lines of code to entire research magazines.
I will outline the most common such techniques and their results.
One of the simplest & fastest methods. Proposed decades ago as a means to find picture simmilarities. The idea is that a forest will have a lot of green, and a human face a lot of pink, or whatever. So, if you compare two pictures with forests, you'll get some simmilarity between histograms, because you have a lot of green in both.
Downside: it is too simplistic. A banana and a beach will look the same, as both are yellow.
OpenCV method: compareHist()
A good example here matchTemplate finding good match. It convolves the search image with the one being search into. It is usually used to find smaller image parts in a bigger one.
Downsides: It only returns good results with identical images, same size & orientation.
OpenCV method: matchTemplate()
Considered one of the most efficient ways to do image search. A number of features are extracted from an image, in a way that guarantees the same features will be recognized again even when rotated, scaled or skewed. The features extracted this way can be matched against other image feature sets. Another image that has a high proportion of the features matching the first one is considered to be depicting the same scene.
Finding the homography between the two sets of points will allow you to also find the relative difference in shooting angle between the original pictures or the amount of overlapping.
There are a number of OpenCV tutorials/samples on this, and a nice video here. A whole OpenCV module (features2d) is dedicated to it.
Downsides: It may be slow. It is not perfect.
Over on the OpenCV Q&A site I am talking about the difference between feature descriptors, which are great when comparing whole images and texture descriptors, which are used to identify objects like human faces or cars in an image.
maybe with "and" or "or"
after false need to write "or"
after true need to write "and"
like
n=0
def returnsfalse():
global n
n=n+1
print ("false %d" % (n))
return False
def returnstrue():
global n
n=n+1
print ("true %d" % (n))
return True
n=0
returnsfalse() or returnsfalse() or returnsfalse() or returnstrue() and returnsfalse()
result:
false 1
false 2
false 3
true 4
false 5
or maybe like
(returnsfalse() or true) and (returnstrue() or true) and ...
got here by searching google "how to put multiple statments in one line python", not answers question directly, maybe somebody else needs this.
SELECT *
FROM reservations
WHERE arrival >= '2012-01-01'
AND arrival < '2013-01-01'
;
BTW if the distribution of values indicates that an index scan will not be the worth (for example if all the values are in 2012), the optimiser could still choose a full table scan. YMMV. Explain is your friend.
When running in a CI script, you will have trouble with imperative commands as create raises an error if the resource already exists.
What you can do is applying (declarative pattern) the output of your imperative command, by using --dry-run=true
and -o yaml
options:
kubectl create whatever --dry-run=true -o yaml | kubectl apply -f -
The command above will not raise an error if the resource already exists (and will update the resource if needed).
This is very useful in some cases where you cannot use the declarative pattern (for instance when creating a docker-registry secret).
It is not recommended to call gc explicitly, but if you call
GC.Collect();
GC.WaitForPendingFinalizers();
It will call GC explicitly throughout your code, don't forget to call GC.WaitForPendingFinalizers();
after GC.Collect()
.
When your native query is based on joins, in that case you can get the result as list of objects and process it.
one simple example.
@Autowired
EntityManager em;
String nativeQuery = "select name,age from users where id=?";
Query query = em.createNativeQuery(nativeQuery);
query.setParameter(1,id);
List<Object[]> list = query.getResultList();
for(Object[] q1 : list){
String name = q1[0].toString();
//..
//do something more on
}
rtsp protocol did not work for me. mjpeg worked first try. I assume it is built into my camera (Dlink DCS 900).
Syntax found here: http://answers.opencv.org/question/133/how-do-i-access-an-ip-camera/
I did not need to compile OpenCV with ffmpg support.
Modify your Jquery in following way:
$.ajax({
url: someurl,
contentType: 'application/json',
data: JSONObject,
headers: { 'Access-Control-Allow-Origin': '*' }, //add this line
dataType: 'json',
type: 'POST',
success: function (Data) {....}
});
In order for new T
to compile, T
must be a complete type. In your case, when you say new tile_tree_apple
inside the definition of tile_tree::tick
, tile_tree_apple
is incomplete (it has been forward declared, but its definition is later in your file). Try moving the inline definitions of your functions to a separate source file, or at least move them after the class definitions.
Something like:
class A
{
void f1();
void f2();
};
class B
{
void f3();
void f4();
};
inline void A::f1() {...}
inline void A::f2() {...}
inline void B::f3() {...}
inline void B::f4() {...}
When you write your code this way, all references to A and B in these methods are guaranteed to refer to complete types, since there are no more forward references!
Try this one:
Data objt = new Data(name, address, contact);
Contacts.add(objt);
If you like to have the timestamp without the timezone but local timezone do
git log -1 --format=%cd --date=local
Which gives this depending on your location
Mon Sep 28 12:07:37 2015
I reinstalled heroku toolbelt and it worked.
I was able to setup Oracle Instant Client (Basic) 11g2 and Oracle ODBC (32bit) drivers on my 32bit Windows 7 PC. Note: you'll need a 'tnsnames.ora' file because it doesn't come with one. You can Google examples and copy/paste into a text file, change the parameters for your environment.
Setting up Oracle Instant Client-Basic 11g2 (Win7 32-bit)
(I think there's another step or two if your using 64-bit)
Oracle Instant Client
ODBC Drivers
Note: The "un-documented" things that were hanging me up where...
- All files (Client and Drivers) needed to be in the same folder (nothing in sub-folders).
- Running the ODBC driver from the command prompt will allow you to see if it installs successfully. Double-clicking the installer just flashed a box on the screen, no idea it was failing because no error dialog.
After you've done this you should be able to setup a new DSN Data Source using the Oracle ODBC driver.
-Hope this helps someone else.
accept
can continuously provide new client connections. However, note that it, and other socket calls are usually blocking. Therefore you have a few options at this point:
Use the __contains__()
method of Pythons string class.:
a = ['abc-123', 'def-456', 'ghi-789', 'abc-456']
for i in a:
if i.__contains__("abc") :
print(i, " is containing")
Try this ...
StringRequest sr = new StringRequest(type,url, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
// valid response
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
// error
}
}){
@Override
protected Map<String,String> getParams(){
Map<String,String> params = new HashMap<String, String>();
params.put("username", username);
params.put("password", password);
params.put("grant_type", "password");
return params;
}
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String,String> params = new HashMap<String, String>();
// Removed this line if you dont need it or Use application/json
// params.put("Content-Type", "application/x-www-form-urlencoded");
return params;
}
We can get the UTC/GMT time stamp from the given date.
/**
* Get the time stamp in GMT/UTC by passing the valid time (dd-MM-yyyy HH:mm:ss)
*/
public static long getGMTTimeStampFromDate(String datetime) {
long timeStamp = 0;
Date localTime = new Date();
String format = "dd-MM-yyyy HH:mm:ss";
SimpleDateFormat sdfLocalFormat = new SimpleDateFormat(format);
sdfLocalFormat.setTimeZone(TimeZone.getDefault());
try {
localTime = (Date) sdfLocalFormat.parse(datetime);
Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("UTC"),
Locale.getDefault());
TimeZone tz = cal.getTimeZone();
cal.setTime(localTime);
timeStamp = (localTime.getTime()/1000);
Log.d("GMT TimeStamp: ", " Date TimegmtTime: " + datetime
+ ", GMT TimeStamp : " + localTime.getTime());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return timeStamp;
}
It will return the UTC time based on passed date.
We can do reverse like UTC time stamp to current date and time(vice versa)
public static String getLocalTimeFromGMT(long gmtTimeStamp) {
try{
Calendar calendar = Calendar.getInstance();
TimeZone tz = TimeZone.getDefault();
calendar.setTimeInMillis(gmtTimeStamp * 1000);
// calendar.add(Calendar.MILLISECOND, tz.getOffset(calendar.getTimeInMillis()));
SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
Date currenTimeZone = (Date) calendar.getTime();
return sdf.format(currenTimeZone);
}catch (Exception e) {
}
return "";
}
I hope this will help others. Thanks!!
Here is a function to do this for any number of columns.
def mean_first(df):
ncols = df.shape[1] # Get the number of columns
index = list(range(ncols)) # Create an index to reorder the columns
index.insert(0,ncols) # This puts the last column at the front
return(df.assign(mean=df.mean(1)).iloc[:,index]) # new df with last column (mean) first
$date=$year."-".$month."-".$day;
$new_date=date('Y-m-d', strtotime($dob));
$status=0;
$insert_date = date("Y-m-d H:i:s");
$latest_insert_id=0;
$insertSql="insert into participationDetail (formId,name,city,emailId,dob,mobile,status,social_media1,social_media2,visa_status,tnc_status,data,gender,insertDate)values('".$formid."','".$name."','".$city."','".$email."','".$new_date."','".$mobile."','".$status."','".$link1."','".$link2."','".$visa_check."','".$tnc_check."','".json_encode($detail_arr,JSON_HEX_APOS)."','".$gender."','".$insert_date."')";
I just created a local connection by breaking my head for hours. So thought of helping you guys.
Step 1: Check your file name listener.ora located at
C:\app\\product\12.1.0\dbhome_3\NETWORK\ADMIN
Check your HOSTNAME, PORT AND SERVICE and give the same while creating new database connection.
Step 2: if this doesnt work, try these combinations give PORT:1521
and SID: orcl
give PORT: and
SID: orcl
give PORT:1521
and SID: pdborcl
give PORT:1521
and
SID: admin
If you get the error as "wrong username and password" :
Make sure you are giving correct username and password
if still it doesnt work try this: Username :system Password: .
Hope it helps!!!!
You are misusing the API.
Here's the situation: in ASP.NET, only one thread can handle a request at a time. You can do some parallel processing if necessary (borrowing additional threads from the thread pool), but only one thread would have the request context (the additional threads do not have the request context).
This is managed by the ASP.NET SynchronizationContext
.
By default, when you await
a Task
, the method resumes on a captured SynchronizationContext
(or a captured TaskScheduler
, if there is no SynchronizationContext
). Normally, this is just what you want: an asynchronous controller action will await
something, and when it resumes, it resumes with the request context.
So, here's why test5
fails:
Test5Controller.Get
executes AsyncAwait_GetSomeDataAsync
(within the ASP.NET request context).AsyncAwait_GetSomeDataAsync
executes HttpClient.GetAsync
(within the ASP.NET request context).HttpClient.GetAsync
returns an uncompleted Task
.AsyncAwait_GetSomeDataAsync
awaits the Task
; since it is not complete, AsyncAwait_GetSomeDataAsync
returns an uncompleted Task
.Test5Controller.Get
blocks the current thread until that Task
completes.Task
returned by HttpClient.GetAsync
is completed.AsyncAwait_GetSomeDataAsync
attempts to resume within the ASP.NET request context. However, there is already a thread in that context: the thread blocked in Test5Controller.Get
.Here's why the other ones work:
test1
, test2
, and test3
): Continuations_GetSomeDataAsync
schedules the continuation to the thread pool, outside the ASP.NET request context. This allows the Task
returned by Continuations_GetSomeDataAsync
to complete without having to re-enter the request context.test4
and test6
): Since the Task
is awaited, the ASP.NET request thread is not blocked. This allows AsyncAwait_GetSomeDataAsync
to use the ASP.NET request context when it is ready to continue.And here's the best practices:
async
methods, use ConfigureAwait(false)
whenever possible. In your case, this would change AsyncAwait_GetSomeDataAsync
to be var result = await httpClient.GetAsync("http://stackoverflow.com", HttpCompletionOption.ResponseHeadersRead).ConfigureAwait(false);
Task
s; it's async
all the way down. In other words, use await
instead of GetResult
(Task.Result
and Task.Wait
should also be replaced with await
).That way, you get both benefits: the continuation (the remainder of the AsyncAwait_GetSomeDataAsync
method) is run on a basic thread pool thread that doesn't have to enter the ASP.NET request context; and the controller itself is async
(which doesn't block a request thread).
More information:
async
/await
intro post, which includes a brief description of how Task
awaiters use SynchronizationContext
.SynchronizationContext
restricts the request context to just one thread at a time.Update 2012-07-13: Incorporated this answer into a blog post.
In memory usage and speed.
When you call jsonstr = json.dumps(mydata)
it first creates a full copy of your data in memory and only then you file.write(jsonstr)
it to disk. So this is a faster method but can be a problem if you have a big piece of data to save.
When you call json.dump(mydata, file)
-- without 's', new memory is not used, as the data is dumped by chunks. But the whole process is about 2 times slower.
Source: I checked the source code of json.dump()
and json.dumps()
and also tested both the variants measuring the time with time.time()
and watching the memory usage in htop.
You can't use IF like that. You can do what you want with AND and OR:
SELECT t.first_name,
t.last_name,
t.employid,
t.status
FROM employeetable t
WHERE ((status_flag = STATUS_ACTIVE AND t.status = 'A')
OR (status_flag = STATUS_INACTIVE AND t.status = 'T')
OR (source_flag = SOURCE_FUNCTION AND t.business_unit = 'production')
OR (source_flag = SOURCE_USER AND t.business_unit = 'users'))
AND t.first_name LIKE firstname
AND t.last_name LIKE lastname
AND t.employid LIKE employeeid;
You can open any folder, so if your projects are in the same tree, just open the folder beneath them.
Otherwise you can open 2 instances of Code as another option
Use this in project.gradle:
buildscript {
repositories
{
mavenCentral()
}
dependencies {
classpath 'com.android.tools.build:gradle:2.3.0'
}
}
allprojects {
repositories {
mavenCentral()
}
}
I don't think you even need to attach it to the DOM, this seems to work for me:
$("<div>Test message</div>").dialog();
Here's a JS fiddle:
A pure solution without jQuery:
function chbg(color) {
document.getElementById('b').style.backgroundColor = color;
}
<div id="a" onmouseover="chbg('red')" onmouseout="chbg('white')">This is element a</div>
<div id="b">This is element b</div>
JSFiddle: http://jsfiddle.net/YShs2/
Like everyone else:
for i, val in enumerate(data):
print i, val
but also
for i, val in enumerate(data, 1):
print i, val
In other words, you can specify as starting value for the index/count generated by enumerate() which comes in handy if you don't want your index to start with the default value of zero.
I was printing out lines in a file the other day and specified the starting value as 1 for enumerate()
, which made more sense than 0 when displaying information about a specific line to the user.
As Peter already pointed out:
In [1]: import requests
In [2]: r = requests.get('https://api.github.com/events')
In [3]: type(r)
Out[3]: requests.models.Response
In [4]: type(r.content)
Out[4]: str
You may also want to check r.text
.
Also: https://2.python-requests.org/en/latest/user/quickstart/
Update 2018
Bootstrap 4
Now that BS4 is flexbox, the fixed-fluid is simple. Just set the width of the fixed column, and use the .col
class on the fluid column.
.sidebar {
width: 180px;
min-height: 100vh;
}
<div class="row">
<div class="sidebar p-2">Fixed width</div>
<div class="col bg-dark text-white pt-2">
Content
</div>
</div>
http://www.codeply.com/go/7LzXiPxo6a
Bootstrap 3..
One approach to a fixed-fluid layout is using media queries that align with Bootstrap's breakpoints so that you only use the fixed width columns are larger screens and then let the layout stack responsively on smaller screens...
@media (min-width:768px) {
#sidebar {
min-width: 300px;
max-width: 300px;
}
#main {
width:calc(100% - 300px);
}
}
Working Bootstrap 3 Fixed-Fluid Demo
Related Q&A:
Fixed width column with a container-fluid in bootstrap
How to left column fixed and right scrollable in Bootstrap 4, responsive?
Look at the r.status_code
attribute:
if r.status_code == 404:
# A 404 was issued.
Demo:
>>> import requests
>>> r = requests.get('http://httpbin.org/status/404')
>>> r.status_code
404
If you want requests
to raise an exception for error codes (4xx or 5xx), call r.raise_for_status()
:
>>> r = requests.get('http://httpbin.org/status/404')
>>> r.raise_for_status()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "requests/models.py", line 664, in raise_for_status
raise http_error
requests.exceptions.HTTPError: 404 Client Error: NOT FOUND
>>> r = requests.get('http://httpbin.org/status/200')
>>> r.raise_for_status()
>>> # no exception raised.
You can also test the response object in a boolean context; if the status code is not an error code (4xx or 5xx), it is considered ‘true’:
if r:
# successful response
If you want to be more explicit, use if r.ok:
.
Simple :::
scp remoteusername@remoteIP:/path/of/file /Local/path/to/copy
scp -r remoteusername@remoteIP:/path/of/folder /Local/path/to/copy
Here is another way you can get to the root of your website without hard coding the url:
var response = Request.CreateResponse(HttpStatusCode.Moved);
string fullyQualifiedUrl = Request.RequestUri.GetLeftPart(UriPartial.Authority);
response.Headers.Location = new Uri(fullyQualifiedUrl);
Note: Will only work if both your MVC website and WebApi are on the same URL
This should do:
Assembly assem = Assembly.GetExecutingAssembly();
AssemblyName aName = assem.GetName();
return aName.Version.ToString();
You can use:
File.WriteAllBytes("Foo.txt", arrBytes); // Requires System.IO
If you have an enumerable and not an array, you can use:
File.WriteAllBytes("Foo.txt", arrBytes.ToArray()); // Requires System.Linq
Using System.out.println() is bad practice (better use logging framework) -> you should not have many occurences in your code base. Using another method to simply shorten it does not seem a good option.
The .Elements operation returns a LIST of XElements - but what you really want is a SINGLE element. Add this:
XElement Contacts = (from xml2 in XMLDoc.Elements("Contacts").Elements("Node")
where xml2.Element("ID").Value == variable
select xml2).FirstOrDefault();
This way, you tell LINQ to give you the first (or NULL, if none are there) from that LIST of XElements you're selecting.
Marc
I tried to convert ddmmyy format to date("Y-m-d"
format but was not working when I directly pass ddmmyy =date('dmy')
then realized it has to be in yyyy-mm-dd format so. used substring to organize
$strParam = '20'.substr($_GET['date'], 4, 2).'-'.substr($_GET['date'], 2, 2).'-'.substr($_GET['date'], 0, 2);
then passed to date("Y-m-d",strtotime($strParam));
it worked!
If you want to use some variable, you may use this way:
String value= "your value";
driver.execute_script("document.getElementById('q').value=' "+value+" ' ");
For me just using the Integer.toString() method works for me just fine. You can convert it over if you just want to very if it is null. Example below:
private void setCarColor(int redIn, int blueIn, int greenIn)
{
//Integer s = null;
if (Integer.toString(redIn) == null || Integer.toString(blueIn) == null || Integer.toString(greenIn) == null )
This is by no means exhaustive advice. But number one thing to keep in mind when writing with the thought of avoiding future memory leaks (loops) is to make sure that anything which accepts a reference to a call-back, should store that call-back as a weak reference.
For linux:
$ strace sqlplus -L scott/tiger@orcl 2>&1| grep -i 'open.*tnsnames.ora'
shows something like this:
open("/opt/oracle/product/10.2.0/db_1/network/admin/tnsnames.ora",O_RDONLY)=7
Changing to
$ strace sqlplus -L scott/tiger@orcl 2>&1| grep -i 'tnsnames.ora'
will show all the file paths that are failing.
This worked for me:
It starts showing compilation errors in the code.
Setting the slice to nil
is the best way to clear a slice. nil
slices in go are perfectly well behaved and setting the slice to nil
will release the underlying memory to the garbage collector.
package main
import (
"fmt"
)
func dump(letters []string) {
fmt.Println("letters = ", letters)
fmt.Println(cap(letters))
fmt.Println(len(letters))
for i := range letters {
fmt.Println(i, letters[i])
}
}
func main() {
letters := []string{"a", "b", "c", "d"}
dump(letters)
// clear the slice
letters = nil
dump(letters)
// add stuff back to it
letters = append(letters, "e")
dump(letters)
}
Prints
letters = [a b c d]
4
4
0 a
1 b
2 c
3 d
letters = []
0
0
letters = [e]
1
1
0 e
Note that slices can easily be aliased so that two slices point to the same underlying memory. The setting to nil
will remove that aliasing.
This method changes the capacity to zero though.
This error can occur in several places, most commonly running further LINQ queries on top of a null collection. LINQ as Query Syntax can appear more null-safe than it is. Consider the following samples:
var filteredCollection = from item in getMyCollection()
orderby item.ReportDate
select item;
This code is not NULL SAFE, meaning that if getMyCollection()
returns a null, you'll get the Value cannot be null. Parameter name: source
error. Very annoying! But it makes perfect sense because LINQ Query syntax is just syntactic sugar for this equivalent code:
var filteredCollection = getMyCollection().OrderBy(x => x.ReportDate);
Which obviously will blow up if the starting method returns a null.
To prevent this, you can use a null coalescing operator in your LINQ query like so:
var filteredCollection = from item in getMyCollection() ??
Enumerable.Empty<CollectionItemClass>()
orderby item.ReportDate
select item;
However, you'll have to remember to do this in any related queries. The best approach (if you control the code that generates the collection) is to make it a coding practice to NEVER RETURN A NULL COLLECTION, EVER. In some cases, returning a null object from a method like "getCustomerById(string id)
" is fine, depending on your team coding style, but if you have a method that returns a collection of business objects, like "getAllcustomers()
" then it should NEVER return a null array/enumerable/etc. Always always always use an if
check, the null coalescing operator, or some other switch to return an empty array/list/enumerable etc, so that consumers of your method can freely LINQ over the results.
I am trying to explain by putting problem statement and solution to it. I hope it will help
Problem Statement:
Find all the published products, whose name like ABC Product or PQR Product, and price should be less than 15/-
Solution:
Below are the conditions that need to be taken care of
Below is the statement that applies above criterion to create query and fetch data.
$elements = $collection->find(
Array(
[price] => Array( [$lt] => 15 ),
[$or] => Array(
[0]=>Array(
[product_name]=>Array(
[$in]=>Array(
[0] => ABC Product,
[1]=> PQR Product
)
)
)
),
[state]=>Published
)
);
Change:
<select name="select2" ...
To:
<select name="select2[]" ...
You can't extend Enum
as it's a static class. You can only extend instances of a type. With this in mind, you're going to have to create a static method yourself to do this; the following should work when combined with your existing method GetDescription
:
public static class EnumHelper
{
public static T GetEnumFromString<T>(string value)
{
if (Enum.IsDefined(typeof(T), value))
{
return (T)Enum.Parse(typeof(T), value, true);
}
else
{
string[] enumNames = Enum.GetNames(typeof(T));
foreach (string enumName in enumNames)
{
object e = Enum.Parse(typeof(T), enumName);
if (value == GetDescription((Enum)e))
{
return (T)e;
}
}
}
throw new ArgumentException("The value '" + value
+ "' does not match a valid enum name or description.");
}
}
And the usage of it would be something like this:
Animal giantPanda = EnumHelper.GetEnumFromString<Animal>("Giant Panda");
If it has something to do control updates on cached pages here I have a nice method how to do this.
www.yoursite.com/page/about?getVer=1&__[date]
This method requires at least one request even when no request is needed because it already exists in the local browser cache. But the overhead is less comparing to using no cache at all (to be sure the page will show the right updated content). This requires just a few bytes for each page request instead of all content for each page.
IMPORTANT: The version info request must be implemented on your server otherwise it will return the whole page.
Example of version string returned by www.yoursite.com/page/about?getVer=1&__[date]
:
skg2pl-v8kqb
To give you an example in code, here is a part of my library (I don't think you can use it but maybe it gives you some idea how to do it):
o.gCheckDocVersion = function() // Because of the hard caching method, check document for changes with ajax
{
var sUrl = o.getQuerylessUrl(window.location.href),
sDocVer = o.gGetData( sUrl, false );
o.ajaxRequest({ url:sUrl+'?getVer=1&'+o.uniqueId(), cache:0, dataType:'text' },
function(sVer)
{
if( typeof sVer == 'string' && sVer.length )
{
var bReload = (( typeof sDocVer == 'string' ) && sDocVer != sVer );
if( bReload || !sDocVer )
{
o.gSetData( sUrl, sVer );
sDocVer = o.gGetData( sUrl, false );
if( bReload && ( typeof sDocVer != 'string' || sDocVer != sVer ))
{ bReload = false; }
}
if( bReload )
{ // Hard refresh page contents
window.location.reload(true); }
}
}, false, false );
};
If you are using version independent resources like javascript or css files, add versionnumbers (implemented with a url rewrite and not with a query because they mostly won't be cached). For example: www.yoursite.com/ver-01/about.js
For me, this method is working great, maybe it can help you too.
If the "default value" you want is immutable, @eduffy's suggestion, e.g. [0]*10
, is good enough.
But if you want, say, a list of ten dict
s, do not use [{}]*10
-- that would give you a list with the same initially-empty dict
ten times, not ten distinct ones. Rather, use [{} for i in range(10)]
or similar constructs, to construct ten separate dict
s to make up your list.
just wrap your content with a table like this:
<table width="100%" height="100%">
<tr align="center">
<th align="center">
text
</th>
</tr>
</table><
Here is a helper method to do the job.
First of all you'll need a new Comparator interface, as Comparator doesn't support primitives:
public interface IntComparator{
public int compare(int a, int b);
}
(You could of course do it with autoboxing / unboxing but I won't go there, that's ugly)
Then, here's a helper method to sort an int array using this comparator:
public static void sort(final int[] data, final IntComparator comparator){
for(int i = 0; i < data.length + 0; i++){
for(int j = i; j > 0
&& comparator.compare(data[j - 1], data[j]) > 0; j--){
final int b = j - 1;
final int t = data[j];
data[j] = data[b];
data[b] = t;
}
}
}
And here is some client code. A stupid comparator that sorts all numbers that consist only of the digit '9' to the front (again sorted by size) and then the rest (for whatever good that is):
final int[] data =
{ 4343, 544, 433, 99, 44934343, 9999, 32, 999, 9, 292, 65 };
sort(data, new IntComparator(){
@Override
public int compare(final int a, final int b){
final boolean onlyNinesA = this.onlyNines(a);
final boolean onlyNinesB = this.onlyNines(b);
if(onlyNinesA && !onlyNinesB){
return -1;
}
if(onlyNinesB && !onlyNinesA){
return 1;
}
return Integer.valueOf(a).compareTo(Integer.valueOf(b));
}
private boolean onlyNines(final int candidate){
final String str = String.valueOf(candidate);
boolean nines = true;
for(int i = 0; i < str.length(); i++){
if(!(str.charAt(i) == '9')){
nines = false;
break;
}
}
return nines;
}
});
System.out.println(Arrays.toString(data));
Output:
[9, 99, 999, 9999, 32, 65, 292, 433, 544, 4343, 44934343]
The sort code was taken from Arrays.sort(int[]), and I only used the version that is optimized for tiny arrays. For a real implementation you'd probably want to look at the source code of the internal method sort1(int[], offset, length)
in the Arrays class.
The question has been answered, but for your future coding reference you might like to consider this.
In your HTML, add the name as an attribute to the button and remove the onclick reference.
<button id="button" data-name="Mathew" type="button">click</button>
In your JavaScript, grab the button using its ID, assign the function to the button's click
event, and use the function to display the button's data-name attribute.
var button = document.getElementById('button');
button.onclick = myfunction;
function myfunction() {
var name = this.getAttribute('data-name');
alert(name);
}
There must be some syntax error. Copy/paste this code and see if it works:
<?php
$link = mysql_connect('localhost', 'root', '');
if (!$link) {
die('Could not connect:' . mysql_error());
}
echo 'Connected successfully';
?
I had the same error message. It turns out I was using the msql_connect()
function instead of mysql_connect()
.
Use .text() to extract the content of the div
var text = $('#field-function_purpose').text()
The follows might be helpful:
# Valid font size are xx-small, x-small, small, medium, large, x-large, xx-large, larger, smaller, None
plt.xticks(
rotation=45,
horizontalalignment='right',
fontweight='light',
fontsize='medium',
)
Here is the function xticks
[reference] with example and API
def xticks(ticks=None, labels=None, **kwargs):
"""
Get or set the current tick locations and labels of the x-axis.
Call signatures::
locs, labels = xticks() # Get locations and labels
xticks(ticks, [labels], **kwargs) # Set locations and labels
Parameters
----------
ticks : array_like
A list of positions at which ticks should be placed. You can pass an
empty list to disable xticks.
labels : array_like, optional
A list of explicit labels to place at the given *locs*.
**kwargs
:class:`.Text` properties can be used to control the appearance of
the labels.
Returns
-------
locs
An array of label locations.
labels
A list of `.Text` objects.
Notes
-----
Calling this function with no arguments (e.g. ``xticks()``) is the pyplot
equivalent of calling `~.Axes.get_xticks` and `~.Axes.get_xticklabels` on
the current axes.
Calling this function with arguments is the pyplot equivalent of calling
`~.Axes.set_xticks` and `~.Axes.set_xticklabels` on the current axes.
Examples
--------
Get the current locations and labels:
>>> locs, labels = xticks()
Set label locations:
>>> xticks(np.arange(0, 1, step=0.2))
Set text labels:
>>> xticks(np.arange(5), ('Tom', 'Dick', 'Harry', 'Sally', 'Sue'))
Set text labels and properties:
>>> xticks(np.arange(12), calendar.month_name[1:13], rotation=20)
Disable xticks:
>>> xticks([])
"""
I think using nested list comprehensions is the most elegant way to solve this, because the intermediate result is the position where the element is. An implementation would be:
list =[ ['a','b'], ['a','c'], ['b','d'] ]
search = 'c'
any([ (list.index(x),x.index(y)) for x in list for y in x if y == search ] )
In my case I got this error because of a line
<script src="#"></script>
Chrome tried to interpret the current HTML file then as javascript.
This is how I am comparing 2 dates, now() and a date from the table
@if (\Carbon\Carbon::now()->lte($item->client->event_date_from))
.....
.....
@endif
Should work just right. I have used the comparison functions provided by Carbon.
A quick true/false test of whether it will cast to [int]
[bool]($var -as [int] -is [int])
The file format would permit up to 255-character worksheet names, but if the Excel UI doesn't want you exceeding 31 characters, don't try to go beyond 31. App's full of weird undocumented limits and quirks, and feeding it files that are within spec but not within the range of things the testers would have tested usually causes REALLY strange behavior. (Personal favorite example: using the Excel 4.0 bytecode for an if() function, in a file with an Excel 97-style stringtable, disabled the toolbar button for bold in Excel 97.)
I try this. I hope to help. It work with
static void Main()
{
string[,] matrix = {
{ "aa", "aaa" },
{ "bb", "bbb" }
};
int index = 0;
foreach (string element in matrix)
{
if (index < matrix.GetLength(1))
{
Console.Write(element);
if (index < (matrix.GetLength(1) - 1))
{
Console.Write(" ");
}
index++;
}
if (index == matrix.GetLength(1))
{
Console.Write("\n");
index = 0;
}
}
return false;
return false;
does 3 separate things when you call it:
event.preventDefault()
– It stops the browsers default behaviour.event.stopPropagation()
– It prevents the event from propagating (or “bubbling up”) the DOM.Note that this behaviour differs from normal (non-jQuery) event handlers, in which, notably, return false
does not stop the event from bubbling up.
preventDefault();
preventDefault();
does one thing: It stops the browsers default behaviour.
When to use them?
We know what they do but when to use them? Simply it depends on what you want to accomplish. Use preventDefault();
if you want to “just” prevent the default browser behaviour. Use return false; when you want to prevent the default browser behaviour and prevent the event from propagating the DOM. In most situations where you would use return false; what you really want is preventDefault()
.
Examples:
Let’s try to understand with examples:
We will see pure JAVASCRIPT example
Example 1:
<div onclick='executeParent()'>_x000D_
<a href='https://stackoverflow.com' onclick='executeChild()'>Click here to visit stackoverflow.com</a>_x000D_
</div>_x000D_
<script>_x000D_
function executeChild() {_x000D_
alert('Link Clicked');_x000D_
}_x000D_
_x000D_
function executeParent() {_x000D_
alert('div Clicked');_x000D_
}_x000D_
</script>
_x000D_
Run the above code you will see the hyperlink ‘Click here to visit stackoverflow.com‘ now if you click on that link first you will get the javascript alert Link Clicked Next you will get the javascript alert div Clicked and immediately you will be redirected to stackoverflow.com.
Example 2:
<div onclick='executeParent()'>_x000D_
<a href='https://stackoverflow.com' onclick='executeChild()'>Click here to visit stackoverflow.com</a>_x000D_
</div>_x000D_
<script>_x000D_
function executeChild() {_x000D_
event.preventDefault();_x000D_
event.currentTarget.innerHTML = 'Click event prevented'_x000D_
alert('Link Clicked');_x000D_
}_x000D_
_x000D_
function executeParent() {_x000D_
alert('div Clicked');_x000D_
}_x000D_
</script>
_x000D_
Run the above code you will see the hyperlink ‘Click here to visit stackoverflow.com‘ now if you click on that link first you will get the javascript alert Link Clicked Next you will get the javascript alert div Clicked Next you will see the hyperlink ‘Click here to visit stackoverflow.com‘ replaced by the text ‘Click event prevented‘ and you will not be redirected to stackoverflow.com. This is due > to event.preventDefault() method we used to prevent the default click action to be triggered.
Example 3:
<div onclick='executeParent()'>_x000D_
<a href='https://stackoverflow.com' onclick='executeChild()'>Click here to visit stackoverflow.com</a>_x000D_
</div>_x000D_
<script>_x000D_
function executeChild() {_x000D_
event.stopPropagation();_x000D_
event.currentTarget.innerHTML = 'Click event prevented'_x000D_
alert('Link Clicked');_x000D_
}_x000D_
_x000D_
function executeParent() {_x000D_
alert('div Clicked');_x000D_
}_x000D_
</script>
_x000D_
This time if you click on Link the function executeParent() will not be called and you will not get the javascript alert div Clicked this time. This is due to us having prevented the propagation to the parent div using event.stopPropagation() method. Next you will see the hyperlink ‘Click here to visit stackoverflow.com‘ replaced by the text ‘Click event is going to be executed‘ and immediately you will be redirected to stackoverflow.com. This is because we haven’t prevented the default click action from triggering this time using event.preventDefault() method.
Example 4:
<div onclick='executeParent()'>_x000D_
<a href='https://stackoverflow.com' onclick='executeChild()'>Click here to visit stackoverflow.com</a>_x000D_
</div>_x000D_
<script>_x000D_
function executeChild() {_x000D_
event.preventDefault();_x000D_
event.stopPropagation();_x000D_
event.currentTarget.innerHTML = 'Click event prevented'_x000D_
alert('Link Clicked');_x000D_
}_x000D_
_x000D_
function executeParent() {_x000D_
alert('Div Clicked');_x000D_
}_x000D_
</script>
_x000D_
If you click on the Link, the function executeParent() will not be called and you will not get the javascript alert. This is due to us having prevented the propagation to the parent div using event.stopPropagation() method. Next you will see the hyperlink ‘Click here to visit stackoverflow.com‘ replaced by the text ‘Click event prevented‘ and you will not be redirected to stackoverflow.com. This is because we have prevented the default click action from triggering this time using event.preventDefault() method.
Example 5:
For return false I have three examples and all appear to be doing the exact same thing (just returning false), but in reality the results are quite different. Here's what actually happens in each of the above.
cases:
Will see all three example.
<div onclick='executeParent()'>_x000D_
<a href='https://stackoverflow.com' onclick='return false'>Click here to visit stackoverflow.com</a>_x000D_
</div>_x000D_
<script>_x000D_
var link = document.querySelector('a');_x000D_
_x000D_
link.addEventListener('click', function() {_x000D_
event.currentTarget.innerHTML = 'Click event prevented using inline html'_x000D_
alert('Link Clicked');_x000D_
});_x000D_
_x000D_
_x000D_
function executeParent() {_x000D_
alert('Div Clicked');_x000D_
}_x000D_
</script>
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div>_x000D_
<a href='https://stackoverflow.com'>Click here to visit stackoverflow.com</a>_x000D_
</div>_x000D_
<script>_x000D_
$('a').click(function(event) {_x000D_
alert('Link Clicked');_x000D_
$('a').text('Click event prevented using return FALSE');_x000D_
$('a').contents().unwrap();_x000D_
return false;_x000D_
});_x000D_
$('div').click(function(event) {_x000D_
alert('Div clicked');_x000D_
});_x000D_
</script>
_x000D_
<div onclick='executeParent()'>_x000D_
<a href='https://stackoverflow.com' onclick='executeChild()'>Click here to visit stackoverflow.com</a>_x000D_
</div>_x000D_
<script>_x000D_
function executeChild() {_x000D_
event.currentTarget.innerHTML = 'Click event prevented'_x000D_
alert('Link Clicked');_x000D_
return false_x000D_
}_x000D_
_x000D_
function executeParent() {_x000D_
alert('Div Clicked');_x000D_
}_x000D_
</script>
_x000D_
Hope these examples are clear. Try executing all these examples in a html file to see how they work.
#div-name
{
background-image: url('../images/background-art-main.jpg');
background-position: top right 50px;
background-repeat: no-repeat;
}
If you only want to ssh a few times, such as on a borrowed or shared computer, try:
ssh buck@hostname
or
ssh -l buck hostname
in C#:
new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1).AddMonths(-1)
new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1).AddDays(-1)
Found a solution.
1) Go to where your SDK is located that android studio/eclipse is using.
If you are using Android studio, go to extras\android\m2repository\com\android\support\
.
If you are using eclipse, go to \extras\android\support\
2) See what folders you have, for me I had gridlayout-v7, support-v4 and support-v13.
3) click into support-v4 and see what number the following folder is, mine was named 13.0
Since you are using "com.android.support:support-v4:18.0.+", change this to reflect what version you have, for example I have support-v4 so first part v4 stays the same. Since the next path is 13.0, change your 18.0 to:
"com.android.support:support-v4:13.0.+"
This worked for me, hope it helps!
Update:
I noticed I had android studio set up with the wrong SDK which is why originally had difficulty updating! The path should be C:\Users\Username\AppData\Local\Android\android-sdk\extras\
Also note, if your SDK is up to date, the code will be:
"com.android.support:support-v4:19.0.+"
Similar to Julien's answer above, I had success with the following:
fig, ax = plt.subplots(figsize=(10,4))
for key, grp in df.groupby(['ticker']):
ax.plot(grp['Date'], grp['adj_close'], label=key)
ax.legend()
plt.show()
This solution might be more relevant if you want more control in matlab.
Solution inspired by: https://stackoverflow.com/a/52526454/10521959
After trying to add the path using:
pip show
on command prompt and using
sys.path.insert(0, "/home/myname/pythonfiles")
and didn't work. Also got SSL error when trying to install the module again using conda this time instead of pip.
I simply copied the module that wasn't found from the path "Mine was in
C:\Users\user\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.7_qbz5n2kfra8p0\LocalCache\local-packages\Python37\site-packages
so I copied it to 'C:\Users\user\Anaconda3\Lib\site-packages'
This is my very simple c++ program to list down the prime numbers in between 2 and 100.
for(int j=2;j<=100;++j)
{
int i=2;
for(;i<=j-1;i++)
{
if(j%i == 0)
break;
}
if(i==j && i != 2)
cout<<j<<endl;
}
Use FB static method getCurrentProfile() of Profile class to retrieve those info.
Profile profile = Profile.getCurrentProfile();
String firstName = profile.getFirstName());
System.out.println(profile.getProfilePictureUri(20,20));
System.out.println(profile.getLinkUri());
No one of the previous answers (which all are correct) was suited to my situation: I don't use the async
parameter in jQuery.ajax()
and I don't include a script tag as part of the content that was being returned like:
<div>
SOME CONTENT HERE
</div>
<script src="/scripts/script.js"></script>
My situation is that I am calling two AJAX requests consecutively with the aim to update two divs at the same time:
function f1() {
$.ajax(...); // XMLHTTP request to url_1 and append result to div_1
}
function f2() {
$.ajax(...); // XMLHTTP request to url_2 and append result to div_2
}
function anchor_f1(){
$('a.anchor1').click(function(){
f1();
})
}
function anchor_f2(){
$('a.anchor2').click(function(){
f2();
});
}
// the listener of anchor 3 the source of problem
function anchor_problem(){
$('a.anchor3').click(function(){
f1();
f2();
});
}
anchor_f1();
anchor_f2();
anchor_problem();
When I click on a.anchor3
, it raises the warning flag.I resolved the issue by replacing f2 invoking by click()
function:
function anchor_problem(){
$('a.anchor_problem').click(function(){
f1();
$('a.anchor_f2').click();
});
}
If you are converting to HTML, you can set the size of the image using HTML syntax using:
<img src="path/to/image" height="400px" width="300px" />
or whatever height and width you would want to give.
Try this:
DateTime.Now.ToString("yyyy-MM-ddThh:mm:sszzz");
zzz
is the timezone offset.
unique_ptr<char[]>
can be used where you want the performance of C and convenience of C++. Consider you need to operate on millions (ok, billions if you don't trust yet) of strings. Storing each of them in a separate string
or vector<char>
object would be a disaster for the memory (heap) management routines. Especially if you need to allocate and delete different strings many times.
However, you can allocate a single buffer for storing that many strings. You wouldn't like char* buffer = (char*)malloc(total_size);
for obvious reasons (if not obvious, search for "why use smart ptrs"). You would rather like unique_ptr<char[]> buffer(new char[total_size]);
By analogy, the same performance&convenience considerations apply to non-char
data (consider millions of vectors/matrices/objects).
tabindex
is a global attribute responsible for two things:
In my mind the second thing is even more important than the first one. There are very few elements that are focusable by default (e.g. <a> and form controls). Developers very often add some JavaScript event handlers (like 'onclick') on not focusable elements (<div>, <span> and so on), and the way to make your interface be responsive not only to mouse events but also to keyboard events (e.g. 'onkeypress') is to make such elements focusable. Lastly, if you don't want to set the order but just make your element focusable use tabindex="0"
on all such elements:
<div tabindex="0"></div>
Also, if you don't want it to be focusable via the tab key then use tabindex="-1"
. For example, the below link will not be focused while using tab keys to traverse.
<a href="#" tabindex="-1">Tab key cannot reach here!</a>
I had the same problem. It was because I had accidentally used a relative path with the symbolic link.
Are you sure you used full paths, e.g.:
ln -s /etc/nginx/sites-available/example.com.conf /etc/nginx/sites-enabled/example.com.conf
Using Swift 3 (Xcode 8.3)
func deviceName() -> String {
var systemInfo = utsname()
uname(&systemInfo)
let str = withUnsafePointer(to: &systemInfo.machine.0) { ptr in
return String(cString: ptr)
}
return str
}
Note: According to official dev forum answer, it is safe to use tuples in this way. Memory alignment for the big Int8 tuple will be the same as if it were a big Int8 array. ie: contiguous and not-padded.
I had this problem and I solved it when I understood that it was looking for the Windows Registry specified in the brackets.
Since the error was happening only in one computer, what I had to do was export the registry from the computer that it was working and install it on the computer that was missing it.
Just convert it to timestamp
datetime.datetime.fromtimestamp(ms/1000.0)
function news_get_by_id ( $news_id )
{
$this->db->select('*');
$this->db->select("DATE_FORMAT( date, '%d.%m.%Y' ) as date_human", FALSE );
$this->db->select("DATE_FORMAT( date, '%H:%i') as time_human", FALSE );
$this->db->from('news');
$this->db->where('news_id', $news_id );
$query = $this->db->get();
if ( $query->num_rows() > 0 )
{
$row = $query->row_array();
return $row;
}
}
This
You're missing service name:
SQL> connect username/password@hostname:port/SERVICENAME
EDIT
If you can connect to the database from other computer try running there:
select sys_context('USERENV','SERVICE_NAME') from dual
and
select sys_context('USERENV','SID') from dual
Use Ctrl + F11. This will rotate your emulator.
In the view from a processor, It can be described by this pic
In the view from a processor, It can be described by this pic
To solve this issue it can also help to delete and recreate the *.sln.DotSettings
file of the associated solution.
Check out Jazor. It's a simple command line JSON parser written in Ruby.
gem install jazor
jazor --help
You can use the standard HTML title attribute of image for this:
<img src="source of image" alt="alternative text" title="this will be displayed as a tooltip"/>
To summarize and explain visually how it works. Code construction is as follows:
par(mar = c(3,2,2,1))
barplot(...all parameters...)
title("Title text", adj = 0.5, line = 0)
explanation:
par(mar = c(low, left, top, right)) - margins of the graph area.
title("text" - title text
adj = from left (0) to right (1) with anything in between: 0.1, 0.2, etc...
line = positive values move title text up, negative - down)
There are two crucial nonobvious settings that I've discovered when tuning linked servers on Excel under SQL Server 2014. With those settings, ' FROM OPENDATASOURCE(''Microsoft.ACE.OLEDB.16.0'', ...)'
as well as '... FROM [' + @srv_name + ']...data AS xl ...'
function properly.
This is just for context.
DECLARE @DB_NAME NVARCHAR(30) = DB_NAME();
DECLARE @srv_name nvarchar(64) = N'<srv_base_name>@' + @DB_NAME; --to distinguish linked server usage by different databases
EXEC sp_addlinkedserver
@server=@srv_name,
@srvproduct=N'OLE DB Provider for ACE 16.0',
@provider= N'Microsoft.ACE.OLEDB.16.0',
@datasrc= '<local_file_path>\<excel_workbook_name>.xlsx',
@provstr= N'Excel 12.0;HDR=YES;IMEX=0'
;
@datasrc
: Encoding is crucial here: varchar instead of
nvarchar.@provstr
: Verion, settings and sytax are important!@provider
: Specify the provider installed in your SQL Server environment. Available providers are enumerated under Server Objects::Linked Servers::Providers
in SSMS's Object Explorer.This is the first crucial setting.
Even for SA
like for any other SQL Server login:
EXEC sp_addlinkedsrvlogin @rmtsrvname = @srv_name, @locallogin = N'sa', @useself = N'False', @rmtuser = N'admin', @rmtpassword = N''
;
@rmtuser
: It should be admin
. Actually, there is no any admin
in Windows logins on the system at the same time.@rmtpassword
: It should be an empty string.This is the second crucial setting.
Setting Ad Hoc Distributed Queries
to 1 is not enough.
One should set to 0
the DisallowAdhocAccess
registry key explicitly for the driver specified to @provider
:
[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Microsoft SQL Server\MSSQL12.DEF_INST\Providers\Microsoft.ACE.OLEDB.16.0]
"DisallowAdhocAccess"=dword:00000000
If you get the context via the parameter list of Configure in Startup.cs, You can instead do this:
public void Configure(IApplicationBuilder app, IHostingEnvironment env, LoggerFactory loggerFactory,
ApplicationDbContext context)
{
context.Database.Migrate();
...
In C++ both struct
& class
are equal except struct's
default member access specifier is public
& class has private
.
The reason for having struct
in C++ is C++ is a superset of C and must have backward compatible with legacy C types
.
For example if the language user tries to include some C header file legacy-c.h
in his C++ code & it contains struct Test {int x,y};
. Members of struct Test
should be accessible as like C.
Let us take an interview Question. There is a method that throws NullPointerException in the superclass. Can we override it with a method that throws RuntimeException?
To answer this question, let us know what is an Unchecked and Checked exception.
Checked exceptions must be explicitly caught or propagated as described in Basic try-catch-finally Exception Handling. Unchecked exceptions do not have this requirement. They don't have to be caught or declared thrown.
Checked exceptions in Java extend the java.lang.Exception class. Unchecked exceptions extend the java.lang.RuntimeException.
public class NullPointerException extends RuntimeException
Unchecked exceptions extend the java.lang.RuntimeException. Thst's why NullPointerException is an Uncheked exception.
Let's take an example: Example 1 :
public class Parent {
public void name() throws NullPointerException {
System.out.println(" this is parent");
}
}
public class Child extends Parent{
public void name() throws RuntimeException{
System.out.println(" child ");
}
public static void main(String[] args) {
Parent parent = new Child();
parent.name();// output => child
}
}
The program will compile successfully. Example 2:
public class Parent {
public void name() throws RuntimeException {
System.out.println(" this is parent");
}
}
public class Child extends Parent{
public void name() throws NullPointerException {
System.out.println(" child ");
}
public static void main(String[] args) {
Parent parent = new Child();
parent.name();// output => child
}
}
The program will also compile successfully. Therefore it is evident, that nothing happens in case of Unchecked exceptions. Now, let's take a look what happens in case of Checked exceptions. Example 3: When base class and child class both throws a checked exception
public class Parent {
public void name() throws IOException {
System.out.println(" this is parent");
}
}
public class Child extends Parent{
public void name() throws IOException{
System.out.println(" child ");
}
public static void main(String[] args) {
Parent parent = new Child();
try {
parent.name();// output=> child
}catch( Exception e) {
System.out.println(e);
}
}
}
The program will compile successfully. Example 4: When child class method is throwing border checked exception compared to the same method of base class.
import java.io.IOException;
public class Parent {
public void name() throws IOException {
System.out.println(" this is parent");
}
}
public class Child extends Parent{
public void name() throws Exception{ // broader exception
System.out.println(" child ");
}
public static void main(String[] args) {
Parent parent = new Child();
try {
parent.name();//output=> Compilation failure
}catch( Exception e) {
System.out.println(e);
}
}
}
The program will fail to compile. So, we have to be careful when we are using Checked exceptions.
Unlike PHP where you can do an MD5 hashing of your text by just calling md5 function ie md5($text)
, in Java it was made little bit complicated. I usually implemented it by calling a function which returns the md5 hash text.
Here is how I implemented it, First create a function named md5hashing
inside your main class as given below.
public static String md5hashing(String text)
{ String hashtext = null;
try
{
String plaintext = text;
MessageDigest m = MessageDigest.getInstance("MD5");
m.reset();
m.update(plaintext.getBytes());
byte[] digest = m.digest();
BigInteger bigInt = new BigInteger(1,digest);
hashtext = bigInt.toString(16);
// Now we need to zero pad it if you actually want the full 32 chars.
while(hashtext.length() < 32 ){
hashtext = "0"+hashtext;
}
} catch (Exception e1)
{
// TODO: handle exception
JOptionPane.showMessageDialog(null,e1.getClass().getName() + ": " + e1.getMessage());
}
return hashtext;
}
Now call the function whenever you needed as given below.
String text = textFieldName.getText();
String pass = md5hashing(text);
Here you can see that hashtext is appended with a zero to make it match with md5 hashing in PHP.
Solution with method String::repeat (Java 11)
String str = "Apple";
String formatted = "0".repeat(8 - str.length()) + str;
If needed change 8 to another number or parameterize it
This code will print each individual number:
for myList in [[10,13,17],[3,5,1],[13,11,12]]:
for item in myList:
print(item)
Or for your specific use case:
((50 - List1[0][0]) + List1[0][1]) - List1[0][2]
use the pow
function (it takes float
s/double
s though).
man pow
:
#include <math.h>
double pow(double x, double y);
float powf(float x, float y);
long double powl(long double x, long double y);
EDIT: For the special case of positive integer powers of 2
, you can use bit shifting: (1 << x)
will equal 2
to the power x
. There are some potential gotchas with this, but generally, it would be correct.
For MAC after doing lot of research it worked for me..! 1. Install the beyond compare and this will be installed in below location
/Applications/Beyond\ Compare.app/Contents/MacOS/bcomp
Please follow these steps to make bc as diff/merge tool in git http://www.scootersoftware.com/support.php?zz=kb_mac
You can use wc function in library qdap:
> str1 <- "How many words are in this sentence"
> wc(str1)
[1] 7