For my project's setup, "${pageContext.request.contextPath}"= refers to "src/main/webapp". Another way to tell is by right clicking on your project in Eclipse and then going to Properties:
In case if anyone wants to create there own exponential function using recursion, below is for your reference.
public static double power(double value, double p) {
if (p <= 0)
return 1;
return value * power(value, p - 1);
}
We can use [(ngModel)] in following way and have a value selection variable radioSelected
app.component.html
<div class="text-center mt-5">
<h4>Selected value is {{radioSel.name}}</h4>
<div>
<ul class="list-group">
<li class="list-group-item" *ngFor="let item of itemsList">
<input type="radio" [(ngModel)]="radioSelected" name="list_name" value="{{item.value}}" (change)="onItemChange(item)"/>
{{item.name}}
</li>
</ul>
</div>
<h5>{{radioSelectedString}}</h5>
</div>
app.component.ts
import {Item} from '../app/item';
import {ITEMS} from '../app/mock-data';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'app';
radioSel:any;
radioSelected:string;
radioSelectedString:string;
itemsList: Item[] = ITEMS;
constructor() {
this.itemsList = ITEMS;
//Selecting Default Radio item here
this.radioSelected = "item_3";
this.getSelecteditem();
}
// Get row item from array
getSelecteditem(){
this.radioSel = ITEMS.find(Item => Item.value === this.radioSelected);
this.radioSelectedString = JSON.stringify(this.radioSel);
}
// Radio Change Event
onItemChange(item){
this.getSelecteditem();
}
}
Sample Data for Listing
export const ITEMS: Item[] = [
{
name:'Item 1',
value:'item_1'
},
{
name:'Item 2',
value:'item_2'
},
{
name:'Item 3',
value:'item_3'
},
{
name:'Item 4',
value:'item_4'
},
{
name:'Item 5',
value:'item_5'
}
];
Use jQuery:
$.ajax({ url: 'your-url', success: function(data) { alert(data); } });
This data is your HTML.
Without jQuery (just JavaScript):
function makeHttpObject() {
try {return new XMLHttpRequest();}
catch (error) {}
try {return new ActiveXObject("Msxml2.XMLHTTP");}
catch (error) {}
try {return new ActiveXObject("Microsoft.XMLHTTP");}
catch (error) {}
throw new Error("Could not create HTTP request object.");
}
var request = makeHttpObject();
request.open("GET", "your_url", true);
request.send(null);
request.onreadystatechange = function() {
if (request.readyState == 4)
alert(request.responseText);
};
Best way to swap images with javascript with left vertical clickable thumbnails
SCRIPT FILE: function swapImages() {
window.onload = function () {
var img = document.getElementById("img_wrap");
var imgall = img.getElementsByTagName("img");
var firstimg = imgall[0]; //first image
for (var a = 0; a <= imgall.length; a++) {
setInterval(function () {
var rand = Math.floor(Math.random() * imgall.length);
firstimg.src = imgall[rand].src;
}, 3000);
imgall[1].onmouseover = function () {
//alert("what");
clearInterval();
firstimg.src = imgall[1].src;
}
imgall[2].onmouseover = function () {
clearInterval();
firstimg.src = imgall[2].src;
}
imgall[3].onmouseover = function () {
clearInterval();
firstimg.src = imgall[3].src;
}
imgall[4].onmouseover = function () {
clearInterval();
firstimg.src = imgall[4].src;
}
imgall[5].onmouseover = function () {
clearInterval();
firstimg.src = imgall[5].src;
}
}
}
}
If you want the image to load and display a particular image, then use .src
to load that image URL.
If you want a piece of meta data (on any tag) that can contain a URL, then use data-src
or any data-xxx
that you want to select.
MDN documentation on data-xxxx attributes: https://developer.mozilla.org/en-US/docs/DOM/element.dataset
Example of src
on an image tag where the image loads the JPEG for you and displays it:
<img id="myImage" src="http://mydomain.com/foo.jpg">
<script>
var imageUrl = document.getElementById("myImage").src;
</script>
Example of 'data-src' on a non-image tag where the image is not loaded yet - it's just a piece of meta data on the div tag:
<div id="myDiv" data-src="http://mydomain.com/foo.jpg">
<script>
// in all browsers
var imageUrl = document.getElementById("myDiv").getAttribute("data-src");
// or in modern browsers
var imageUrl = document.getElementById("myDiv").dataset.src;
</script>
Example of data-src
on an image tag used as a place to store the URL of an alternate image:
<img id="myImage" src="http://mydomain.com/foo.jpg" data-src="http://mydomain.com/foo.jpg">
<script>
var item = document.getElementById("myImage");
// switch the image to the URL specified in data-src
item.src = item.dataset.src;
</script>
There's another good way, just edit the file apache2.conf
theres a line at the end
IncludeOptional sites-enabled/*.conf
just remove the .conf
at the end, like this
IncludeOptional sites-enabled/*
and restart the server.
(I tried this only in the Ubuntu 13.10, when I updated it.)
What you have is correct, though you will not call it global, it is a class attribute and can be accessed via class e.g Shape.lolwut
or via an instance e.g. shape.lolwut
but be careful while setting it as it will set an instance level attribute not class attribute
class Shape(object):
lolwut = 1
shape = Shape()
print Shape.lolwut, # 1
print shape.lolwut, # 1
# setting shape.lolwut would not change class attribute lolwut
# but will create it in the instance
shape.lolwut = 2
print Shape.lolwut, # 1
print shape.lolwut, # 2
# to change class attribute access it via class
Shape.lolwut = 3
print Shape.lolwut, # 3
print shape.lolwut # 2
output:
1 1 1 2 3 2
Somebody may expect output to be 1 1 2 2 3 3
but it would be incorrect
Try this:
function someFunction(site)
{
return site.replace(/\/$/, "");
}
I met the same situation under windows, and searched for the solution.
Seeing this post Install mysql-python (Windows).
It points out installing such a pip environment is difficult, needs many other dependencies.
But I finally know that if we use mysqlclient
with a version down to 1.3.4
, it don't need that requirements any more, so try:
pip install mysqlclient==1.3.4
I just discovered a workaround for this problem that is so simple, and yet I haven't found any discussions anywhere that mention it. It does require control of the parent frame.
In your iFrame, say you want this iframe: src="http://www.example.com/mypage.php"
Well, instead of HTML to specify the iframe, use a javascript to build the HTML for your iframe, get the parent url through javascript "at build time", and send it as a url GET parameter in the querystring of your src target, like so:
<script type="text/javascript">
url = parent.document.URL;
document.write('<iframe src="http://example.com/mydata/page.php?url=' + url + '"></iframe>');
</script>
Then, find yourself a javascript url parsing function that parses the url string to get the url variable you are after, in this case it's "url".
I found a great url string parser here: http://www.netlobo.com/url_query_string_javascript.html
Try adding a view users/show.json.erb
This should be rendered when you make a request for the JSON format, and you get the added benefit of it being rendered by erb too, so your file could look something like this
{
"first_name": "<%= @user.first_name.to_json %>",
"last_name": "<%= @user.last_name.to_json %>"
}
Since we know that i
is an int
, you can just go ahead and unsigneding it!
This would do the trick:
int i = -62;
unsigned int j = unsigned(i);
GitHub is a great tool in-all for making repositories. However, it does not do good with private repositories.
You're forced to pay for private repositories unless you get some sort of plan. I have a couple of projects so far, and if GitHub doesn't do what I want I just go to Bitbucket. It's a bit harder to work with than GitHub, however it's unlimited free repositories.
Might be a bit odd or bad practice but this is one way of going about it.
(arg1, arg2, arg3) = (1, 2, 3)
if (arg1 == 1)*(arg2 == 2)*(arg3 == 3):
print('Example.')
Anything multiplied by 0 == 0. If any of these conditions fail then it evaluates to false.
Sometimes, a textual representation might also help; with this query on the system catalog views, you can get a list of all FK relationships and how the link two tables (and what columns they operate on).
SELECT
fk.name 'FK Name',
tp.name 'Parent table',
cp.name, cp.column_id,
tr.name 'Refrenced table',
cr.name, cr.column_id
FROM
sys.foreign_keys fk
INNER JOIN
sys.tables tp ON fk.parent_object_id = tp.object_id
INNER JOIN
sys.tables tr ON fk.referenced_object_id = tr.object_id
INNER JOIN
sys.foreign_key_columns fkc ON fkc.constraint_object_id = fk.object_id
INNER JOIN
sys.columns cp ON fkc.parent_column_id = cp.column_id AND fkc.parent_object_id = cp.object_id
INNER JOIN
sys.columns cr ON fkc.referenced_column_id = cr.column_id AND fkc.referenced_object_id = cr.object_id
ORDER BY
tp.name, cp.column_id
Dump this into Excel, and you can slice and dice - based on the parent table, the referenced table or anything else.
I find visual guides helpful - but sometimes, textual documentation is just as good (or even better) - just my 2 cents.....
... or if you really want to use NOT IN
you can use
SELECT * FROM match WHERE id NOT IN ( SELECT id FROM email WHERE id IS NOT NULL)
List has Contains method that return bool. We can use that method in query.
List<int> listA = new List<int>();
List<int> listB = new List<int>();
listA.AddRange(new int[] { 1,2,3,4,5 });
listB.AddRange(new int[] { 3,5,6,7,8 });
var v = from x in listA
where !listB.Contains(x)
select x;
foreach (int i in v)
Console.WriteLine(i);
Basic subsetting:
album2 <- album2[, -5] #delete column 5
album2 <- album2[, -c(5:7)] # delete columns 5 through 7
Easy Solution:
Go to
Project property -> java builder path -> maven -> find c3p0-0.9.5.2.jar
and see the location where the file is stored in the local repository and go to this location and delete the repository manually.
Now you should be able to sort by this column either Oldest to Newest or Newest to Oldest
First you need to make sure if both of your files are in the same working directory. Next, you can import the whole file. For example,
import myClass
or you can import the entire class and entire functions from the file. For example,
from myClass import
Finally, you need to create an instance of the class from the original file and call the instance objects.
The Unix Date command will display in epoch time
the command is
date +"%s"
https://linux.die.net/man/1/date
Edit: Some people have observed you asked for days, so it's the result of that command divided by 86,400
So, the answers here are all a bit incomplete. The use of a '%20' to encode a space in URLs is explicitly defined in RFC3986, which defines how a URI is built. There is no mention in this specification of using a '+' for encoding spaces - if you go solely by this specification, a space must be encoded as '%20'.
The mention of using '+' for encoding spaces comes from the various incarnations of the HTML specification - specifically in the section describing content type 'application/x-www-form-urlencoded'. This is used for posting form data.
Now, the HTML 2.0 Specification (RFC1866) explicitly said, in section 8.2.2, that the Query part of a GET request's URL string should be encoded as 'application/x-www-form-urlencoded'. This, in theory, suggests that it's legal to use a '+' in the URL in the query string (after the '?').
But... does it really? Remember, HTML is itself a content specification, and URLs with query strings can be used with content other than HTML. Further, while the later versions of the HTML spec continue to define '+' as legal in 'application/x-www-form-urlencoded' content, they completely omit the part saying that GET request query strings are defined as that type. There is, in fact, no mention whatsoever about the query string encoding in anything after the HTML 2.0 spec.
Which leaves us with the question - is it valid? Certainly there's a LOT of legacy code which supports '+' in query strings, and a lot of code which generates it as well. So odds are good you won't break if you use '+'. (And, in fact, I did all the research on this recently because I discovered a major site which failed to accept '%20' in a GET query as a space. They actually failed to decode ANY percent encoded character. So the service you're using may be relevant as well.)
But from a pure reading of the specifications, without the language from the HTML 2.0 specification carried over into later versions, URLs are covered entirely by RFC3986, which means spaces ought to be converted to '%20'. And definitely that should be the case if you are requesting anything other than an HTML document.
For me xcode-select --reset
was the solution on Mojave.
You can define a new udf
when adding a column_name
:
u_f = F.udf(lambda :yourstring,StringType())
a.select(u_f().alias('column_name')
You can try this:
echo n | copy /-y <SOURCE> <DESTINATION>
-y
simply prompts before overwriting and we can pipe n to all those questions. So this would in essence just copy non-existing files. :)
You could use x ** (1. / 3)
to compute the (floating-point) cube root of x
.
The slight subtlety here is that this works differently for negative numbers in Python 2 and 3. The following code, however, handles that:
def is_perfect_cube(x):
x = abs(x)
return int(round(x ** (1. / 3))) ** 3 == x
print(is_perfect_cube(63))
print(is_perfect_cube(64))
print(is_perfect_cube(65))
print(is_perfect_cube(-63))
print(is_perfect_cube(-64))
print(is_perfect_cube(-65))
print(is_perfect_cube(2146689000)) # no other currently posted solution
# handles this correctly
This takes the cube root of x
, rounds it to the nearest integer, raises to the third power, and finally checks whether the result equals x
.
The reason to take the absolute value is to make the code work correctly for negative numbers across Python versions (Python 2 and 3 treat raising negative numbers to fractional powers differently).
from the SimpleDateFormat java doc:
* <td><code>"yyyyy.MMMMM.dd GGG hh:mm aaa"</code>
* <td><code>02001.July.04 AD 12:08 PM</code>
* <td><code>"EEE, d MMM yyyy HH:mm:ss Z"</code>
* <td><code>Wed, 4 Jul 2001 12:08:56 -0700</code>
where F13 is the cell you need to reference:
=CELL("Row",F13) yields 13; its row number
=CELL("Col",F13) yields 6; its column number;
=SUBSTITUTE(ADDRESS(1,COLUMN(F13)*1,4),"1","") yields F; its column letter
Other way to solve the problem of space reclaiming is, Create multiple partitions within table - Range based, Value based partitions and just drop/truncate the partition to reclaim the space, which will release the space used by whole data stored in the particular partition.
There will be some changes needed in table schema when you introduce the partitioning for your table like - Unique Keys, Indexes to include partition column etc.
You can add the 'muted' and 'autoplay' attributes together to enable autoplay for android devices.
e.g.
<video id="video" class="video" autoplay muted >
_x000D_
Yes. If the size does not match, the system will rescale it. But it's better to make 2 versions of the icons.
You could differentiate iPad and iPhone by the user agent on your server. If you don't want to write script on server, you could also change the icon with Javascript by
<link ref="apple-touch-icon" href="iPhone_version.png" />
...
if (... iPad test ...) {
$('link[rel="apple-touch-icon"]').href = 'iPad_version.png'; // assuming jQuery
}
This works because the icon is queried only when you add the web clip.
(There's no public way to differentiate iPhone =4 from iPhone =3GS in Javascript yet.)
inspired by Chris above
#! /bin/bash
installed() {
return $(dpkg-query -W -f '${Status}\n' "${1}" 2>&1|awk '/ok installed/{print 0;exit}{print 1}')
}
pkgs=(libgl1-mesa-dev xorg-dev vulkan-tools libvulkan-dev vulkan-validationlayers-dev spirv-tools)
missing_pkgs=""
for pkg in ${pkgs[@]}; do
if ! $(installed $pkg) ; then
missing_pkgs+=" $pkg"
fi
done
if [ ! -z "$missing_pkgs" ]; then
cmd="sudo apt install -y $missing_pkgs"
echo $cmd
fi
Also had this error when accidentally fed a database connection string to the readonly mirror - not the primary database in a HA setup.
Try to type in cmd: php artisan key:generate the problems will be solved
in scss
&::after{
content: url(images/RelativeProjectsArr.png);
margin-left:30px;
}
&:hover{
background-color:$turkiz;
color:#e5e7ef;
&::after{
content: url(images/RelativeProjectsArrHover.png);
}
}
I prefer this solution:
df = spark.table(selected_table).filter(condition)
counter = df.count()
df = df.select([(counter - count(c)).alias(c) for c in df.columns])
You would want and
instead of &&
.
In could able to resolve this issue with giving username and password in below url.
Please replace username and password with your Github credentials:
git remote set-url origin https://<username>:<password>@github.com/<username>/FirstRepository.git
Very possible the version of pip you're using isn't installing to the version of python you're using. I have a box where this is the case...
try:
which python
python --version
pip -V
If it looks like pip doesn't match your python, then you probably have something like the multiple versions of python and pip I found on my box...
[root@sdpipeline student]# locate bin/pip
/home/student/class/bin/pip
/home/student/class/bin/pip-2.7
/usr/bin/pip
/usr/bin/pip-python
As long as I use /home/student/class/bin/pip (2.7 that matches my python version on that box), then my imports work fine.
You can also try installing pip from source: http://www.pip-installer.org/en/latest/installing.html
There's probably a better way to do this, I'm still learning my way around too, but that's how I solved it -- hope it helps!
You can use the cmath module.
If the number is converted to a complex format, then it becomes easier to just call the polar method on the number.
import cmath
input_num = complex(1, 2) # stored as 1+2j
r, phi = cmath.polar(input_num)
In addition to Jim Hunziker's answer,
you can export the file from the revision as,
git show HEAD@{2013-02-25}:./fileInCurrentDirectory.txt > old_fileInCurrentDirectory.txt
Hope this helps :)
Tool: TFS Power Tools
Source: http://dennymichael.net/2013/03/19/tfs-scorch/
Command: tfpt scorch /recursive /deletes C:\LocationOfWorkspaceOrFolder
This will bring up a dialog box that will ask you to Delete or Download a list of files. Select or Unselect the files accordingly and press ok. Appearance in Grid (CheckBox, FileName, FileAction, FilePath)
Cause: TFS will only compare against items in the workspace. If alterations were made outside of the workspace TFS will be unaware of them.
Hopefully someone finds this useful. I found this post after deleting a handful of folders in varying locations. Not remembering which folders I deleted excluded the usual Force Get/Replace option I would have used.
This is what you need to set to fragment:
/* theme is optional, I am using leanback... */
setStyle(STYLE_NORMAL, R.style.AppTheme_Leanback);
In your case:
DialogFragment newFragment = new DetailsDialogFragment();
newFragment.setStyle(STYLE_NORMAL, R.style.AppTheme_Leanback);
newFragment.show(ft, "dialog");
And why? Because DialogFragment (when not told explicitly), will use its inner styles that will wrap your custom layout in it (no fullscreen, etc.).
And layout? No hacky way needed, this is working just fine:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
...
</RelativeLayout>
Enjoy
GPRESULT
is the right command, but it cannot be run without parameters. /v
or verbose option is difficult to manage without also outputting to a text file. E.G. I recommend using
gpresult /user myAccount /v > C:\dev\me.txt
--Ensure C:\Dev\me.txt exists
Another option is to display summary information only which may be entirely visible in the command window:
gpresult /user myAccount /r
The accounts are listed under the heading:
The user is a part of the following security groups
---------------------------------------------------
I've been trying to deploy a simple Angular 7 application, to an Azure Web App. Everything worked fine, until the point where you refreshed the page. Doing so, was presenting me with an 500 error - moved content. I've read both on the Angular docs and in around a good few forums, that I need to add a web.config file to my deployed solution and make sure the rewrite rule fallback to the index.html file. After hours of frustration and trial and error tests, I've found the error was quite simple: adding a tag around my file markup.
WebConfigurationManager.ConnectionStrings["YourConnectionString"].ProviderName;
This code have one problem:
int latitude = (int) (location.getLatitude());
int longitude = (int) (location.getLongitude());
You can change int
to double
double latitude = location.getLatitude();
double longitude = location.getLongitude();
edit: shortid has been deprecated. The maintainers recommend to use nanoid instead.
Another approach is using the shortid package from npm.
It is very easy to use:
var shortid = require('shortid');
console.log(shortid.generate()); // e.g. S1cudXAF
and has some compelling features:
ShortId creates amazingly short non-sequential url-friendly unique ids. Perfect for url shorteners, MongoDB and Redis ids, and any other id users might see.
- By default 7-14 url-friendly characters: A-Z, a-z, 0-9, _-
- Non-sequential so they are not predictable.
- Can generate any number of ids without duplicates, even millions per day.
- Apps can be restarted any number of times without any chance of repeating an id.
awk, sed, pipe, that's heavy
set `cat /etc/*release`; echo $1
Unless you have GNU awk 4.1.0 or later...
You won't have such an option as sed's -i
option so instead do:
$ awk '{print $0}' file > tmp && mv tmp file
Note: the -i
is not magic, it is also creating a temporary file sed
just handles it for you.
As of GNU awk 4.1.0...
GNU awk
added this functionality in version 4.1.0 (released 10/05/2013). It is not as straight forwards as just giving the -i
option as described in the released notes:
The new -i option (from xgawk) is used for loading awk library files. This differs from -f in that the first non-option argument is treated as a script.
You need to use the bundled inplace.awk
include file to invoke the extension properly like so:
$ cat file
123 abc
456 def
789 hij
$ gawk -i inplace '{print $1}' file
$ cat file
123
456
789
The variable INPLACE_SUFFIX
can be used to specify the extension for a backup file:
$ gawk -i inplace -v INPLACE_SUFFIX=.bak '{print $1}' file
$ cat file
123
456
789
$ cat file.bak
123 abc
456 def
789 hij
I am happy this feature has been added but to me, the implementation isn't very awkish as the power comes from the conciseness of the language and -i inplace
is 8 characters too long i.m.o.
Here is a link to the manual for the official word.
Below are a few extra steps on a fresh Mac that some people might need. This adds a little to @jnovack's excellent answer.
Update: A few other notes when setting this up:
Make sure your admin user has a password. A blank password won't work when trying to enable a root user.
System Preferences > Users and Groups > (select user) > Change password
Then to enable root, run dsenableroot
in a terminal:
$ dsenableroot
username = mac_admin_user
user password:
root password:
verify root password:
dsenableroot:: ***Successfully enabled root user.
Type in the admin user's password, then the new enabled root password twice.
Next type:
sudo gcc
or
sudo make
It will respond with something like the following:
WARNING: Improper use of the sudo command could lead to data loss
or the deletion of important system files. Please double-check your
typing when using sudo. Type "man sudo" for more information.
To proceed, enter your password, or type Ctrl-C to abort.
Password:
You have not agreed to the Xcode license agreements. You must agree to
both license agreements below in order to use Xcode.
Press enter when it prompts to show you the license agreement.
Hit the Enter key to view the license agreements at
'/Applications/Xcode.app/Contents/Resources/English.lproj/License.rtf'
IMPORTANT: BY USING THIS SOFTWARE, YOU ARE AGREEING TO BE BOUND BY THE
FOLLOWING APPLE TERMS:
//...
Press q
to exit the license agreement view.
By typing 'agree' you are agreeing to the terms of the software license
agreements. Type 'print' to print them or anything else to cancel,
[agree, print, cancel]
Type agree
. And then it will end with:
clang: error: no input files
Which basically means that you didn't give make
or gcc
any input files.
Here is what the check looked like:
$ xcode-select -p
/Applications/Xcode.app/Contents/Developer
With Mavericks, it is a little different now.
When the tools were NOT found, this is what the command pkgutil
command returned:
$ pkgutil --pkg-info=com.apple.pkg.CLTools_Executables
No receipt for 'com.apple.pkg.CLTools_Executables' found at '/'.
To install the command line tools, this works nicely from the Terminal, with a nice gui and everything.
$ xcode-select --install
http://macops.ca/installing-command-line-tools-automatically-on-mavericks/
When they were found, this is what the pkgutil
command returned:
$ pkgutil --pkg-info=com.apple.pkg.CLTools_Executables
package-id: com.apple.pkg.CLTools_Executables
version: 5.0.1.0.1.1382131676
volume: /
location: /
install-time: 1384149984
groups: com.apple.FindSystemFiles.pkg-group com.apple.DevToolsBoth.pkg-group com.apple.DevToolsNonRelocatableShared.pkg-group
This command returned the same before and after the install.
$ pkgutil --pkg-info=com.apple.pkg.DeveloperToolsCLI
No receipt for 'com.apple.pkg.DeveloperToolsCLI' found at '/'.
Also I had the component for the CLT selected and installed in xcode's downloads section before, but it seems like it didn't make it to the terminal...
Hope that helps.
Good to see lots of love for zip
in the answers here.
However it should be noted that if you are using a python version before 3.0, the itertools
module in the standard library contains an izip
function which returns an iterable, which is more appropriate in this case (especially if your list of latt/longs is quite long).
In python 3 and later zip
behaves like izip
.
Pure Virtual Functions are mostly used to define:
a) abstract classes
These are base classes where you have to derive from them and then implement the pure virtual functions.
b) interfaces
These are 'empty' classes where all functions are pure virtual and hence you have to derive and then implement all of the functions.
Pure virtual functions are actually functions which have no implementation in base class and have to be implemented in derived class.
Mozilla recently released the awesome L20n or localization 2.0. In their own words L20n is
an open source, localization-specific scripting language used to process gender, plurals, conjugations, and most of the other quirky elements of natural language.
Their js implementation is on the github L20n repository.
I don't think you can "legally" load only part of an XML file, since then it would be malformed (there would be a missing closing element somewhere).
Using LINQ-to-XML, you can do var doc = XDocument.Load("yourfilepath")
. From there its just a matter of querying the data you want, say like this:
var authors = doc.Root.Elements().Select( x => x.Element("Author") );
HTH.
EDIT:
Okay, just to make this a better sample, try this (with @JWL_'s suggested improvement):
using System;
using System.Xml.Linq;
namespace ConsoleApplication1 {
class Program {
static void Main( string[] args ) {
XDocument doc = XDocument.Load( "XMLFile1.xml" );
var authors = doc.Descendants( "Author" );
foreach ( var author in authors ) {
Console.WriteLine( author.Value );
}
Console.ReadLine();
}
}
}
You will need to adjust the path in XDocument.Load()
to point to your XML file, but the rest should work. Ask questions about which parts you don't understand.
As always, you should question whether you truly need a mutable map.
Immutable maps are trivial to build:
val map = Map(
"mykey" -> "myval",
"myotherkey" -> "otherval"
)
Mutable maps are no different when first being built:
val map = collection.mutable.Map(
"mykey" -> "myval",
"myotherkey" -> "otherval"
)
map += "nextkey" -> "nextval"
In both of these cases, inference will be used to determine the correct type parameters for the Map instance.
You can also hold an immutable map in a var
, the variable will then be updated with a new immutable map instance every time you perform an "update"
var map = Map(
"mykey" -> "myval",
"myotherkey" -> "otherval"
)
map += "nextkey" -> "nextval"
If you don't have any initial values, you can use Map.empty:
val map : Map[String, String] = Map.empty //immutable
val map = Map.empty[String,String] //immutable
val map = collection.mutable.Map.empty[String,String] //mutable
I didn't have a solution, just a workaround.
Windows Vista onwards has an inbuilt command called clip
that takes the output of a command from command line and puts it into the clipboard. For example, ipconfig | clip
.
So I made a function with the os
module which takes a string and adds it to the clipboard using the inbuilt Windows solution.
import os
def addToClipBoard(text):
command = 'echo ' + text.strip() + '| clip'
os.system(command)
# Example
addToClipBoard('penny lane')
# Penny Lane is now in your ears, eyes, and clipboard.
As previously noted in the comments however, one downside to this approach is that the echo
command automatically adds a newline to the end of your text. To avoid this you can use a modified version of the command:
def addToClipBoard(text):
command = 'echo | set /p nul=' + text.strip() + '| clip'
os.system(command)
If you are using Windows XP it will work just following the steps in Copy and paste from Windows XP Pro's command prompt straight to the Clipboard.
How about this,
$("body").bind("ajaxSend", function(elm, xhr, s){
if (s.type == "POST") {
xhr.setRequestHeader('X-CSRF-Token', getCSRFTokenValue());
}
});
Ref: http://erlend.oftedal.no/blog/?blogid=118
To pass CSRF
as parameter,
$.ajax({
type: "POST",
url: "file",
data: { CSRF: getCSRFTokenValue()}
})
.done(function( msg ) {
alert( "Data: " + msg );
});
No need to do so much works..
var query = from c in obj.tbCourses
where ...
select c;
Then you can use:
List<course> list_course= query.ToList<course>();
It works fine for me.
Have you taken a look at put.py? I've used it in the past. You can also just hack up your own request with urllib.
You can use like this:
public static String executeHttpPost1(String url,
HashMap<String, String> postParameters) throws UnsupportedEncodingException {
// TODO Auto-generated method stub
HttpClient client = getNewHttpClient();
try{
request = new HttpPost(url);
}
catch(Exception e){
e.printStackTrace();
}
if(postParameters!=null && postParameters.isEmpty()==false){
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(postParameters.size());
String k, v;
Iterator<String> itKeys = postParameters.keySet().iterator();
while (itKeys.hasNext())
{
k = itKeys.next();
v = postParameters.get(k);
nameValuePairs.add(new BasicNameValuePair(k, v));
}
UrlEncodedFormEntity urlEntity = new UrlEncodedFormEntity(nameValuePairs);
request.setEntity(urlEntity);
}
try {
Response = client.execute(request,localContext);
HttpEntity entity = Response.getEntity();
int statusCode = Response.getStatusLine().getStatusCode();
Log.i(TAG, ""+statusCode);
Log.i(TAG, "------------------------------------------------");
try{
InputStream in = (InputStream) entity.getContent();
//Header contentEncoding = Response.getFirstHeader("Content-Encoding");
/*if (contentEncoding != null && contentEncoding.getValue().equalsIgnoreCase("gzip")) {
in = new GZIPInputStream(in);
}*/
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuilder str = new StringBuilder();
String line = null;
while((line = reader.readLine()) != null){
str.append(line + "\n");
}
in.close();
response = str.toString();
Log.i(TAG, "response"+response);
}
catch(IllegalStateException exc){
exc.printStackTrace();
}
} catch(Exception e){
Log.e("log_tag", "Error in http connection "+response);
}
finally {
}
return response;
}
You can use either one of these to check null, whitespace and empty strings.
WHERE COLUMN <> ''
WHERE LEN(COLUMN) > 0
WHERE NULLIF(LTRIM(RTRIM(COLUMN)), '') IS NOT NULL
This could be done running a simple find
command:
find * -maxdepth 0 -exec mv {} PRE_{} \;
The above command will prefix all files and folders in the current directory with PRE_
.
What you actually created with:
MyType[] list = []
Was fixed size array (not list) with size of 0. You can create fixed size array of size for example 4 with:
MyType[] array = new MyType[4]
But there's no add method of course.
If you create list with def
it's something like creating this instance with Object
(You can read more about def
here). And []
creates empty ArrayList
in this case.
So using def list = []
you can then append new items with add()
method of ArrayList
list.add(new MyType())
Or more groovy way with overloaded left shift operator:
list << new MyType()
Different case but may help someone,
In my case Window firewall was enabled on Server,
Two thinks can be done,
1) Disable windows firewall (your on risk but it will get thing work)
2) Add port in inbound rule.
Thanks .
It might be better to use communicate
:
from subprocess import Popen, PIPE, STDOUT
p = Popen(['myapp'], stdout=PIPE, stdin=PIPE, stderr=PIPE)
stdout_data = p.communicate(input='data_to_write')[0]
"Better", because of this warning:
Use communicate() rather than .stdin.write, .stdout.read or .stderr.read to avoid deadlocks due to any of the other OS pipe buffers filling up and blocking the child process.
This was the first question/answer that popped up for me when trying to solve the same problem using ASP.NET MVC as the source of my data. I realize this doesn't solve the PHP question, but it is related enough to be valuable.
I am using ASP.NET MVC. The blog post from Greg Brant worked for me. Ultimately, you create an attribute, [HttpHeaderAttribute("Access-Control-Allow-Origin", "*")]
, that you are able to add to controller actions.
For example:
public class HttpHeaderAttribute : ActionFilterAttribute
{
public string Name { get; set; }
public string Value { get; set; }
public HttpHeaderAttribute(string name, string value)
{
Name = name;
Value = value;
}
public override void OnResultExecuted(ResultExecutedContext filterContext)
{
filterContext.HttpContext.Response.AppendHeader(Name, Value);
base.OnResultExecuted(filterContext);
}
}
And then using it with:
[HttpHeaderAttribute("Access-Control-Allow-Origin", "*")]
public ActionResult MyVeryAvailableAction(string id)
{
return Json( "Some public result" );
}
Place your text file in the /assets
directory under the Android project. Use AssetManager
class to access it.
AssetManager am = context.getAssets();
InputStream is = am.open("test.txt");
Or you can also put the file in the /res/raw
directory, where the file will be indexed and is accessible by an id in the R file:
InputStream is = context.getResources().openRawResource(R.raw.test);
Personally, one of the things I love about python is the tuple-dict combination. What you have here is effectively a 2d array (where x = fruit name and y = color), and I am generally a supporter of the dict of tuples for implementing 2d arrays, at least when something like numpy
or a database isn't more appropriate. So in short, I think you've got a good approach.
Note that you can't use dicts as keys in a dict without doing some extra work, so that's not a very good solution.
That said, you should also consider namedtuple(). That way you could do this:
>>> from collections import namedtuple
>>> Fruit = namedtuple("Fruit", ["name", "color"])
>>> f = Fruit(name="banana", color="red")
>>> print f
Fruit(name='banana', color='red')
>>> f.name
'banana'
>>> f.color
'red'
Now you can use your fruitcount dict:
>>> fruitcount = {Fruit("banana", "red"):5}
>>> fruitcount[f]
5
Other tricks:
>>> fruits = fruitcount.keys()
>>> fruits.sort()
>>> print fruits
[Fruit(name='apple', color='green'),
Fruit(name='apple', color='red'),
Fruit(name='banana', color='blue'),
Fruit(name='strawberry', color='blue')]
>>> fruits.sort(key=lambda x:x.color)
>>> print fruits
[Fruit(name='banana', color='blue'),
Fruit(name='strawberry', color='blue'),
Fruit(name='apple', color='green'),
Fruit(name='apple', color='red')]
Echoing chmullig, to get a list of all colors of one fruit, you would have to filter the keys, i.e.
bananas = [fruit for fruit in fruits if fruit.name=='banana']
I find that some of these answers are vague and complicated, I find the best way to figure out these things for sure is to just open up the console and test it yourself.
var x;
x == null // true
x == undefined // true
x === null // false
x === undefined // true
var y = null;
y == null // true
y == undefined // true
y === null // true
y === undefined // false
typeof x // 'undefined'
typeof y // 'object'
var z = {abc: null};
z.abc == null // true
z.abc == undefined // true
z.abc === null // true
z.abc === undefined // false
z.xyz == null // true
z.xyz == undefined // true
z.xyz === null // false
z.xyz === undefined // true
null = 1; // throws error: invalid left hand assignment
undefined = 1; // works fine: this can cause some problems
So this is definitely one of the more subtle nuances of JavaScript. As you can see, you can override the value of undefined
, making it somewhat unreliable compared to null
. Using the ==
operator, you can reliably use null
and undefined
interchangeably as far as I can tell. However, because of the advantage that null
cannot be redefined, I might would use it when using ==
.
For example, variable != null
will ALWAYS return false if variable
is equal to either null
or undefined
, whereas variable != undefined
will return false if variable
is equal to either null
or undefined
UNLESS undefined
is reassigned beforehand.
You can reliably use the ===
operator to differentiate between undefined
and null
, if you need to make sure that a value is actually undefined
(rather than null
).
Null
and Undefined
are two of the six built in types.4.3.9 undefined value
primitive value used when a variable has not been assigned a value
4.3.11 null value
primitive value that represents the intentional absence of any object value
I use Eclipse and this broke during an update. Here's what worked for me as the answers above did not.
I checked where ant's build.xml expected to find zipalign.exe.
In: C:\Development\Android\android-sdk\tools\ant\build.xml
zipalign is defined as:
<property name="zipalign" location="${android.build.tools.dir}/zipalign${exe}" />
which indicates its expected in:
C:\Development\Android\android-sdk\build-tools\18.0.1
This directory corresponds to the highest version of the 'Android SDK Build-tools' displayed as installed in the 'Android SDK Manager'. So, that's where I copied zipalign.exe (which I obtained from an Android Studio installation!) and signed apps are now automatically zipaligned again!
Did you install Git correctly?
According to the Bower site, you need to make sure you check the option "Run Git from Windows Command Prompt".
I had this issue where Git was not found when I was trying to install Angular. I re-ran the installer for git and changed my setting and then it worked.
From the bower site: http://bower.io/
Spring Boot provided several application listener while try to create application context one of them is ApplicationFailedEvent. We can use to know weather the application context initialized or not.
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.context.event.ApplicationFailedEvent;
import org.springframework.context.ApplicationListener;
public class ApplicationErrorListener implements
ApplicationListener<ApplicationFailedEvent> {
private static final Logger LOGGER =
LoggerFactory.getLogger(ApplicationErrorListener.class);
@Override
public void onApplicationEvent(ApplicationFailedEvent event) {
if (event.getException() != null) {
LOGGER.info("!!!!!!Looks like something not working as
expected so stoping application.!!!!!!");
event.getApplicationContext().close();
System.exit(-1);
}
}
}
Add to above listener class to SpringApplication.
new SpringApplicationBuilder(Application.class)
.listeners(new ApplicationErrorListener())
.run(args);
You can achieve your results with two methods:-
First Method define position values:-
HTML
<ul>
<li>Hello</li>
<li>Hello world</li>
</ul>
CSS
ul{
width:100px;
}
ul li{
border:1px solid orange;
background: url("http://www.adaweb.net/Portals/0/Images/arrow1.gif") no-repeat 90% 5px;
}
ul li:hover{
background: yellow url("http://www.adaweb.net/Portals/0/Images/arrow1.gif") no-repeat 90% 5px;
}
First Demo:- http://jsfiddle.net/QeGAd/18/
Second Method by CSS :before:after Selectors
HTML
<ul>
<li>Hello</li>
<li>Hello world</li>
CSS
ul{
width:100px;
}
ul li{
border:1px solid orange;
}
ul li:after {
content: " ";
padding-right: 16px;
background: url("http://www.adaweb.net/Portals/0/Images/arrow1.gif") no-repeat center right;
}
ul li:hover {
background:yellow;
}
ul li:hover:after {
content: " ";
padding-right: 16px;
background: url("http://www.adaweb.net/Portals/0/Images/arrow1.gif") no-repeat center right;
}
Second Demo:- http://jsfiddle.net/QeGAd/17/
It seems that your date column is not of type datetime but varchar. You have to convert it to datetime when sorting:
select date
from tbemp
order by convert(datetime, date, 103) ASC
style 103 = dd/MM/yyyy (
msdn
)
Here is an alternative solution that I found on the matplotlib mailing list:
import matplotlib.pylab as plt
x = range(1000)
ax = plt.axes()
ax.semilogx(x, x)
ax.xaxis.set_ticks_position('none')
In this scenario, the outer <div>
has a width and height of 90%. The inner div>
has a width of 100% of its parent. Both scale when re-sizing the window.
HTML
<div>
<div>Hello there</div>
</div>
CSS
html, body {
width: 100%;
height: 100%;
}
body > div {
width: 90%;
height: 100%;
background: green;
}
body > div > div {
width: 100%;
background: red;
}
Demo
TEXT is a data-type for text based input. On the other hand, you have BLOB and CLOB which are more suitable for data storage (images, etc) due to their larger capacity limits (4GB for example).
As for the difference between BLOB and CLOB, I believe CLOB has character encoding associated with it, which implies it can be suited well for very large amounts of text.
BLOB and CLOB data can take a long time to retrieve, relative to how quick data from a TEXT field can be retrieved. So, use only what you need.
Try
CREATE TABLE foo LIKE bar;
so the keys and indexes are copied over as, well.
from django.db import models
from django.core.validators import MinValueValidator, MaxValueValidator
size = models.IntegerField(validators=[MinValueValidator(0),
MaxValueValidator(5)])
You can write a try - catch block around the line you want to have ignored.
Like in the example code of yours. If you just continue your code below the closing bracket of the catch block everythings fine.
I suggest this ugly method but it works:
length = 1
lenghtafterpadding = 3
newlength = '0' * (lenghtafterpadding - len(str(length))) + str(length)
I came here to find a lighter solution than this one!
This error message may also happen when the data contains NA
s.
In this case, the behaviour depends on the defaults (see documentation), and maybe all cases with NA
's in the columns mentioned in the variables are silently dropped. So it may be that a factor does indeed have several outcomes, but the factor only has one outcome when restricting to the cases without NA
's.
In this case, to fix the error, either change the model (remove the problematic factor from the formula), or change the data (i.e. complete the cases).
A few of the options are deprecated as of today. So watch out for those.
If you try <input onkeypress="blockSpecialCharacters(event)" />
, an IDE like WebStorm
will slash out event and tell you:
Deprecated symbol used, consults docs for better alternative
Then when you get to the JavaScript, console.log(e.keyCode)
will also give keyCode and say:
Deprecated symbol used, consults docs for better alternative
Anyways I did it using jQuery.
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.js"></script>
<input id="theInput" />
<script>
function blockSpecialCharacters(e) {
let key = e.key;
let keyCharCode = key.charCodeAt(0);
// 0-9
if(keyCharCode >= 48 && keyCharCode <= 57) {
return key;
}
// A-Z
if(keyCharCode >= 65 && keyCharCode <= 90) {
return key;
}
// a-z
if(keyCharCode >= 97 && keyCharCode <= 122) {
return key;
}
return false;
}
$('#theInput').keypress(function(e) {
blockSpecialCharacters(e);
});
</script>
It's not that hard...
Check out this forum post:
http://www.pcreview.co.uk/forums/excel-not-recognizing-dates-dates-t3139469.html
The steps in short:
EnvInject Plugin aka (Environment Injector Plugin) gives you several options to set environment variables from Jenkins configuration.
By selecting Inject environment variables to the build process
you will get:
Properties File Path
Properties Content
Script File Path
Script Content
and finally Evaluated Groovy script
.
Evaluated Groovy script
gives you possibility to set environment variable based on result of executed command:
execute
method: return [HOSTNAME_SHELL: 'hostname'.execute().text,
DATE_SHELL: 'date'.execute().text,
ECHO_SHELL: 'echo hello world!'.execute().text
]
Groovy
code: return [HOSTNAME_GROOVY: java.net.InetAddress.getLocalHost().getHostName(),
DATE_GROOVY: new Date()
]
(More details about each method could be found in build-in help (?))
Unfortunately you can't do the same from Script Content
as it states:
Execute a script file aimed at setting an environment such as creating folders, copying files, and so on. Give the script file content. You can use the above properties variables. However, adding or overriding environment variables in the script doesn't have any impacts in the build job.
The document.location
is an object that contains properties for the current location.
The href
property is one of these properties, containing the complete URL, i.e. all the other properties put together.
Some browsers allow you to assign an URL to the location
object and acts as if you assigned it to the href
property. Some other browsers are more picky, and requires you to use the href
property. Thus, to make the code work in all browsers, you have to use the href
property.
Both the window
and document
objects has a location
object. You can set the URL using either window.location.href
or document.location.href
. However, logically the document.location
object should be read-only (as you can't change the URL of a document; changing the URL loads a new document), so to be on the safe side you should rather use window.location.href
when you want to set the URL.
I my case, I was using syncthing. It created a duplicate that I was not aware of and my compilation was failing.
A map()
creates an array, so a return
is expected for all code paths (if/elses).
If you don't want an array or to return data, use forEach
instead.
If you wanted to you could use this method, which is a bit hacky, but would offer the desired functionality:
jQuery('<a/>', {
id: 'foo',
href: 'http://google.com',
title: 'Become a Googler',
rel: 'external',
text: 'Go to Google!',
target:'_blank',
style:'display:none;'
}).appendTo('#mySelector');
$('#foo').click()
The answers are partially correct because @@ is actually a class variable which is per class hierarchy meaning it is shared by a class, its instances and its descendant classes and their instances.
class Person
@@people = []
def initialize
@@people << self
end
def self.people
@@people
end
end
class Student < Person
end
class Graduate < Student
end
Person.new
Student.new
puts Graduate.people
This will output
#<Person:0x007fa70fa24870>
#<Student:0x007fa70fa24848>
So there is only one same @@variable for Person, Student and Graduate classes and all class and instance methods of these classes refer to the same variable.
There is another way of defining a class variable which is defined on a class object (Remember that each class is actually an instance of something which is actually the Class class but it is another story). You use @ notation instead of @@ but you can't access these variables from instance methods. You need to have class method wrappers.
class Person
def initialize
self.class.add_person self
end
def self.people
@people
end
def self.add_person instance
@people ||= []
@people << instance
end
end
class Student < Person
end
class Graduate < Student
end
Person.new
Person.new
Student.new
Student.new
Graduate.new
Graduate.new
puts Student.people.join(",")
puts Person.people.join(",")
puts Graduate.people.join(",")
Here, @people is single per class instead of class hierarchy because it is actually a variable stored on each class instance. This is the output:
#<Student:0x007f8e9d2267e8>,#<Student:0x007f8e9d21ff38>
#<Person:0x007f8e9d226158>,#<Person:0x007f8e9d226608>
#<Graduate:0x007f8e9d21fec0>,#<Graduate:0x007f8e9d21fdf8>
One important difference is that, you cannot access these class variables (or class instance variables you can say) directly from instance methods because @people in an instance method would refer to an instance variable of that specific instance of the Person or Student or Graduate classes.
So while other answers correctly state that @myvariable (with single @ notation) is always an instance variable, it doesn't necessarily mean that it is not a single shared variable for all instances of that class.
To allow for compound commands to be echoed, I use eval
plus Soth's exe
function to echo and run the command. This is useful for piped commands that would otherwise only show none or just the initial part of the piped command.
Without eval:
exe() { echo "\$ $@" ; "$@" ; }
exe ls -F | grep *.txt
Outputs:
$
file.txt
With eval:
exe() { echo "\$ $@" ; "$@" ; }
exe eval 'ls -F | grep *.txt'
Which outputs
$ exe eval 'ls -F | grep *.txt'
file.txt
Alternatively, if you have Node.js installed, you can use the following command:
npx degit GIT_REPO
npx
comes with Node, and it allows you to run binary node-based packages without installing them first (alternatively, you can first install degit
globally using npm i -g degit
).
Degit is a tool created by Rich Harris, the creator of Svelte and Rollup, which he uses to quickly create a new project by cloning a repository without keeping the git folder. But it can also be used to clone any repo once...
Did you mean len(list1)-1
?
If you're searching for other method, you can try list1.index(list1[-1])
, but I don't recommend this one. You will have to be sure, that the list contains NO duplicates.
Get the invalid chars from System.IO.Path.GetInvalidPathChars();
and check if your string (Directory path) contains those or not.
+ theme(plot.title = element_text(size=22))
Here is the full set of things you can change in element_text
:
element_text(family = NULL, face = NULL, colour = NULL, size = NULL,
hjust = NULL, vjust = NULL, angle = NULL, lineheight = NULL,
color = NULL)
It's 2020 now, for the latest solution, you can use Burp Suite to sniffing https traffic without rooting your Android device.
Steps:
Install Burp Suite
Enable Proxy
Import the certification in your Android phone
Change you Wifi configuration to listening to proxy
Profit!
I wrote the full tutorial and screenshot on how to do it at here: https://www.yodiw.com/monitor-android-network-traffic-with-burp/
It looks like Google recently broke something with their revoke stuff (it's started returning 400 errors for us). You now have to call
auth2.disconnect();
In our case we then have to wait a couple of seconds for the disconnect call to complete otherwise the sign-in code will re-authorise before it's done. It'd be good if google returned a promise from the disconnect method.
I've been able to solve this by using a hack involving import *
. It even works for both named and default exports!
For a named export:
// dependency.js
export const doSomething = (y) => console.log(y)
// myModule.js
import { doSomething } from './dependency';
export default (x) => {
doSomething(x * 2);
}
// myModule-test.js
import myModule from '../myModule';
import * as dependency from '../dependency';
describe('myModule', () => {
it('calls the dependency with double the input', () => {
dependency.doSomething = jest.fn(); // Mutate the named export
myModule(2);
expect(dependency.doSomething).toBeCalledWith(4);
});
});
Or for a default export:
// dependency.js
export default (y) => console.log(y)
// myModule.js
import dependency from './dependency'; // Note lack of curlies
export default (x) => {
dependency(x * 2);
}
// myModule-test.js
import myModule from '../myModule';
import * as dependency from '../dependency';
describe('myModule', () => {
it('calls the dependency with double the input', () => {
dependency.default = jest.fn(); // Mutate the default export
myModule(2);
expect(dependency.default).toBeCalledWith(4); // Assert against the default
});
});
As Mihai Damian quite rightly pointed out below, this is mutating the module object of dependency
, and so it will 'leak' across to other tests. So if you use this approach you should store the original value and then set it back again after each test.
To do this easily with Jest, use the spyOn() method instead of jest.fn()
, because it supports easily restoring its original value, therefore avoiding before mentioned 'leaking'.
There is no way to clear the screen but, a really easy way to fake it can be printing as much Serial.println();
as you need to keep all the old data out of the screen.
ng set --global defaults.styleExt=scss
is deprecated since ng6. You will get this message:
get/set have been deprecated in favor of the config command
You should use:
ng config schematics.@schematics/angular:component '{ styleext: "scss"}'
If you want to target a specific project (replace {project} with your project's name):
ng config projects.{project}.schematics.@schematics/angular:component '{ styleext: "scss"}'
Start by figuring out what your current working directory is for your running script.
Add this line at the beginning:
puts Dir.pwd
.
This will tell you in which current working directory ruby is running your script. You will most likely see it's not where you assume it is. Then make sure you're specifying pathnames properly for windows. See the docs here how to properly format pathnames for windows:
http://www.ruby-doc.org/core/classes/IO.html
Then either use Dir.chdir
to change the working directory to the place where text.txt is, or specify the absolute pathname to the file according to the instructions in the IO docs above. That SHOULD do it...
EDIT
Adding a 3rd solution which might be the most convenient one, if you're putting the text files among your script files:
Dir.chdir(File.dirname(__FILE__))
This will automatically change the current working directory to the same directory as the .rb
file that is running the script.
random.shuffle
should work. Here's an example, where the objects are lists:
from random import shuffle
x = [[i] for i in range(10)]
shuffle(x)
# print(x) gives [[9], [2], [7], [0], [4], [5], [3], [1], [8], [6]]
# of course your results will vary
Note that shuffle works in place, and returns None.
var message =/*[[${message}]]*/ 'defaultanyvalue';
Just put the pixel padding into the image - add 10px or whatever to the canvas size of the image in photohop and align it right in CSS.
Try withColumn
with the function when
as follows:
val sqlContext = new SQLContext(sc)
import sqlContext.implicits._ // for `toDF` and $""
import org.apache.spark.sql.functions._ // for `when`
val df = sc.parallelize(Seq((4, "blah", 2), (2, "", 3), (56, "foo", 3), (100, null, 5)))
.toDF("A", "B", "C")
val newDf = df.withColumn("D", when($"B".isNull or $"B" === "", 0).otherwise(1))
newDf.show()
shows
+---+----+---+---+
| A| B| C| D|
+---+----+---+---+
| 4|blah| 2| 1|
| 2| | 3| 0|
| 56| foo| 3| 1|
|100|null| 5| 0|
+---+----+---+---+
I added the (100, null, 5)
row for testing the isNull
case.
I tried this code with Spark 1.6.0
but as commented in the code of when
, it works on the versions after 1.4.0
.
Instead of detecting a browser, you should rather detect a feature (whether it's supported or not). This is what Modernizr does.
Of course there are cases where you still need to check the browser because you need to work around an issue and not to detect a feature. Specific WebKit
check which does not use jQuery $.browser
:
var isWebKit = !!window.webkitURL;
As some of the comments suggested the above approach doesn't work for older Safari versions. Updating with another approach suggested in comments and by another answer:
var isWebKit = 'WebkitAppearance' in document.documentElement.style;
I think this will meet your requirements:
For those wondering if jQuery id selectors are slower than document.getElementById, the answer is yes, but not because of the preconception that it searches through the entire DOM looking for an element. jQuery does actually use the native method. It's actually because jQuery uses a regular expression first to separate out strings in the selector to check by, and of course running the constructor:
rquickExpr = /^(?:(<[\w\W]+>)[^>]*|#([\w-]*))$/
Whereas using a DOM element as an argument returns immediately with 'this'.
So this:
$(document.getElementById('blah')).doSomething();
Will always be faster than this:
$('#blah').doSomething();
The issue was in fact that one of the properties was a relation to another table. I changed my LINQ query so that it could get the same data from a different method without needing to load the entire table.
Thank you all for your help!
Your model is @Messages
, change it to @message
.
To change it like you should use migration:
def change rename_table :old_table_name, :new_table_name end
Of course do not create that file by hand but use rails generator:
rails g migration ChangeMessagesToMessage
That will generate new file with proper timestamp in name in 'db
dir. Then run:
rake db:migrate
And your app should be fine since then.
The checking of the presence of the member before assigning it is, in my opinion, quite ugly.
Kohana has a useful function to make selecting parameters simple.
You can make your own like so...
function arrayGet($array, $key, $default = NULL)
{
return isset($array[$key]) ? $array[$key] : $default;
}
And then do something like...
$page = arrayGet($_GET, 'p', 1);
I found this to be the biggest help:
Use HAProxy 1.5 or newer, and simply add the following line to the frontend config:
redirect scheme https code 301 if !{ ssl_fc }
$("#yourbuttonid").click(function(){ document.location = "<%= Url.Action("Youraction") %>";})
I solve My problem:
package R does not exist
.
Goto AndroidManifest.xml
file and changed the minSDKVersion="17"
from 19
I faced the very same error when I was trying to connect to my SQL Server 2014 instance using sa
user using SQL Server Management Studio (SSMS). I was facing this error even when security settings for sa
user was all good and SQL authentication mode was enabled on the SQL Server instance.
Finally, the issue turned out to be that Named Pipes
protocol was disabled. Here is how you can enable it:
Open SQL Server Configuration Manager application from start menu. Now, enable Named Pipes
protocol for both Client Protocols
and Protocols for <SQL Server Instance Name>
nodes as shown in the snapshot below:
Note: Make sure you restart the SQL Server instance after making changes.
P.S. I'm not very sure but there is a possibility that the Named Pipes
enabling was required under only one of the two nodes that I've advised. So you can try it one after the other to reach to a more precise solution.
There is also who is active?:
Who is Active? is a comprehensive server activity stored procedure based on the SQL Server 2005 and 2008 dynamic management views (DMVs). Think of it as sp_who2 on a hefty dose of anabolic steroids
At my last job we ran statistics once a week. If I remember correctly, we scheduled them on a Thursday night, and on Friday the DBAs were very careful to monitor the longest running queries for anything unexpected. (Friday was picked because it was often just after a code release, and tended to be a fairly low traffic day.) When they saw a bad query they would find a better query plan and save that one so it wouldn't change again unexpectedly. (Oracle has tools to do this for you automatically, you tell it the query to optimize and it does.)
Many organizations avoid running statistics out of fear of bad query plans popping up unexpectedly. But this usually means that their query plans get worse and worse over time. And when they do run statistics then they encounter a number of problems. The resulting scramble to fix those issues confirms their fears about the dangers of running statistics. But if they ran statistics regularly, used the monitoring tools as they are supposed to, and fixed issues as they came up then they would have fewer headaches, and they wouldn't encounter them all at once.
According to spark documentation "where()
is an alias for filter()
"
filter(condition)
Filters rows using the given condition.
where()
is an alias for filter()
.
Parameters: condition – a Column
of types.BooleanType
or a string of SQL expression.
>>> df.filter(df.age > 3).collect()
[Row(age=5, name=u'Bob')]
>>> df.where(df.age == 2).collect()
[Row(age=2, name=u'Alice')]
>>> df.filter("age > 3").collect()
[Row(age=5, name=u'Bob')]
>>> df.where("age = 2").collect()
[Row(age=2, name=u'Alice')]
You are creating those bytes
objects yourself:
item['title'] = [t.encode('utf-8') for t in title]
item['link'] = [l.encode('utf-8') for l in link]
item['desc'] = [d.encode('utf-8') for d in desc]
items.append(item)
Each of those t.encode()
, l.encode()
and d.encode()
calls creates a bytes
string. Do not do this, leave it to the JSON format to serialise these.
Next, you are making several other errors; you are encoding too much where there is no need to. Leave it to the json
module and the standard file object returned by the open()
call to handle encoding.
You also don't need to convert your items
list to a dictionary; it'll already be an object that can be JSON encoded directly:
class W3SchoolPipeline(object):
def __init__(self):
self.file = open('w3school_data_utf8.json', 'w', encoding='utf-8')
def process_item(self, item, spider):
line = json.dumps(item) + '\n'
self.file.write(line)
return item
I'm guessing you followed a tutorial that assumed Python 2, you are using Python 3 instead. I strongly suggest you find a different tutorial; not only is it written for an outdated version of Python, if it is advocating line.decode('unicode_escape')
it is teaching some extremely bad habits that'll lead to hard-to-track bugs. I can recommend you look at Think Python, 2nd edition for a good, free, book on learning Python 3.
Now I think there is better scoping of variables to a block of statements using let
:
function printnums()
{
// i is not accessible here
for(let i = 0; i <10; i+=)
{
console.log(i);
}
// i is not accessible here
// j is accessible here
for(var j = 0; j <10; j++)
{
console.log(j);
}
// j is accessible here
}
I think people will start using let here after so that they will have similar scoping in JavaScript like other languages, Java, C#, etc.
People with not a clear understanding about scoping in JavaScript used to make the mistake earlier.
Hoisting is not supported using let
.
With this approach errors present in JavaScript are getting removed.
Refer to ES6 In Depth: let and const to understand it better.
if (UIDevice.current.identifierForVendor?.uuidString) != nil
{
self.lblDeviceIdValue.text = UIDevice.current.identifierForVendor?.uuidString
}
If you are using tortoise git.
please follow the below steps.
Now your changes moved from BranchA to BranchB
Try
SELECT @@VERSION
or for SQL Server 2000 and above the following is easier to parse :)
SELECT SERVERPROPERTY('productversion')
, SERVERPROPERTY('productlevel')
, SERVERPROPERTY('edition')
string time = "19851231";
DateTime theTime= DateTime.ParseExact(time,
"yyyyMMdd",
CultureInfo.InvariantCulture,
DateTimeStyles.None);
The snippet you're showing doesn't seem to be directly responsible for the error.
This is how you can CAUSE the error:
namespace MyNameSpace
{
int i; <-- THIS NEEDS TO BE INSIDE THE CLASS
class MyClass
{
...
}
}
If you don't immediately see what is "outside" the class, this may be due to misplaced or extra closing bracket(s) }
.
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 )
add the file info.php to the following directory - your default http/apache directory - normally /var/www/html
with the following contents
<?php
phpinfo();
?>
Then httpd/apache restart the go to your default html directory http://enter.server.here/info.php
would deliver the whole php pedigree!
if You have The JAVA_HOME environment variable is not defined correctly This environment variable is needed to run this program NB: JAVA_HOME should point to a JDK not a JRE Error so do one thing ...type C:>dir/x and you will see the PROGRA~1 or May ~2 and After int Environment Variable Chang The JAVA_HOME Dir Like This JAVA_HOME:- C:\PROGRA~1\Java\jdk1.8.0_144\ also Set In Path :-%JAVA_HOME%\bin; And it Works
Now we've got CSS grid. Welcome to 2019.
/* Required */_x000D_
body {_x000D_
margin: 0;_x000D_
height: 100%;_x000D_
}_x000D_
_x000D_
#wrapper {_x000D_
height: 100vh;_x000D_
display: grid;_x000D_
grid-template-rows: 30px 1fr 30px;_x000D_
}_x000D_
_x000D_
#content {_x000D_
overflow-y: scroll;_x000D_
}_x000D_
_x000D_
/* Optional */_x000D_
#wrapper > * {_x000D_
padding: 5px;_x000D_
}_x000D_
_x000D_
#header {_x000D_
background-color: #ff0000ff;_x000D_
}_x000D_
_x000D_
#content {_x000D_
background-color: #00ff00ff;_x000D_
}_x000D_
_x000D_
#footer {_x000D_
background-color: #0000ffff;_x000D_
}
_x000D_
<body>_x000D_
<div id="wrapper">_x000D_
<div id="header">Header Content</div>_x000D_
<div id="content">_x000D_
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum._x000D_
</div>_x000D_
<div id="footer">Footer Content</div>_x000D_
</div>_x000D_
</body>
_x000D_
I needed to execute an directive AFTER loading several templates so I created this directive:
utilModule.directive('utPreload',_x000D_
['$templateRequest', '$templateCache', '$q', '$compile', '$rootScope',_x000D_
function($templateRequest, $templateCache, $q, $compile, $rootScope) {_x000D_
'use strict';_x000D_
var link = function(scope, element) {_x000D_
scope.$watch('done', function(done) {_x000D_
if(done === true) {_x000D_
var html = "";_x000D_
if(scope.slvAppend === true) {_x000D_
scope.urls.forEach(function(url) {_x000D_
html += $templateCache.get(url);_x000D_
});_x000D_
}_x000D_
html += scope.slvHtml;_x000D_
element.append($compile(html)($rootScope));_x000D_
}_x000D_
});_x000D_
};_x000D_
_x000D_
var controller = function($scope) {_x000D_
$scope.done = false;_x000D_
$scope.html = "";_x000D_
$scope.urls = $scope.slvTemplate.split(',');_x000D_
var promises = [];_x000D_
$scope.urls.forEach(function(url) {_x000D_
promises.add($templateRequest(url));_x000D_
});_x000D_
$q.all(promises).then(_x000D_
function() { // SUCCESS_x000D_
$scope.done = true;_x000D_
}, function() { // FAIL_x000D_
throw new Error('preload failed.');_x000D_
}_x000D_
);_x000D_
};_x000D_
_x000D_
return {_x000D_
restrict: 'A',_x000D_
scope: {_x000D_
utTemplate: '=', // the templates to load (comma separated)_x000D_
utAppend: '=', // boolean: append templates to DOM after load?_x000D_
utHtml: '=' // the html to append and compile after templates have been loaded_x000D_
},_x000D_
link: link,_x000D_
controller: controller_x000D_
};_x000D_
}]);
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js"></script>_x000D_
_x000D_
<div class="container-fluid"_x000D_
ut-preload_x000D_
ut-append="true"_x000D_
ut-template="'html/one.html,html/two.html'"_x000D_
ut-html="'<my-directive></my-directive>'">_x000D_
_x000D_
</div>
_x000D_
Run following command:
mvn clean install -DskipTests=true
Instead of using overflow:hidden
, which is a kind of hack, why not simply setting a fixed height, e.g. height:500px
, to the parent division?
In short, yes. But there are times when you might favor one vs. the other. Google "case switch vs. if else". There are some discussions already on SO too. Also, here is a good video that talks about it in the context of MATLAB:
http://blogs.mathworks.com/pick/2008/01/02/matlab-basics-switch-case-vs-if-elseif/
Personally, when I have 3 or more cases, I usually just go with case/switch.
The graphicx
package provides the command \resizebox{width}{height}{object}
:
\documentclass{article}
\usepackage{graphicx}
\begin{document}
\hrule
%%%
\makeatletter%
\setlength{\@tempdima}{\the\columnwidth}% the, well columnwidth
\settowidth{\@tempdimb}{(\ref{Equ:TooLong})}% the width of the "(1)"
\addtolength{\@tempdima}{-\the\@tempdimb}% which cannot be used for the math
\addtolength{\@tempdima}{-1em}%
% There is probably some variable giving the required minimal distance
% between math and label, but because I do not know it I used 1em instead.
\addtolength{\@tempdima}{-1pt}% distance must be greater than "1em"
\xdef\Equ@width{\the\@tempdima}% space remaining for math
\begin{equation}%
\resizebox{\Equ@width}{!}{$\displaystyle{% to get everything inside "big"
A+B+C+D+E+F+G+H+I+J+K+L+M+N+O+P+Q+R+S+T+U+V+W+X+Y+Z}$}%
\label{Equ:TooLong}%
\end{equation}%
\makeatother%
%%%
\hrule
\end{document}
I can give you two advices:
What you are using is not a model dialog, it is a separate window.
Use this code:
private static Object firstHandle;
private static Object lastHandle;
public static void switchToWindowsPopup() {
Set<String> handles = DriverManager.getCurrent().getWindowHandles();
Iterator<String> itr = handles.iterator();
firstHandle = itr.next();
lastHandle = firstHandle;
while (itr.hasNext()) {
lastHandle = itr.next();
}
DriverManager.getCurrent().switchTo().window(lastHandle.toString());
}
public static void switchToMainWindow() {
DriverManager.getCurrent().switchTo().window(firstHandle.toString());
Just drop the option v
.
-v
is for verbose. If you don't use it then it won't display:
tar -zxf tmp.tar.gz -C ~/tmp1
If by 'current directory' you mean the directory in which the zip file is, then I would use this command:
find . -name '*.zip' -execdir unzip {} \;
excerpt from find's man page
-execdir command ;
-execdir command {} +
Like -exec, but the specified command is run from the subdirectory containing the matched file, which is not normally the directory in which you started find. This a much more secure method for invoking commands, as it avoids race conditions during resolution of the paths to the matched files. As with the -exec option, the '+' form of -execdir will build a command line to process more than one matched file, but any given invocation of command will only list files that exist in the same subdirectory. If you use this option, you must ensure that your $PATH environment variable does not reference the current directory; otherwise, an attacker can run any commands they like by leaving an appropriately-named file in a directory in which you will run -execdir.
Here is a Gmail implementation of the accepted answer:
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
# me == my email address
# you == recipient's email address
me = "[email protected]"
you = "[email protected]"
# Create message container - the correct MIME type is multipart/alternative.
msg = MIMEMultipart('alternative')
msg['Subject'] = "Link"
msg['From'] = me
msg['To'] = you
# Create the body of the message (a plain-text and an HTML version).
text = "Hi!\nHow are you?\nHere is the link you wanted:\nhttp://www.python.org"
html = """\
<html>
<head></head>
<body>
<p>Hi!<br>
How are you?<br>
Here is the <a href="http://www.python.org">link</a> you wanted.
</p>
</body>
</html>
"""
# Record the MIME types of both parts - text/plain and text/html.
part1 = MIMEText(text, 'plain')
part2 = MIMEText(html, 'html')
# Attach parts into message container.
# According to RFC 2046, the last part of a multipart message, in this case
# the HTML message, is best and preferred.
msg.attach(part1)
msg.attach(part2)
# Send the message via local SMTP server.
mail = smtplib.SMTP('smtp.gmail.com', 587)
mail.ehlo()
mail.starttls()
mail.login('userName', 'password')
mail.sendmail(me, you, msg.as_string())
mail.quit()
Found another example where you would have to call destructor(s) manually. Suppose you have implemented a variant-like class that holds one of several types of data:
struct Variant {
union {
std::string str;
int num;
bool b;
};
enum Type { Str, Int, Bool } type;
};
If the Variant
instance was holding a std::string
, and now you're assigning a different type to the union, you must destruct the std::string
first. The compiler will not do that automatically.
From Solution Explorer, right click on myfile.txt and choose "Properties"
From there, set the Build Action
to content
and Copy to Output Directory
to either Copy always
or Copy if newer
It is looks stupid for me. But I had been in the same situation and I did revert for reverted commits. I did number reverts so I had to do revert for each 'revert commit'.
Now my commits history looks a weird a bit.
It is a pet project so it is OK. But for real-life project I would give preference to go to last commit before reverted restore all reverted code together in one commit and more reasonable comment.
Since May 23, 2018 update, when you're using a firebase dependency, you must include the firebase-core
dependency, too.
If adding it, you still having the error, try to update the gradle plugin in your gradle-wrapper.properties
to 4.5 version:
distributionUrl=https\://services.gradle.org/distributions/gradle-4.5-all.zip
and resync the project.
You cannot change the default but there is a codeless workaround.
Select the whole sheet and change the font size on your data to something small, like 10 or 12. When you zoom in to view the data you will find that the drop down box entries are now visible.
To emphasize, the issue is not so much with the size of the font in the drop down, it is the relative size between drop down and data display font sizes.
here's a way using the SSSE3 instruction pshufb using its Intel intrinsic, assuming you have a multiple of 4 int
s:
unsigned int *bswap(unsigned int *destination, unsigned int *source, int length) {
int i;
__m128i mask = _mm_set_epi8(12, 13, 14, 15, 8, 9, 10, 11, 4, 5, 6, 7, 0, 1, 2, 3);
for (i = 0; i < length; i += 4) {
_mm_storeu_si128((__m128i *)&destination[i],
_mm_shuffle_epi8(_mm_loadu_si128((__m128i *)&source[i]), mask));
}
return destination;
}
There's a prod()
in numpy that does what you're asking for.
In the first regex, each space character is being replaced, character by character, with the empty string.
In the second regex, each contiguous string of space characters is being replaced with the empty string because of the +
.
However, just like how 0 multiplied by anything else is 0, it seems as if both methods strip spaces in exactly the same way.
If you change the replacement string to '#'
, the difference becomes much clearer:
var str = ' A B C D EF ';
console.log(str.replace(/\s/g, '#')); // ##A#B##C###D#EF#
console.log(str.replace(/\s+/g, '#')); // #A#B#C#D#EF#
Building and simplifying @kindall's answer, here's what I typically use:
v_print = None
def main()
parser = argparse.ArgumentParser()
parser.add_argument('-v', '--verbosity', action="count",
help="increase output verbosity (e.g., -vv is more than -v)")
args = parser.parse_args()
if args.verbosity:
def _v_print(*verb_args):
if verb_args[0] > (3 - args.verbosity):
print verb_args[1]
else:
_v_print = lambda *a: None # do-nothing function
global v_print
v_print = _v_print
if __name__ == '__main__':
main()
This then provides the following usage throughout your script:
v_print(1, "INFO message")
v_print(2, "WARN message")
v_print(3, "ERROR message")
And your script can be called like this:
% python verbose-tester.py -v
ERROR message
% python verbose=tester.py -vv
WARN message
ERROR message
% python verbose-tester.py -vvv
INFO message
WARN message
ERROR message
A couple notes:
3
that sets the upper bound for your logging, but I accept that as a compromise for simplicity.v_print
to work throughout your program, you have to do the junk with the global. It's no fun, but I challenge somebody to find a better way.I've been searching answer but couldn't find but finally I could fix this by adding play-service-ads dependency let's try this
*) File -> Project Structure... -> Under the module you can find app and there is a option called dependencies and you can add com.google.android.gms:play-services-ads:x.x.x dependency to your project
I faced this problem when I try to import eclipse project into android studio
I just found this post: http://forum.springsource.org/showthread.php?68949-White-spaces-are-required-between-publicId-and-systemId./page2&s=c69fe19798f5a071d22eaf681ca84a56
A couple people here had success by switching the lines around in an XML file.
If you can use bootstrap3 then you can use css "navbar-fixed-top" also you need to add below css to push your page content down
body{
margin-top:100px;
}
Javascript files are often cached by the browser for a lot longer than you might expect.
This can often result in unexpected behaviour when you release a new version of your JS file.
Therefore, it is common practice to add a QueryString parameter to the URL for the javascript file. That way, the browser caches the Javascript file with v=1. When you release a new version of your javascript file you change the url's to v=2 and the browser will be forced to download a new copy.
You can probably skip the step of explicitly creating an array...
One trick that I like to use is to set the inter-field separator (IFS) to the delimiter character. This is especially handy for iterating through the space or return delimited results from the stdout of any of a number of unix commands.
Below is an example using semicolons (as you had mentioned in your question):
export IFS=";"
sentence="one;two;three"
for word in $sentence; do
echo "$word"
done
Note: in regular Bourne-shell scripting setting and exporting the IFS would occur on two separate lines (IFS='x'; export IFS;).
Just a quick thing, that denotes the intent of descending order.
descending = -1
a.sort_by { |h| h[:bar] * descending }
(Will think of a better way in the mean time) ;)
a.sort_by { |h| h[:bar] }.reverse!
Animations:
// slide to top of the page
$('.up').click(function () {
$("html, body").animate({
scrollTop: 0
}, 600);
return false;
});
// slide page to anchor
$('.menutop b').click(function(){
//event.preventDefault();
$('html, body').animate({
scrollTop: $( $(this).attr('href') ).offset().top
}, 600);
return false;
});
// Scroll to class, div
$("#button").click(function() {
$('html, body').animate({
scrollTop: $("#target-element").offset().top
}, 1000);
});
// div background animate
$(window).scroll(function () {
var x = $(this).scrollTop();
// freezze div background
$('.banner0').css('background-position', '0px ' + x +'px');
// from left to right
$('.banner0').css('background-position', x+'px ' +'0px');
// from right to left
$('.banner0').css('background-position', -x+'px ' +'0px');
// from bottom to top
$('#skills').css('background-position', '0px ' + -x + 'px');
// move background from top to bottom
$('.skills1').css('background-position', '0% ' + parseInt(-x / 1) + 'px' + ', 0% ' + parseInt(-x / 1) + 'px, center top');
// Show hide mtop menu
if ( x > 100 ) {
$( ".menu" ).addClass( 'menushow' );
$( ".menu" ).fadeIn("slow");
$( ".menu" ).animate({opacity: 0.75}, 500);
} else {
$( ".menu" ).removeClass( 'menushow' );
$( ".menu" ).animate({opacity: 1}, 500);
}
});
// progres bar animation simple
$('.bar1').each(function(i) {
var width = $(this).data('width');
$(this).animate({'width' : width + '%' }, 900, function(){
// Animation complete
});
});
As @Agam said,
You need this statement in your driver file:
from AthleteList import AtheleteList
Zookeeper is one of the best open source server and service that helps to reliably coordinates distributed processes. Zookeeper is a CP system (Refer CAP Theorem) that provides Consistency and Partition tolerance. Replication of Zookeeper state across all the nodes makes it an eventually consistent distributed service.
Moreover, any newly elected leader will update its followers with missing proposals or with a snapshot of the state, if the followers have many proposals missing.
Zookeeper also provides an API that is very easy to use. This blog post, Zookeeper Java API examples, has some examples if you are looking for examples.
So where do we use this? If your distributed service needs a centralized, reliable and consistent configuration management, locks, queues etc, you will find Zookeeper a reliable choice.
i tried all the solution above but none of them works for me. finaly i solved it myself, and find actually it's quite easy. there are two points you need to be careful.
parameters.setPreviewSize(cameraResolution.x, cameraResolution.y);
this previewSize must be one of the camera supported resolution, which can be get as below:
List<Camera.Size> rawSupportedSizes = parameters.getSupportedPreviewSizes();
usually one of the rawSupportedSize equals to the device resolution.
Second, place your SurfaceView in a FrameLayout and set the surface layout height and width in surfaceChanged method as above
FrameLayout.LayoutParams layoutParams = (FrameLayout.LayoutParams) surfaceView.getLayoutParams();
layoutParams.height = cameraResolution.x;
layoutParams.width = cameraResolution.y;
Ok, things done, hope this could help you.
Below code disable Focus on ListViewItem
<ListView.ItemContainerStyle>
<Style TargetType="{x:Type ListViewItem}">
<Setter Property="Background" Value="Transparent" />
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type ListViewItem}">
<ContentPresenter />
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
You can do it in the following way:
myfxn <- function(var1,var2,var3){
var1*var2*var3
}
lapply(1:3,myfxn,var2=2,var3=100)
and you will get the answer:
[[1]] [1] 200
[[2]] [1] 400
[[3]] [1] 600
Wrap the table in a DIV, set with the following style:
div.wrapper {
width: 500px;
height: 500px;
overflow: auto;
}
This could be updated to ES6 with arrow functions and look like:
getFeed().then(data => vm.feed = data);
If you wish to use the async function
, you could also do like that:
async function myFunction(){
vm.feed = await getFeed();
// do whatever you need with vm.feed below
}
Set the datasource property to an empty string then call the Clear method.
generally . doesn't match newlines, so try ((.|\n)*)<foobar>
This could be because your CSV file has embedded single or double quotes. If your CSV file is tab-delimited try opening it as:
c = csv.reader(f, delimiter='\t', quoting=csv.QUOTE_NONE)
Instead of:
void addStudent(person)
{
return;
}
try this:
void addStudent(student person)
{
return;
}
Since you have already declared a structure called 'student' you don't necessarily have to specify so in the function implementation as in:
void addStudent(struct student person)
{
return;
}
Its really working if we use Doctype on our web page jquery(window) will return the viewport height else it will return the complete document height.
Define the following tag on the top of your web page:
<!DOCTYPE html>
As pointed out in this comment How do you check in python whether a string contains only numbers? the isdigit()
method is not totally accurate for this use case, because it returns True for some digit-like characters:
>>> "\u2070".isdigit() # unicode escaped 'superscript zero'
True
If this needs to be avoided, the following simple function checks, if all characters in a string are a digit between "0" and "9":
import string
def contains_only_digits(s):
# True for "", "0", "123"
# False for "1.2", "1,2", "-1", "a", "a1"
for ch in s:
if not ch in string.digits:
return False
return True
Used in the example from the question:
if len(isbn) == 10 and contains_only_digits(isbn):
print ("Works")
Have not tested it yet, but the looks are better than the one Alex mentions.
The description at winginx.com/en/htaccess says:
About the htaccess to nginx converter
The service is to convert an Apache's .htaccess to nginx configuration instructions.
First of all, the service was thought as a mod_rewrite to nginx converter. However, it allows you to convert some other instructions that have reason to be ported from Apache to nginx.
Note server instructions (e.g. php_value, etc.) are ignored.
The converter does not check syntax, including regular expressions and logic errors.
Please, check the result manually before use.
String stringrep = myintvar.ToString("X");
int num = int.Parse("FF", System.Globalization.NumberStyles.HexNumber);
You can also go with:
Dim ts As New TimeSpan(35, 21, 59, 59) '(11, 22, 30, 30) '
Dim TimeStr1 As String = String.Format("{0:c}", ts)
Dim TimeStr2 As String = New Date(ts.Ticks).ToString("dd.HH:mm:ss")
EDIT:
You can also look at Strings.Format.
Dim ts As New TimeSpan(23, 30, 59)
Dim str As String = Strings.Format(New DateTime(ts.Ticks), "H:mm:ss")
If you have an app with extensions and/or a watch app and you have multiple provisioning profiles for each extension/watch app then you should use this script to re-sign the ipa file.
Here is an example of how to use this script:
./resign.sh YourApp.ipa "iPhone Distribution: YourCompanyOrDeveloperName" -p <path_to_provisioning_profile_for_app>.mobileprovision -p <path_to_provisioning_profile_for_watchkitextension>.mobileprovision -p <path_to_provisioning_profile_for_watchkitapp>.mobileprovision -p <path_to_provisioning_profile_for_todayextension>.mobileprovision resignedYourApp.ipa
You can include other extension provisioning profiles too by adding it with yet another -p option.
For me - all the provisioning profiles were signed by the same certificate/signing identity.
Two End Registration or Users Automatically Registered to "Shouttoday" by ajax when they Complete Registration by form submission.
var deffered = $.ajax({
url:"code.shouttoday.com/ajax_registration",
type:"POST",
data: $('form').serialize()
});
$(function(){
var form;
$('form').submit( function(event) {
var formId = $(this).attr("id");
form = this;
event.preventDefault();
deffered.done(function(response){
alert($('form').serializeArray());alert(response);
alert("success");
alert('Submitting');
form.submit();
})
.error(function(){
alert(JSON.stringify($('form').serializeArray()).toString());
alert("error");
form.submit();
});
});
});
If you're on the New Google Sheets, this is all you need to do, according to the docs:
change your recalculation setting to "On change and every minute" in your spreadsheet at File > Spreadsheet settings.
This will make the entire sheet update itself every minute, on the server side, regardless of whether you have the spreadsheet up in your browser or not.
If you're on the old Google Sheets, you'll want to add a cell with this formula to achieve the same functionality:
=GoogleClock()
EDIT to include old and new Google Sheets and change to =GoogleClock()
.
On older notebooks with integrated video Swing app starts and works much faster than JavaFX app. As for development, I'd recommend switch to Scala - comparable Scala Swing app contains 2..3 times less code than Java. As for Swing vs SWT: Netbeans GUI considerably faster than Eclipse...
As your data is nvarchar there is no guarantee it will convert to datetime (as it may hold invalid date/time information) - so a way to handle this is to use ISDATE which I would use within a cross apply. (Cross apply results are reusable hence making is easier for the output formats.)
| YOUR_DT | SQL2008 |
|-----------------------------|---------------------|
| 2013-08-29 13:55:48 | 29-08-2013 13:55:48 |
| 2013-08-29 13:55:48 blah | (null) |
| 2013-08-29 13:55:48 rubbish | (null) |
SELECT
[Your_Dt]
, convert(varchar, ca1.dt_converted ,105) + ' ' + convert(varchar, ca1.dt_converted ,8) AS sql2008
FROM your_table
CROSS apply ( SELECT CASE WHEN isdate([Your_Dt]) = 1
THEN convert(datetime,[Your_Dt])
ELSE NULL
END
) AS ca1 (dt_converted)
;
Notes:
You could also introduce left([Your_Dt],19) to only get a string like '2013-08-29 13:55:48' from '2013-08-29 13:55:48 rubbish'
For that specific output I think you will need 2 sql 2008 date styles (105 & 8) sql2012 added for comparison
declare @your_dt as datetime2
set @your_dt = '2013-08-29 13:55:48'
select
FORMAT(@your_dt, 'dd-MM-yyyy H:m:s') as sql2012
, convert(varchar, @your_dt ,105) + ' ' + convert(varchar, @your_dt ,8) as sql2008
| SQL2012 | SQL2008 |
|---------------------|---------------------|
| 29-08-2013 13:55:48 | 29-08-2013 13:55:48 |
Your syntax appears completely correct in:
mongoimport --db dbName --collection collectionName --file fileName.json
Make sure you are in the correct folder or provide the full path.
you cant do it.. because jsp is compiled and converted into html server side whereas javascript is executed on client side. you may set the value to a hidden html element and send to servlet in request just in case you want to use for further
Use the code below to generate the random number of 11 characters or change the number as per your requirement.
$randomNum=substr(str_shuffle("0123456789abcdefghijklmnopqrstvwxyz"), 0, 11);
or we can use custom function to generate the random number
function randomNumber($length){
$numbers = range(0,9);
shuffle($numbers);
for($i = 0;$i < $length;$i++)
$digits .= $numbers[$i];
return $digits;
}
//generate random number
$randomNum=randomNumber(11);
I got a nice solution inspired by Apple's Table View Animations and Gestures. I deleted unnecessary parts from Apple's sample and translated it into swift.
I know the answer is quite long, but all the code is necessary. Fortunately, you can just copy and paste most of the code and just need to do a bit modification on step 1 and 3
1.create SectionHeaderView.swift
and SectionHeaderView.xib
import UIKit
protocol SectionHeaderViewDelegate {
func sectionHeaderView(sectionHeaderView: SectionHeaderView, sectionOpened: Int)
func sectionHeaderView(sectionHeaderView: SectionHeaderView, sectionClosed: Int)
}
class SectionHeaderView: UITableViewHeaderFooterView {
var section: Int?
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var disclosureButton: UIButton!
@IBAction func toggleOpen() {
self.toggleOpenWithUserAction(true)
}
var delegate: SectionHeaderViewDelegate?
func toggleOpenWithUserAction(userAction: Bool) {
self.disclosureButton.selected = !self.disclosureButton.selected
if userAction {
if self.disclosureButton.selected {
self.delegate?.sectionHeaderView(self, sectionClosed: self.section!)
} else {
self.delegate?.sectionHeaderView(self, sectionOpened: self.section!)
}
}
}
override func awakeFromNib() {
var tapGesture: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: "toggleOpen")
self.addGestureRecognizer(tapGesture)
// change the button image here, you can also set image via IB.
self.disclosureButton.setImage(UIImage(named: "arrow_up"), forState: UIControlState.Selected)
self.disclosureButton.setImage(UIImage(named: "arrow_down"), forState: UIControlState.Normal)
}
}
the SectionHeaderView.xib
(the view with gray background) should look something like this in a tableview(you can customize it according to your needs, of course):
note:
a) the toggleOpen
action should be linked to disclosureButton
b) the disclosureButton
and toggleOpen
action are not necessary. You can delete these 2 things if you don't need the button.
2.create SectionInfo.swift
import UIKit
class SectionInfo: NSObject {
var open: Bool = true
var itemsInSection: NSMutableArray = []
var sectionTitle: String?
init(itemsInSection: NSMutableArray, sectionTitle: String) {
self.itemsInSection = itemsInSection
self.sectionTitle = sectionTitle
}
}
3.in your tableview
import UIKit
class TableViewController: UITableViewController, SectionHeaderViewDelegate {
let SectionHeaderViewIdentifier = "SectionHeaderViewIdentifier"
var sectionInfoArray: NSMutableArray = []
override func viewDidLoad() {
super.viewDidLoad()
let sectionHeaderNib: UINib = UINib(nibName: "SectionHeaderView", bundle: nil)
self.tableView.registerNib(sectionHeaderNib, forHeaderFooterViewReuseIdentifier: SectionHeaderViewIdentifier)
// you can change section height based on your needs
self.tableView.sectionHeaderHeight = 30
// You should set up your SectionInfo here
var firstSection: SectionInfo = SectionInfo(itemsInSection: ["1"], sectionTitle: "firstSection")
var secondSection: SectionInfo = SectionInfo(itemsInSection: ["2"], sectionTitle: "secondSection"))
sectionInfoArray.addObjectsFromArray([firstSection, secondSection])
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return sectionInfoArray.count
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if self.sectionInfoArray.count > 0 {
var sectionInfo: SectionInfo = sectionInfoArray[section] as! SectionInfo
if sectionInfo.open {
return sectionInfo.open ? sectionInfo.itemsInSection.count : 0
}
}
return 0
}
override func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let sectionHeaderView: SectionHeaderView! = self.tableView.dequeueReusableHeaderFooterViewWithIdentifier(SectionHeaderViewIdentifier) as! SectionHeaderView
var sectionInfo: SectionInfo = sectionInfoArray[section] as! SectionInfo
sectionHeaderView.titleLabel.text = sectionInfo.sectionTitle
sectionHeaderView.section = section
sectionHeaderView.delegate = self
let backGroundView = UIView()
// you can customize the background color of the header here
backGroundView.backgroundColor = UIColor(red:0.89, green:0.89, blue:0.89, alpha:1)
sectionHeaderView.backgroundView = backGroundView
return sectionHeaderView
}
func sectionHeaderView(sectionHeaderView: SectionHeaderView, sectionOpened: Int) {
var sectionInfo: SectionInfo = sectionInfoArray[sectionOpened] as! SectionInfo
var countOfRowsToInsert = sectionInfo.itemsInSection.count
sectionInfo.open = true
var indexPathToInsert: NSMutableArray = NSMutableArray()
for i in 0..<countOfRowsToInsert {
indexPathToInsert.addObject(NSIndexPath(forRow: i, inSection: sectionOpened))
}
self.tableView.insertRowsAtIndexPaths(indexPathToInsert as [AnyObject], withRowAnimation: .Top)
}
func sectionHeaderView(sectionHeaderView: SectionHeaderView, sectionClosed: Int) {
var sectionInfo: SectionInfo = sectionInfoArray[sectionClosed] as! SectionInfo
var countOfRowsToDelete = sectionInfo.itemsInSection.count
sectionInfo.open = false
if countOfRowsToDelete > 0 {
var indexPathToDelete: NSMutableArray = NSMutableArray()
for i in 0..<countOfRowsToDelete {
indexPathToDelete.addObject(NSIndexPath(forRow: i, inSection: sectionClosed))
}
self.tableView.deleteRowsAtIndexPaths(indexPathToDelete as [AnyObject], withRowAnimation: .Top)
}
}
}
Checking if v
contains the element x
:
#include <algorithm>
if(std::find(v.begin(), v.end(), x) != v.end()) {
/* v contains x */
} else {
/* v does not contain x */
}
Checking if v
contains elements (is non-empty):
if(!v.empty()){
/* v is non-empty */
} else {
/* v is empty */
}
To do this, I use a custom filter.
In my app:
myApp.filter('rawHtml', ['$sce', function($sce){
return function(val) {
return $sce.trustAsHtml(val);
};
}]);
Then, in the view:
<h1>{{ stuff.title}}</h1>
<div ng-bind-html="stuff.content | rawHtml"></div>
For future readers.
I got this error because my specified LOG file had a space in it:
BEFORE:
/l:FileLogger,Microsoft.Build.Engine;logfile=c:\Folder With Spaces\My_Log.log
AFTER: (which resolved it)
/l:FileLogger,Microsoft.Build.Engine;logfile="c:\Folder With Spaces\My_Log.log"
If it's about just one property - let's say you want to temporarily change some default, for instance disable CA checking: you can do it with
npm config set ca ""
To come back to the defaults for that setting, simply
npm config delete ca
To verify, use npm config get ca
.
I finally got this to work after, like, 4 separate tries after incurring the same problem that was originally posted. So here's what happened, I am not sure if this is an old issue now (2009-07-09), but I will post anyway in case it is helpful to you. What worked for me... might work for you...
Hopefully this helps.
(Edit) The previously recomended add-on is not available any longer, you may try this other one
For development purposes in Chrome, installing this add on will get rid of that specific error:
Access to XMLHttpRequest at 'http://192.168.1.42:8080/sockjs-node/info?t=1546163388687'
from origin 'http://localhost:8080' has been blocked by CORS policy: The value of the
'Access-Control-Allow-Origin' header in the response must not be the wildcard '*'
when the request's credentials mode is 'include'. The credentials mode of requests
initiated by the XMLHttpRequest is controlled by the withCredentials attribute.
After installing, make sure you add your url pattern to the Intercepted URLs
by clicking on the AddOn's (CORS, green or red) icon and filling the appropriate textbox. An example URL pattern to add here that will work with http://localhost:8080
would be: *://*
This should help you.
Dim Ws As Worksheet
Set Ws = Sheets("Sheet-Name")
Dim tbl As ListObject
Set tbl = Ws.ListObjects("Table-Name")
Dim newrow As ListRow
Set newrow = tbl.ListRows.Add
With newrow
.Range(1, Ws.Range("Table-Name[Table-Column-Name]").Column) = "Your Data"
End With
I'm sorry, I managed to find the answer myself using google and a bit of luck : )
For those interested;
I installed the pdftk (pdf toolkit) on our debian server, and using the following command I achieved desired output:
pdftk file1.pdf file2.pdf cat output output.pdf
OR
gs -q -sPAPERSIZE=letter -dNOPAUSE -dBATCH -sDEVICE=pdfwrite -sOutputFile=output.pdf file1.pdf file2.pdf file3.pdf ...
This in turn can be piped directly into pdf2ps.
IE < 8 does not render the dropdown list itself it just uses the windows control which cannot be styled this way. Beginning from IE 8 this has changed and the styling is now applied. Of course, its market share is rather negligible yet.
Yes. 'main( )' method can be overloaded. I have tried to put in some piece of code to answer your question.
public class Test{
static public void main( String [] args )
{
System.out.println( "In the JVMs static main" );
main( 5, 6, 7 ); //Calling overloaded static main method
Test t = new Test( );
String [] message = { "Subhash", "Loves", "Programming" };
t.main(5);
t.main( 6, message );
}
public static void main( int ... args )
{
System.out.println( "In the static main called by JVM's main" );
for( int val : args )
{
System.out.println( val );
}
}
public void main( int x )
{
System.out.println( "1: In the overloaded non-static main with int with value " + x );
}
public void main( int x, String [] args )
{
System.out.println( "2: In the overloaded non-static main with int with value " + x );
for ( String val : args )
{
System.out.println( val );
}
}
}
Output:
$ java Test
In the JVMs static main
In the static main called by JVM's main
5
6
7
1: In the overloaded non-static main with int with value 5
2: In the overloaded non-static main with int with value 6
Subhash
Loves
Programming
$
In the above code, both static-method as well as a non-static version of main methods are overloaded for demonstration purpose. Note that, by writing JVMs main, I mean to say, it is the main method that JVM uses first to execute a program.
SELECT * FROM Employees
WHERE rownum <= 3
ORDER BY Salary ;
The parent of the row is not the object you think, this is what I understand from the error.
Try detecting the parent of the row first, then you can be sure what to write into getElementById
part of the parent.
You can use the contains selector to search for elements containing a specific text
var elem = $('div.text_div:contains("This div contains some text")')?;
elem.text(elem.text().replace("contains", "Hello everyone"));
??????????????????????????????????????????
Both on Windows and POSIX systems, named-pipes provide a way for inter-process communication to occur among processes running on the same machine. What named pipes give you is a way to send your data without having the performance penalty of involving the network stack.
Just like you have a server listening to a IP address/port for incoming requests, a server can also set up a named pipe which can listen for requests. In either cases, the client process (or the DB access library) must know the specific address (or pipe name) to send the request. Often, a commonly used standard default exists (much like port 80 for HTTP, SQL server uses port 1433 in TCP/IP; \\.\pipe\sql\query for a named pipe).
By setting up additional named pipes, you can have multiple DB servers running, each with its own request listeners.
The advantage of named pipes is that it is usually much faster, and frees up network stack resources.
-- BTW, in the Windows world, you can also have named pipes to remote machines -- but in that case, the named pipe is transported over TCP/IP, so you will lose performance. Use named pipes for local machine communication.
If you are trying to do something similar to the Google search page when open in Chrome, (where certain events are triggered when you 'focus' on the page), then the hover() event may help.
$(window).hover(function() {
// code here...
});
I have a new response for this case: the easy way to solve this is having you jenkinsFile from source code.
Then you chose: this job have a git parameter
And and the Pipeline setup, unchecked the "Lightweight checkout" checkbox, this will perform a really git checkout on job workspace.
After, the parameter will be autopopulate by your git branch
I Got AutoFlash light with below simple Three Steps.
<uses-permission android:name="android.permission.CAMERA" /> <uses-feature android:name="android.hardware.camera" /> <uses-permission android:name="android.permission.FLASHLIGHT"/> <uses-feature android:name="android.hardware.camera.flash" android:required="false" />
In your Camera Code do this way.
//Open Camera
Camera mCamera = Camera.open();
//Get Camera Params for customisation
Camera.Parameters parameters = mCamera.getParameters();
//Check Whether device supports AutoFlash, If you YES then set AutoFlash
List<String> flashModes = parameters.getSupportedFlashModes();
if (flashModes.contains(android.hardware.Camera.Parameters.FLASH_MODE_AUTO))
{
parameters.setFlashMode(Parameters.FLASH_MODE_AUTO);
}
mCamera.setParameters(parameters);
mCamera.startPreview();
Build + Run —> Now Go to Dim light area and Snap photo, you should get auto flash light if device supports.