You want to join on condition 1 AND condition 2, so simply use the AND keyword as below
ON a.userid = b.sourceid AND a.listid = b.destinationid;
I had the same problem, and in my case, the solution was updating the usb-serial driver using windows update on windows 10 device's manager. There was no need to download a especific driver, I just let windows update find a suitable driver.
Please consider replacring the accepted solution with the following:
parse_url() will always include any sub-domain(s), so this function doesn't parse domain names very well. Here are some examples:
$url = 'http://www.google.com/dhasjkdas/sadsdds/sdda/sdads.html';
$parse = parse_url($url);
echo $parse['host']; // prints 'www.google.com'
echo parse_url('https://subdomain.example.com/foo/bar', PHP_URL_HOST);
// Output: subdomain.example.com
echo parse_url('https://subdomain.example.co.uk/foo/bar', PHP_URL_HOST);
// Output: subdomain.example.co.uk
Instead, you may consider this pragmatic solution. It will cover many, but not all domain names -- for instance, lower-level domains such as 'sos.state.oh.us' are not covered.
function getDomain($url) {
$host = parse_url($url, PHP_URL_HOST);
if(filter_var($host,FILTER_VALIDATE_IP)) {
// IP address returned as domain
return $host; //* or replace with null if you don't want an IP back
}
$domain_array = explode(".", str_replace('www.', '', $host));
$count = count($domain_array);
if( $count>=3 && strlen($domain_array[$count-2])==2 ) {
// SLD (example.co.uk)
return implode('.', array_splice($domain_array, $count-3,3));
} else if( $count>=2 ) {
// TLD (example.com)
return implode('.', array_splice($domain_array, $count-2,2));
}
}
// Your domains
echo getDomain('http://google.com/dhasjkdas/sadsdds/sdda/sdads.html'); // google.com
echo getDomain('http://www.google.com/dhasjkdas/sadsdds/sdda/sdads.html'); // google.com
echo getDomain('http://google.co.uk/dhasjkdas/sadsdds/sdda/sdads.html'); // google.co.uk
// TLD
echo getDomain('https://shop.example.com'); // example.com
echo getDomain('https://foo.bar.example.com'); // example.com
echo getDomain('https://www.example.com'); // example.com
echo getDomain('https://example.com'); // example.com
// SLD
echo getDomain('https://more.news.bbc.co.uk'); // bbc.co.uk
echo getDomain('https://www.bbc.co.uk'); // bbc.co.uk
echo getDomain('https://bbc.co.uk'); // bbc.co.uk
// IP
echo getDomain('https://1.2.3.45'); // 1.2.3.45
Finally, Jeremy Kendall's PHP Domain Parser allows you to parse the domain name from a url. League URI Hostname Parser will also do the job.
First, it's always worth noting that git reset --hard
is a potentially dangerous command, since it throws away all your uncommitted changes. For safety, you should always check that the output of git status
is clean (that is, empty) before using it.
Initially you say the following:
So I know that Git tracks changes I make to my application, and it holds on to them until I commit the changes, but here's where I'm hung up:
That's incorrect. Git only records the state of the files when you stage them (with git add
) or when you create a commit. Once you've created a commit which has your project files in a particular state, they're very safe, but until then Git's not really "tracking changes" to your files. (for example, even if you do git add
to stage a new version of the file, that overwrites the previously staged version of that file in the staging area.)
In your question you then go on to ask the following:
When I want to revert to a previous commit I use: git reset --hard HEAD And git returns: HEAD is now at 820f417 micro
How do I then revert the files on my hard drive back to that previous commit?
If you do git reset --hard <SOME-COMMIT>
then Git will:
master
) back to point at <SOME-COMMIT>
.<SOME-COMMIT>
.HEAD
points to your current branch (or current commit), so all that git reset --hard HEAD
will do is to throw away any uncommitted changes you have.
So, suppose the good commit that you want to go back to is f414f31
. (You can find that via git log
or any history browser.) You then have a few different options depending on exactly what you want to do:
git reset --hard f414f31
. However, this is rewriting the history of your branch, so you should avoid it if you've shared this branch with anyone. Also, the commits you did after f414f31
will no longer be in the history of your master
branch.Create a new commit that represents exactly the same state of the project as f414f31
, but just adds that on to the history, so you don't lose any history. You can do that using the steps suggested in this answer - something like:
git reset --hard f414f31
git reset --soft HEAD@{1}
git commit -m "Reverting to the state of the project at f414f31"
Well,
Just worked it out. While having both installations we have two ORACLE_HOME directories and both have SQAORA32.dll files. While looking up for ORACLE_HOMe my app was getting confused..I just removed the Client oracle home entry as oracle client is by default present in oracle DB Now its working...Thanks!!
Microsoft provides us built-in functionality which we use in our application for security purposes, so no one can hack our site or invade some critical information.
From Purpose Of ValidateAntiForgeryToken In MVC Application by Harpreet Singh:
Use of ValidateAntiForgeryToken
Let’s try with a simple example to understand this concept. I do not want to make it too complicated, that’s why I am going to use a template of an MVC application, already available in Visual Studio. We will do this step by step. Let’s start.
Step 1 - Create two MVC applications with default internet template and give those names as CrossSite_RequestForgery and Attack_Application respectively.
Now, open CrossSite_RequestForgery application's Web Config and change the connection string with the one given below and then save.
`
<connectionStrings> <add name="DefaultConnection" connectionString="Data Source=local\SQLEXPRESS;Initial Catalog=CSRF; Integrated Security=true;" providerName="System.Data.SqlClient" /> </connectionStrings>
Now, click on Tools >> NuGet Package Manager, then Package Manager Console
Now, run the below mentioned three commands in Package Manager Console to create the database.
Enable-Migrations add-migration first update-database
Important Notes - I have created database with code first approach because I want to make this example in the way developers work. You can create database manually also. It's your choice.
- Now, open Account Controller. Here, you will see a register method whose type is post. Above this method, there should be an attribute available as [ValidateAntiForgeryToken]. Comment this attribute. Now, right click on register and click go to View. There again, you will find an html helper as @Html.AntiForgeryToken() . Comment this one also. Run the application and click on register button. The URL will be open as:
http://localhost:52269/Account/Register
Notes- I know now the question being raised in all readers’ minds is why these two helpers need to be commented, as everyone knows these are used to validate request. Then, I just want to let you all know that this is just because I want to show the difference after and before applying these helpers.
Now, open the second application which is Attack_Application. Then, open Register method of Account Controller. Just change the POST method with the simple one, shown below.
Registration Form
- @Html.LabelFor(m => m.UserName) @Html.TextBoxFor(m => m.UserName)
- @Html.LabelFor(m => m.Password) @Html.PasswordFor(m => m.Password)
- @Html.LabelFor(m => m.ConfirmPassword) @Html.PasswordFor(m => m.ConfirmPassword)
7.Now, suppose you are a hacker and you know the URL from where you can register user in CrossSite_RequestForgery application. Now, you created a Forgery site as Attacker_Application and just put the same URL in post method.
8.Run this application now and fill the register fields and click on register. You will see you are registered in CrossSite_RequestForgery application. If you check the database of CrossSite_RequestForgery application then you will see and entry you have entered.
- Important - Now, open CrossSite_RequestForgery application and comment out the token in Account Controller and register the View. Try to register again with the same process. Then, an error will occur as below.
Server Error in '/' Application. ________________________________________ The required anti-forgery cookie "__RequestVerificationToken" is not present.
This is what the concept says. What we add in View i.e. @Html.AntiForgeryToken() generates __RequestVerificationToken on load time and [ValidateAntiForgeryToken] available on Controller method. Match this token on post time. If token is the same, then it means this is a valid request.
insert into run(id,name,dob)values(&id,'&name',[what should I write here?]);
insert into run(id,name,dob)values(&id,'&name',TO_DATE('&dob','YYYY-MM-DD'));
Question was: Why is not (explicitly) calling return faster or better, and thus preferable?
There is no statement in R documentation making such an assumption.
The main page ?'function' says:
function( arglist ) expr
return(value)
Is it faster without calling return?
Both function()
and return()
are primitive functions and the function()
itself returns last evaluated value even without including return()
function.
Calling return()
as .Primitive('return')
with that last value as an argument will do the same job but needs one call more. So that this (often) unnecessary .Primitive('return')
call can draw additional resources.
Simple measurement however shows that the resulting difference is very small and thus can not be the reason for not using explicit return. The following plot is created from data selected this way:
bench_nor2 <- function(x,repeats) { system.time(rep(
# without explicit return
(function(x) vector(length=x,mode="numeric"))(x)
,repeats)) }
bench_ret2 <- function(x,repeats) { system.time(rep(
# with explicit return
(function(x) return(vector(length=x,mode="numeric")))(x)
,repeats)) }
maxlen <- 1000
reps <- 10000
along <- seq(from=1,to=maxlen,by=5)
ret <- sapply(along,FUN=bench_ret2,repeats=reps)
nor <- sapply(along,FUN=bench_nor2,repeats=reps)
res <- data.frame(N=along,ELAPSED_RET=ret["elapsed",],ELAPSED_NOR=nor["elapsed",])
# res object is then visualized
# R version 2.15
The picture above may slightly difffer on your platform. Based on measured data, the size of returned object is not causing any difference, the number of repeats (even if scaled up) makes just a very small difference, which in real word with real data and real algorithm could not be counted or make your script run faster.
Is it better without calling return?
Return
is good tool for clearly designing "leaves" of code where the routine should end, jump out of the function and return value.
# here without calling .Primitive('return')
> (function() {10;20;30;40})()
[1] 40
# here with .Primitive('return')
> (function() {10;20;30;40;return(40)})()
[1] 40
# here return terminates flow
> (function() {10;20;return();30;40})()
NULL
> (function() {10;20;return(25);30;40})()
[1] 25
>
It depends on strategy and programming style of the programmer what style he use, he can use no return() as it is not required.
R core programmers uses both approaches ie. with and without explicit return() as it is possible to find in sources of 'base' functions.
Many times only return() is used (no argument) returning NULL in cases to conditially stop the function.
It is not clear if it is better or not as standard user or analyst using R can not see the real difference.
My opinion is that the question should be: Is there any danger in using explicit return coming from R implementation?
Or, maybe better, user writing function code should always ask: What is the effect in not using explicit return (or placing object to be returned as last leaf of code branch) in the function code?
It is possible to center a video inside an element just like a cover
sized background-image
without JS using the object-fit
attribute or CSS Transforms
.
As pointed in the comments, it is possible to achieve the same result without CSS transform
, but using object-fit
, which I think it's an even better option for the same result:
.video-container {
height: 300px;
width: 300px;
position: relative;
}
.video-container video {
width: 100%;
height: 100%;
position: absolute;
object-fit: cover;
z-index: 0;
}
/* Just styling the content of the div, the *magic* in the previous rules */
.video-container .caption {
z-index: 1;
position: relative;
text-align: center;
color: #dc0000;
padding: 10px;
}
_x000D_
<div class="video-container">
<video autoplay muted loop>
<source src="https://commondatastorage.googleapis.com/gtv-videos-bucket/sample/BigBuckBunny.mp4" type="video/mp4" />
</video>
<div class="caption">
<h2>Your caption here</h2>
</div>
</div>
_x000D_
You can set a video as a background to any HTML element easily thanks to transform
CSS property.
Note that you can use the transform
technique to center vertically and horizontally any HTML element.
.video-container {
height: 300px;
width: 300px;
overflow: hidden;
position: relative;
}
.video-container video {
min-width: 100%;
min-height: 100%;
position: absolute;
top: 50%;
left: 50%;
transform: translateX(-50%) translateY(-50%);
}
/* Just styling the content of the div, the *magic* in the previous rules */
.video-container .caption {
z-index: 1;
position: relative;
text-align: center;
color: #dc0000;
padding: 10px;
}
_x000D_
<div class="video-container">
<video autoplay muted loop>
<source src="https://commondatastorage.googleapis.com/gtv-videos-bucket/sample/BigBuckBunny.mp4" type="video/mp4" />
</video>
<div class="caption">
<h2>Your caption here</h2>
</div>
</div>
_x000D_
While doing my own server side JS experimentation I ended up using teajs. It conforms to common.js, is based on V8 AND is the only project that I know of that provides 'mod_teajs' apache server module.
In my opinion Node.js server is not production ready and lacks too many features - Apache is battle tested and the right way to do SSJS.
You're trying to put a text node inside an input element.
Input elements are empty and can't have children.
...
var checkbox = document.createElement('input');
checkbox.type = "checkbox";
checkbox.name = "name";
checkbox.value = "value";
checkbox.id = "id";
var label = document.createElement('label')
label.htmlFor = "id";
label.appendChild(document.createTextNode('text for label after checkbox'));
container.appendChild(checkbox);
container.appendChild(label);
It's more than one error
Under apply plugin: 'android-library'
add this ::
android {
packagingOptions {
exclude 'META-INF/ASL2.0'
exclude 'META-INF/LICENSE'
exclude 'META-INF/NOTICE'
}
}
In case of duplicate files it's easy, look inside the JAR
under the META-INF
dir and see what's causing the error. It could be multiple. In my case Couchbase Lite plugin.
As you add more plugins, you will need more exceptions
You can do something like this:
public myform()
{
InitializeComponent(); // this will be called in ComboBox ComboBox = new System.Windows.Forms.ComboBox();
}
private void Form1_Load(object sender, EventArgs e)
{
// TODO: This line of code loads data into the 'myDataSet.someTable' table. You can move, or remove it, as needed.
this.myTableAdapter.Fill(this.myDataSet.someTable);
comboBox1.SelectedItem = null;
comboBox1.SelectedText = "--select--";
}
The accepted answer appears to be targetted for C++, so I thought I'd add an answer that pertains to C, and this differs in a few ways. There were also some changes made between ISO/IEC 9899:1989 (C90) and ISO/IEC 9899:1999 (C99).
main()
should be declared as either:
int main(void)
int main(int argc, char **argv)
Or equivalent. For example, int main(int argc, char *argv[])
is equivalent to the second one. In C90, the int
return type can be omitted as it is a default, but in C99 and newer, the int
return type may not be omitted.
If an implementation permits it, main()
can be declared in other ways (e.g., int main(int argc, char *argv[], char *envp[])
), but this makes the program implementation defined, and no longer strictly conforming.
The standard defines 3 values for returning that are strictly conforming (that is, does not rely on implementation defined behaviour): 0
and EXIT_SUCCESS
for a successful termination, and EXIT_FAILURE
for an unsuccessful termination. Any other values are non-standard and implementation defined. In C90, main()
must have an explicit return
statement at the end to avoid undefined behaviour. In C99 and newer, you may omit the return statement from main()
. If you do, and main()
finished, there is an implicit return 0
.
Finally, there is nothing wrong from a standards point of view with calling main()
recursively from a C program.
I think the java.lang.UnsupportedOperationException
is what you are looking for.
You could write a custom validation attribute:
public class CombinedMinLengthAttribute: ValidationAttribute
{
public CombinedMinLengthAttribute(int minLength, params string[] propertyNames)
{
this.PropertyNames = propertyNames;
this.MinLength = minLength;
}
public string[] PropertyNames { get; private set; }
public int MinLength { get; private set; }
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
var properties = this.PropertyNames.Select(validationContext.ObjectType.GetProperty);
var values = properties.Select(p => p.GetValue(validationContext.ObjectInstance, null)).OfType<string>();
var totalLength = values.Sum(x => x.Length) + Convert.ToString(value).Length;
if (totalLength < this.MinLength)
{
return new ValidationResult(this.FormatErrorMessage(validationContext.DisplayName));
}
return null;
}
}
and then you might have a view model and decorate one of its properties with it:
public class MyViewModel
{
[CombinedMinLength(20, "Bar", "Baz", ErrorMessage = "The combined minimum length of the Foo, Bar and Baz properties should be longer than 20")]
public string Foo { get; set; }
public string Bar { get; set; }
public string Baz { get; set; }
}
try this as well, when you have a invalid number error
In this a.emplid is number and b.emplid is an varchar2 so if you got to convert one of the sides
where to_char(a.emplid)=b.emplid
I would do something like this:
bool isBigEndian() {
static unsigned long x(1);
static bool result(reinterpret_cast<unsigned char*>(&x)[0] == 0);
return result;
}
Along these lines, you would get a time efficient function that only does the calculation once.
The current answer wasn't working. I wanted to remove the title entirely, yet the text "back" wasn't going away.
Go back to the previous view controller and set its title property:
self.title = @" ";
ONLY works when the previous View Controller does not have a title
Since my Edit on the above post by thevangelist wasn't approved, posting additional information.
If you want to pick value from package.json like a defined version number and access it through DefinePlugin inside Javascript.
{"version": "0.0.1"}
Then, Import package.json inside respective webpack.config, access the attribute using the import variable, then use the attribute in the DefinePlugin.
const PACKAGE = require('../package.json');
const _version = PACKAGE.version;//Picks the version number from package.json
For example certain configuration on webpack.config is using METADATA for DefinePlugin:
const METADATA = webpackMerge(commonConfig({env: ENV}).metadata, {
host: HOST,
port: PORT,
ENV: ENV,
HMR: HMR,
RELEASE_VERSION:_version//Version attribute retrieved from package.json
});
new DefinePlugin({
'ENV': JSON.stringify(METADATA.ENV),
'HMR': METADATA.HMR,
'process.env': {
'ENV': JSON.stringify(METADATA.ENV),
'NODE_ENV': JSON.stringify(METADATA.ENV),
'HMR': METADATA.HMR,
'VERSION': JSON.stringify(METADATA.RELEASE_VERSION)//Setting it for the Scripts usage.
}
}),
Access this inside any typescript file:
this.versionNumber = process.env.VERSION;
The smartest way would be like this:
// webpack.config.js
plugins: [
new webpack.DefinePlugin({
VERSION: JSON.stringify(require("./package.json").version)
})
]
I have a use case where I have to iterate through the dict to get the key, value pair, also the index indicating where I am. This is how I do it:
d = {'x': 1, 'y': 2, 'z': 3}
for i, (key, value) in enumerate(d.items()):
print(i, key, value)
Note that the parentheses around the key, value are important, without them, you'd get an ValueError
"not enough values to unpack".
rowMeans
is nice, but if you are still trying to wrap your head around the apply
family of functions, this is a good opprotunity to begin understanding it.
DF['Mean'] <- apply(DF[,2:4], 1, mean)
Notice I'm doing a slightly different assignment than the first example. This approach makes it easier to incorporate it into for loops.
AnyObject
is the official way to use a weak reference in Swift.
class MyClass {
weak var delegate: MyClassDelegate?
}
protocol MyClassDelegate: AnyObject {
}
From Apple:
To prevent strong reference cycles, delegates should be declared as weak references. For more information about weak references, see Strong Reference Cycles Between Class Instances. Marking the protocol as class-only will later allow you to declare that the delegate must use a weak reference. You mark a protocol as being class-only by inheriting from AnyObject, as discussed in Class-Only Protocols.
I have a table which has about 120,000 records and need to select only those which does not exist (matched with a varchar column) in four other tables with number of rows approx 1500, 4000, 40000, 200. All the involved tables have unique index on the concerned Varchar
column.
NOT IN
took about 10 mins, NOT EXISTS
took 4 secs.
I have a recursive query which might had some untuned section which might have contributed to the 10 mins, but the other option taking 4 secs explains, atleast to me that NOT EXISTS
is far better or at least that IN
and EXISTS
are not exactly the same and always worth a check before going ahead with code.
CREATE TYPE dumyTable
AS TABLE
(
RateCodeId int,
RateLowerRange int,
RateHigherRange int,
RateRangeValue int
);
GO
CREATE PROCEDURE spInsertRateRanges
@dt AS dumyTable READONLY
AS
BEGIN
SET NOCOUNT ON;
INSERT tblRateCodeRange(RateCodeId,RateLowerRange,RateHigherRange,RateRangeValue)
SELECT *
FROM @dt
END
to answer to your second question - performance IS affected - if you are using those selectors with a single (no nested) ul:
<ul>
<li>jjj</li>
<li>jjj</li>
<li>jjj</li>
</ul>
the child selector ul > li
is more performant than ul li
because it is more specific. the browser traverse the dom "right to left", so when it finds a li
it then looks for a any ul
as a parent in the case of a child selector, while it has to traverse the whole dom tree to find any ul
ancestors in case of the descendant selector
I also hit this error. In my case the root cause was async related (during a codebase refactor): An asynchronous function that builds the object to which the "not a function" function belongs was not awaited, and the subsequent attempt to invoke the function throws the error, example below:
const car = carFactory.getCar();
car.drive() //throws TypeError: drive is not a function
The fix was:
const car = await carFactory.getCar();
car.drive()
Posting this incase it helps anyone else facing this error.
the following property must be added in the gradle.build file
processResources {
filesMatching("**/*.properties") {
expand project.properties
}
}
Additionally, if working with Intellij, the project must be re-imported.
You can export the data from MySQL to Excel by using this simple code.
<?php
include('db_con.php');
$stmt=$db_con->prepare('select * from books');
$stmt->execute();
$columnHeader ='';
$columnHeader = "Sr NO"."\t"."Book Name"."\t"."Book Author"."\t"."Book
ISBN"."\t";
$setData='';
while($rec =$stmt->FETCH(PDO::FETCH_ASSOC))
{
$rowData = '';
foreach($rec as $value)
{
$value = '"' . $value . '"' . "\t";
$rowData .= $value;
}
$setData .= trim($rowData)."\n";
}
header("Content-type: application/octet-stream");
header("Content-Disposition: attachment; filename=Book record
sheet.xls");
header("Pragma: no-cache");
header("Expires: 0");
echo ucwords($columnHeader)."\n".$setData."\n";
?>
complete code here php export to excel
use linq
from c in Customers
group c by DbFunctions.TruncateTime(c.CreateTime) into date
orderby date.Key descending
select new
{
Value = date.Count().ToString(),
Name = date.Key.ToString().Substring(0, 10)
}
How about converting to lowercase first? you can use string.lower()
.
git diff `git merge-base master branch`..branch
Merge base is the point where branch
diverged from master
.
Git diff supports a special syntax for this:
git diff master...branch
You must not swap the sides because then you would get the other branch. You want to know what changed in branch
since it diverged from master
, not the other way round.
Loosely related:
Note that ..
and ...
syntax does not have the same semantics as in other Git tools. It differs from the meaning specified in man gitrevisions
.
Quoting man git-diff
:
git diff [--options] <commit> <commit> [--] [<path>…]
This is to view the changes between two arbitrary
<commit>
.
git diff [--options] <commit>..<commit> [--] [<path>…]
This is synonymous to the previous form. If
<commit>
on one side is omitted, it will have the same effect as usingHEAD
instead.
git diff [--options] <commit>...<commit> [--] [<path>…]
This form is to view the changes on the branch containing and up to the second
<commit>
, starting at a common ancestor of both<commit>
. "git diff A...B
" is equivalent to "git diff $(git-merge-base A B) B
". You can omit any one of<commit>
, which has the same effect as usingHEAD
instead.Just in case you are doing something exotic, it should be noted that all of the
<commit>
in the above description, except in the last two forms that use ".." notations, can be any<tree>
.For a more complete list of ways to spell
<commit>
, see "SPECIFYING REVISIONS" section ingitrevisions[7]
. However, "diff" is about comparing two endpoints, not ranges, and the range notations ("<commit>..<commit>
" and "<commit>...<commit>
") do not mean a range as defined in the "SPECIFYING RANGES" section ingitrevisions[7]
.
The simplest way is create a static folder inside the main project folder. Static folder containing .css files.
main folder
/Main Folder
/Main Folder/templates/foo.html
/Main Folder/static/foo.css
/Main Folder/application.py(flask script)
Image of main folder containing static and templates folders and flask script
flask
from flask import Flask, render_template
app = Flask(__name__)
@app.route("/")
def login():
return render_template("login.html")
html (layout)
<!DOCTYPE html>
<html>
<head>
<title>Project(1)</title>
<link rel="stylesheet" href="/static/styles.css">
</head>
<body>
<header>
<div class="container">
<nav>
<a class="title" href="">Kamook</a>
<a class="text" href="">Sign Up</a>
<a class="text" href="">Log In</a>
</nav>
</div>
</header>
{% block body %}
{% endblock %}
</body>
</html>
html
{% extends "layout.html" %}
{% block body %}
<div class="col">
<input type="text" name="username" placeholder="Username" required>
<input type="password" name="password" placeholder="Password" required>
<input type="submit" value="Login">
</div>
{% endblock %}
As a last resort, if all other suggestions fail, then backup all your data and do a factory reset.
You can ignore the peer dependency warnings by using the --force flag with Angular cli when updating dependencies.
ng update @angular/cli @angular/core --force
For a full list of options, check the docs: https://angular.io/cli/update
also you should click right button on mouse at your projectname and choose "open module settings" or press F4 button. Then on "dependencies" tab add your lib.jar to declare needed lib
You will need the child to store the parents this variable. As the Parent is the only object that has access to it's this variable it will also need a function that places the this variable into the child's that variable, something like this.
var Parent = {
Child : {
that : {},
},
init : function(){
this.Child.that = this;
}
}
To test this out try to run this in Firefox's Scratchpad, it worked for me.
var Parent = {
data : "Parent Data",
Child : {
that : {},
data : "Child Data",
display : function(){
console.log(this.data);
console.log(this.that.data);
}
},
init : function(){
this.Child.that = this;
}
}
Parent.init();
Parent.Child.display();
REPEAT
...
UNTIL cond
Is equivalent to
while True:
...
if cond:
break
I have two demos, one with jQuery
and one without. Neither use date functions and are about as simple as it gets.
function startTimer(duration, display) {_x000D_
var timer = duration, minutes, seconds;_x000D_
setInterval(function () {_x000D_
minutes = parseInt(timer / 60, 10);_x000D_
seconds = parseInt(timer % 60, 10);_x000D_
_x000D_
minutes = minutes < 10 ? "0" + minutes : minutes;_x000D_
seconds = seconds < 10 ? "0" + seconds : seconds;_x000D_
_x000D_
display.textContent = minutes + ":" + seconds;_x000D_
_x000D_
if (--timer < 0) {_x000D_
timer = duration;_x000D_
}_x000D_
}, 1000);_x000D_
}_x000D_
_x000D_
window.onload = function () {_x000D_
var fiveMinutes = 60 * 5,_x000D_
display = document.querySelector('#time');_x000D_
startTimer(fiveMinutes, display);_x000D_
};
_x000D_
<body>_x000D_
<div>Registration closes in <span id="time">05:00</span> minutes!</div>_x000D_
</body>
_x000D_
function startTimer(duration, display) {
var timer = duration, minutes, seconds;
setInterval(function () {
minutes = parseInt(timer / 60, 10);
seconds = parseInt(timer % 60, 10);
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
display.text(minutes + ":" + seconds);
if (--timer < 0) {
timer = duration;
}
}, 1000);
}
jQuery(function ($) {
var fiveMinutes = 60 * 5,
display = $('#time');
startTimer(fiveMinutes, display);
});
However if you want a more accurate timer that is only slightly more complicated:
function startTimer(duration, display) {_x000D_
var start = Date.now(),_x000D_
diff,_x000D_
minutes,_x000D_
seconds;_x000D_
function timer() {_x000D_
// get the number of seconds that have elapsed since _x000D_
// startTimer() was called_x000D_
diff = duration - (((Date.now() - start) / 1000) | 0);_x000D_
_x000D_
// does the same job as parseInt truncates the float_x000D_
minutes = (diff / 60) | 0;_x000D_
seconds = (diff % 60) | 0;_x000D_
_x000D_
minutes = minutes < 10 ? "0" + minutes : minutes;_x000D_
seconds = seconds < 10 ? "0" + seconds : seconds;_x000D_
_x000D_
display.textContent = minutes + ":" + seconds; _x000D_
_x000D_
if (diff <= 0) {_x000D_
// add one second so that the count down starts at the full duration_x000D_
// example 05:00 not 04:59_x000D_
start = Date.now() + 1000;_x000D_
}_x000D_
};_x000D_
// we don't want to wait a full second before the timer starts_x000D_
timer();_x000D_
setInterval(timer, 1000);_x000D_
}_x000D_
_x000D_
window.onload = function () {_x000D_
var fiveMinutes = 60 * 5,_x000D_
display = document.querySelector('#time');_x000D_
startTimer(fiveMinutes, display);_x000D_
};
_x000D_
<body>_x000D_
<div>Registration closes in <span id="time"></span> minutes!</div>_x000D_
</body>
_x000D_
Now that we have made a few pretty simple timers we can start to think about re-usability and separating concerns. We can do this by asking "what should a count down timer do?"
So with these things in mind lets write a better (but still very simple) CountDownTimer
function CountDownTimer(duration, granularity) {
this.duration = duration;
this.granularity = granularity || 1000;
this.tickFtns = [];
this.running = false;
}
CountDownTimer.prototype.start = function() {
if (this.running) {
return;
}
this.running = true;
var start = Date.now(),
that = this,
diff, obj;
(function timer() {
diff = that.duration - (((Date.now() - start) / 1000) | 0);
if (diff > 0) {
setTimeout(timer, that.granularity);
} else {
diff = 0;
that.running = false;
}
obj = CountDownTimer.parse(diff);
that.tickFtns.forEach(function(ftn) {
ftn.call(this, obj.minutes, obj.seconds);
}, that);
}());
};
CountDownTimer.prototype.onTick = function(ftn) {
if (typeof ftn === 'function') {
this.tickFtns.push(ftn);
}
return this;
};
CountDownTimer.prototype.expired = function() {
return !this.running;
};
CountDownTimer.parse = function(seconds) {
return {
'minutes': (seconds / 60) | 0,
'seconds': (seconds % 60) | 0
};
};
So why is this implementation better than the others? Here are some examples of what you can do with it. Note that all but the first example can't be achieved by the startTimer
functions.
An example that displays the time in XX:XX format and restarts after reaching 00:00
An example that displays the time in two different formats
An example that has two different timers and only one restarts
An example that starts the count down timer when a button is pressed
This is a JQuery-free version of the answer provided by raphadko and noun.
1) Create your recaptcha fields normally with this:
<div class="g-recaptcha"></div>
2) Load the script with this:
<script src="https://www.google.com/recaptcha/api.js?onload=CaptchaCallback&render=explicit" async defer></script>
3) Now call this to iterate over the fields and create the recaptchas:
var CaptchaCallback = function() {
var captchas = document.getElementsByClassName("g-recaptcha");
for(var i = 0; i < captchas.length; i++) {
grecaptcha.render(captchas[i], {'sitekey' : 'YOUR_KEY_HERE'});
}
};
You can use window.open to open a new window/tab(according to browser setting) in javascript.
By using document.write you can write HTML content to the opened window.
Inside a module
Option Explicit
dim objExcelApp as Excel.Application
dim wb as Excel.Workbook
sub Initialize()
set objExcelApp = new Excel.Application
end sub
sub ProcessDataWorkbook()
dim ws as Worksheet
set wb = objExcelApp.Workbooks.Open("path to my workbook")
set ws = wb.Sheets(1)
ws.Cells(1,1).Value = "Hello"
ws.Cells(1,2).Value = "World"
'Close the workbook
wb.Close
set wb = Nothing
end sub
sub Release()
set objExcelApp = Nothing
end sub
To see your log in SQL Developer
then press:
CTRL+SHIFT + L (or CTRL + CMD + L on macOS)
or
View -> Log
or by using mysql query
show errors;
Here is another trick. Use a generic vararg array
import java.util.ArrayList;
class TypedArrayList<E> extends ArrayList<E>
{
@SafeVarargs
public TypedArrayList (E... typeInfo)
{
// Get generic type at runtime ...
System.out.println (typeInfo.getClass().getComponentType().getTypeName());
}
}
public class GenericTest
{
public static void main (String[] args)
{
// No need to supply the dummy argument
ArrayList<Integer> ar1 = new TypedArrayList<> ();
ArrayList<String> ar2 = new TypedArrayList<> ();
ArrayList<?> ar3 = new TypedArrayList<> ();
}
}
Map#merge
As of java-8 you can use Map#merge(K key, V value, BiFunction remappingFunction)
which merges a value into the Map
using remappingFunction
in case the key is already found in the Map
you want to put the pair into.
// using lambda
newMap.forEach((key, value) -> map.merge(key, value, (oldValue, newValue) -> oldValue));
// using for-loop
for (Map.Entry<Integer, String> entry: newMap.entrySet()) {
map.merge(entry.getKey(), entry.getValue(), (oldValue, newValue) -> oldValue);
}
The code iterates the newMap
entries (key
and value
) and each one is merged into map
through the method merge
. The remappingFunction
is triggered in case of duplicated key and in that case it says that the former (original) oldValue
value will be used and not rewritten.
With this solution, you don't need a temporary Map
.
Let's have an example of merging newMap
entries into map
and keeping the original values in case of the duplicated antry.
Map<Integer, String> newMap = new HashMap<>();
newMap.put(2, "EVIL VALUE"); // this will NOT be merged into
newMap.put(4, "four"); // this WILL be merged into
newMap.put(5, "five"); // this WILL be merged into
Map<Integer, String> map = new HashMap<>();
map.put(1, "one");
map.put(2, "two");
map.put(3, "three");
newMap.forEach((k, v) -> map.merge(k, v, (oldValue, newValue) -> oldValue));
map.forEach((k, v) -> System.out.println(k + " " + v));
1 one 2 two 3 three 4 four 5 five
Are you using php 5.4 on your local? the render line is using the new way of initializing arrays. Try replacing ["title" => "Welcome "]
with array("title" => "Welcome ")
If you are using .NET 4.0 you can use a Tuple
.
List<Tuple<T1, T2>> list;
For older versions of .NET you have to create a custom class (unless you are lucky enough to be able to find a class that fits your needs in the base class library).
@Test
public void testToStringToMap() {
Map<String,String> expected = new HashMap<>();
expected.put("first_name", "naresh");
expected.put("last_name", "kumar");
expected.put("gender", "male");
String mapString = expected.toString();
Map<String, String> actual = Arrays.stream(mapString.replace("{", "").replace("}", "").split(","))
.map(arrayData-> arrayData.split("="))
.collect(Collectors.toMap(d-> ((String)d[0]).trim(), d-> (String)d[1]));
expected.entrySet().stream().forEach(e->assertTrue(actual.get(e.getKey()).equals(e.getValue())));
}
For Windows (7), the same folder is located at,
%APPDATA%\Subversion\auth
Type in the above in the Run(Win key + R) dialog box and hit Enter,
To check the existing username open the below file as a text file,
%APPDATA%\Subversion\auth\svn.simple\xxxxxxxxxx
A slight more difficult answer that uses ControlTemplate and has an animation effect (adapted from https://docs.microsoft.com/en-us/dotnet/framework/wpf/controls/customizing-the-appearance-of-an-existing-control)
In your resource dictionary define a control template for your button like this one:
<ControlTemplate TargetType="Button" x:Key="testButtonTemplate2">
<Border Name="RootElement">
<Border.Background>
<SolidColorBrush x:Name="BorderBrush" Color="Black"/>
</Border.Background>
<Grid Margin="4" >
<Grid.Background>
<SolidColorBrush x:Name="ButtonBackground" Color="Aquamarine"/>
</Grid.Background>
<ContentPresenter HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" VerticalAlignment="{TemplateBinding VerticalContentAlignment}" Margin="4,5,4,4"/>
</Grid>
<VisualStateManager.VisualStateGroups>
<VisualStateGroup x:Name="CommonStates">
<VisualState x:Name="Normal"/>
<VisualState x:Name="MouseOver">
<Storyboard>
<ColorAnimation Storyboard.TargetName="ButtonBackground" Storyboard.TargetProperty="Color" To="Red"/>
</Storyboard>
</VisualState>
<VisualState x:Name="Pressed">
<Storyboard>
<ColorAnimation Storyboard.TargetName="ButtonBackground" Storyboard.TargetProperty="Color" To="Red"/>
</Storyboard>
</VisualState>
</VisualStateGroup>
</VisualStateManager.VisualStateGroups>
</Border>
</ControlTemplate>
in your XAML you can use the template above for your button as below:
Define your button
<Button Template="{StaticResource testButtonTemplate2}"
HorizontalAlignment="Center" VerticalAlignment="Center"
Foreground="White">My button</Button>
Hope it helps
My answer is a total hack- I just created a link that looks like a button and add the URL to that.
<a class="el-button"
style="color: white; background-color: #58B7FF;"
:href="<YOUR URL ENDPOINT HERE>"
:download="<FILE NAME NERE>">
<i class="fa fa-file-excel-o"></i> Excel
</a>
I'm using the excellent VueJs hence the odd anotations, however, this solution is framework agnostic. The idea would work for any HTML based design.
Unicode is a standard which maps the characters in all languages to a particular numeric value called Code Points. The reason it does this is that it allows different encodings to be possible using the same set of code points.
UTF-8 and UTF-16 are two such encodings. They take code points as input and encodes them using some well-defined formula to produce the encoded string.
Choosing a particular encoding depends upon your requirements. Different encodings have different memory requirements and depending upon the characters that you will be dealing with, you should choose the encoding which uses the least sequences of bytes to encode those characters.
For more in-depth details about Unicode, UTF-8 and UTF-16, you can check out this article,
select a.ip, a.os, a.hostname, a.port, a.protocol,
b.state
from a
left join b on a.ip = b.ip
and a.port = b.port
You don't need the count, just whether or not the item was seen before. Adapted that answer to this problem:
def list_duplicates(seq):
seen = set()
seen_add = seen.add
# adds all elements it doesn't know yet to seen and all other to seen_twice
seen_twice = set( x for x in seq if x in seen or seen_add(x) )
# turn the set into a list (as requested)
return list( seen_twice )
a = [1,2,3,2,1,5,6,5,5,5]
list_duplicates(a) # yields [1, 2, 5]
Just in case speed matters, here are some timings:
# file: test.py
import collections
def thg435(l):
return [x for x, y in collections.Counter(l).items() if y > 1]
def moooeeeep(l):
seen = set()
seen_add = seen.add
# adds all elements it doesn't know yet to seen and all other to seen_twice
seen_twice = set( x for x in l if x in seen or seen_add(x) )
# turn the set into a list (as requested)
return list( seen_twice )
def RiteshKumar(l):
return list(set([x for x in l if l.count(x) > 1]))
def JohnLaRooy(L):
seen = set()
seen2 = set()
seen_add = seen.add
seen2_add = seen2.add
for item in L:
if item in seen:
seen2_add(item)
else:
seen_add(item)
return list(seen2)
l = [1,2,3,2,1,5,6,5,5,5]*100
Here are the results: (well done @JohnLaRooy!)
$ python -mtimeit -s 'import test' 'test.JohnLaRooy(test.l)'
10000 loops, best of 3: 74.6 usec per loop
$ python -mtimeit -s 'import test' 'test.moooeeeep(test.l)'
10000 loops, best of 3: 91.3 usec per loop
$ python -mtimeit -s 'import test' 'test.thg435(test.l)'
1000 loops, best of 3: 266 usec per loop
$ python -mtimeit -s 'import test' 'test.RiteshKumar(test.l)'
100 loops, best of 3: 8.35 msec per loop
Interestingly, besides the timings itself, also the ranking slightly changes when pypy is used. Most interestingly, the Counter-based approach benefits hugely from pypy's optimizations, whereas the method caching approach I have suggested seems to have almost no effect.
$ pypy -mtimeit -s 'import test' 'test.JohnLaRooy(test.l)'
100000 loops, best of 3: 17.8 usec per loop
$ pypy -mtimeit -s 'import test' 'test.thg435(test.l)'
10000 loops, best of 3: 23 usec per loop
$ pypy -mtimeit -s 'import test' 'test.moooeeeep(test.l)'
10000 loops, best of 3: 39.3 usec per loop
Apparantly this effect is related to the "duplicatedness" of the input data. I have set l = [random.randrange(1000000) for i in xrange(10000)]
and got these results:
$ pypy -mtimeit -s 'import test' 'test.moooeeeep(test.l)'
1000 loops, best of 3: 495 usec per loop
$ pypy -mtimeit -s 'import test' 'test.JohnLaRooy(test.l)'
1000 loops, best of 3: 499 usec per loop
$ pypy -mtimeit -s 'import test' 'test.thg435(test.l)'
1000 loops, best of 3: 1.68 msec per loop
I manage to apply gradient border using this code..
public static Bitmap drawShadow(Bitmap bitmap, int leftRightThk, int bottomThk, int padTop) {
int w = bitmap.getWidth();
int h = bitmap.getHeight();
int newW = w - (leftRightThk * 2);
int newH = h - (bottomThk + padTop);
Bitmap.Config conf = Bitmap.Config.ARGB_8888;
Bitmap bmp = Bitmap.createBitmap(w, h, conf);
Bitmap sbmp = Bitmap.createScaledBitmap(bitmap, newW, newH, false);
Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
Canvas c = new Canvas(bmp);
// Left
int leftMargin = (leftRightThk + 7)/2;
Shader lshader = new LinearGradient(0, 0, leftMargin, 0, Color.TRANSPARENT, Color.BLACK, TileMode.CLAMP);
paint.setShader(lshader);
c.drawRect(0, padTop, leftMargin, newH, paint);
// Right
Shader rshader = new LinearGradient(w - leftMargin, 0, w, 0, Color.BLACK, Color.TRANSPARENT, TileMode.CLAMP);
paint.setShader(rshader);
c.drawRect(newW, padTop, w, newH, paint);
// Bottom
Shader bshader = new LinearGradient(0, newH, 0, bitmap.getHeight(), Color.BLACK, Color.TRANSPARENT, TileMode.CLAMP);
paint.setShader(bshader);
c.drawRect(leftMargin -3, newH, newW + leftMargin + 3, bitmap.getHeight(), paint);
c.drawBitmap(sbmp, leftRightThk, 0, null);
return bmp;
}
hope this helps !
It is true that a typical IPv4 header is 20 bytes, and the UDP header is 8 bytes. However it is possible to include IP options which can increase the size of the IP header to as much as 60 bytes. In addition, sometimes it is necessary for intermediate nodes to encapsulate datagrams inside of another protocol such as IPsec (used for VPNs and the like) in order to route the packet to its destination. So if you do not know the MTU on your particular network path, it is best to leave a reasonable margin for other header information that you may not have anticipated. A 512-byte UDP payload is generally considered to do that, although even that does not leave quite enough space for a maximum size IP header.
I have a library that is doing exactly you need.
Some time ago I had wrote simple and fast enough library for work with CSV files. You can find it by the following link: https://github.com/ukushu/DataExporter
It works with CSV like with 2 dimensions array. Exactly like you need.
As example, in case of you need all of values of 3rd row only you need is to write:
Csv csv = new Csv();
csv.FileOpen("c:\\file1.csv");
var allValuesOf3rdRow = csv.Rows[2];
or to read 2nd cell of
var value = csv.Rows[2][1];
Another solution :
create the SSH keys, type ssh-keygen -t rsa -C "[email protected]"
. This will create both id_rsa and id_rsa.pub files.
Add the id_rsa to ssh list on local computer: ssh-add ~/.ssh/id_rsa.
After generating the keys get the pubkey using :
cat ~/.ssh/id_rsa.pub
you will get something like :
cat ~/.ssh/id_rsa.pub
ssh-rsa AAAB3NzaC1yc2EAAAADAQABAAACAQCvMzmFEUPvaA1AFEBH6zGIF3N6pVE2SJv9V1MHgEwk4C7xovdk7Lr4LDoqEcqxgeJftwWQWWVrWWf7q9qCdHTAanH2Q5vx5nZjLB+B7saksehVOPWDR/MOSpVcr5bwIjf8dc8u5S8h24uBlguGkX+4lFJ+zwhiuwJlhykMvs5py1gD2hy+hvOs1Y17JPWhVVesGV3tlmtbfVolEiv9KShgkk3Hq56fyl+QmPzX1jya4TIC3k55FTzwRWBd+IpblbrGlrIBS6hvpHQpgUs47nSHLEHTn0Xmn6Q== [email protected]
copy this key (value) and go to github.com and under the setting (ssh and pgp key) add your public key.
There are several causes for this error.
wait_timeout
- Time in seconds that the server waits for a connection to become active before closing it.interactive_timeout
- Time in seconds that the server waits for an interactive connection.max_allowed_packet
- Maximum size in bytes of a packet or a generated/intermediate string. Set as large as the largest BLOB, in multiples of 1024.Example of my.cnf:
[mysqld]
# 8 hours
wait_timeout = 28800
# 8 hours
interactive_timeout = 28800
max_allowed_packet = 256M
free -h
CONN_MAX_AGE
(see docs)SHOW VARIABLES LIKE '%time%';
mysqladmin variables
log_warnings = 4
log_error_verbosity = 3
The documentation for css() says that setting the style property to the empty string will remove that property if it does not reside in a stylesheet:
Setting the value of a style property to an empty string — e.g.
$('#mydiv').css('color', '')
— removes that property from an element if it has already been directly applied, whether in the HTML style attribute, through jQuery's.css()
method, or through direct DOM manipulation of the style property. It does not, however, remove a style that has been applied with a CSS rule in a stylesheet or<style>
element.
Since your styles are inline, you can write:
$(selector).css("-moz-user-select", "");
For a system-agnostic solution that works on both Windows and Linux, no matter what the input path, one could use os.path.join(os.sep, rootdir + os.sep, targetdir)
On WIndows:
>>> os.path.join(os.sep, "C:" + os.sep, "Windows")
'C:\\Windows'
On Linux:
>>> os.path.join(os.sep, "usr" + os.sep, "lib")
'/usr/lib'
This might not be a popular option, but sometimes the scripts end up being distributed in various chunks, in that case I've found this to be a quick fix
if(window.onload != null){var f1 = window.onload;}
window.onload=function(){
//do something
if(f1!=null){f1();}
}
then somewhere else...
if(window.onload != null){var f2 = window.onload;}
window.onload=function(){
//do something else
if(f2!=null){f2();}
}
this will update the onload function and chain as needed
Try grabbing the path using:
document.location.pathname
In Javascript you can the current URL in parts. Check out: https://css-tricks.com/snippets/javascript/get-url-and-url-parts-in-javascript/
I would really recommend to:
push only to the main repo
make sure that main repo is a bare repo, in order to never have any problem with the main repo working tree being not in sync with its .git
base. See "How to push a local git repository to another computer?"
If you do have to make modification in the main (bare) repo, clone it (on the main server), do your modification and push back to it
In other words, keep a bare repo accessible both from the main server and the local computer, in order to have a single upstream repo from/to which to pull/pull.
If you want to do it with multiline/multiple command/s then you can do this:
output=$( bash <<EOF
# Multiline/multiple command/s
EOF
)
Or:
output=$(
# Multiline/multiple command/s
)
Example:
#!/bin/bash
output="$( bash <<EOF
echo first
echo second
echo third
EOF
)"
echo "$output"
Output:
first
second
third
Using heredoc, you can simplify things pretty easily by breaking down your long single line code into a multiline one. Another example:
output="$( ssh -p $port $user@$domain <<EOF
# Breakdown your long ssh command into multiline here.
EOF
)"
For the future googlers: use RingtoneManager.getActualDefaultRingtoneUri()
instead of RingtoneManager.getDefaultUri()
. According to its name, it would return the actual uri, so you can freely use it. From documentation of getActualDefaultRingtoneUri()
:
Gets the current default sound's Uri. This will give the actual sound Uri, instead of using this, most clients can use DEFAULT_RINGTONE_URI.
Meanwhile getDefaultUri()
says this:
Returns the Uri for the default ringtone of a particular type. Rather than returning the actual ringtone's sound Uri, this will return the symbolic Uri which will resolved to the actual sound when played.
Support, unfortunately, is brutal at best. Here's a post on the topic:
https://www.campaignmonitor.com/blog/email-marketing/2013/02/embedded-images-in-html-email/
And the post content:
You cannot assign arrays to copy them. How you can copy the contents of one into another depends on multiple factors:
For char
arrays, if you know the source array is null terminated and destination array is large enough for the string in the source array, including the null terminator, use strcpy()
:
#include <string.h>
char array1[18] = "abcdefg";
char array2[18];
...
strcpy(array2, array1);
If you do not know if the destination array is large enough, but the source is a C string, and you want the destination to be a proper C string, use snprinf()
:
#include <stdio.h>
char array1[] = "a longer string that might not fit";
char array2[18];
...
snprintf(array2, sizeof array2, "%s", array1);
If the source array is not necessarily null terminated, but you know both arrays have the same size, you can use memcpy
:
#include <string.h>
char array1[28] = "a non null terminated string";
char array2[28];
...
memcpy(array2, array1, sizeof array2);
I think most easy way is using Subject. In bellow example code the child will be notified each time 'tellChild' is called.
Parent.component.ts
import {Subject} from 'rxjs/Subject';
...
export class ParentComp {
changingValue: Subject<boolean> = new Subject();
tellChild(){
this.changingValue.next(true);
}
}
Parent.component.html
<my-comp [changing]="changingValue"></my-comp>
Child.component.ts
...
export class ChildComp implements OnInit{
@Input() changing: Subject<boolean>;
ngOnInit(){
this.changing.subscribe(v => {
console.log('value is changing', v);
});
}
Working sample on Stackblitz
Yes. For example you can use the solution by https://grabz.it.
It's got a Javascript API which can be used in different ways to grab and manipulate the screenshot. In order to use it in your app you will need to first get an app key and secret and download the free Javascript SDK.
So, let's see a simple example for using it:
//first include the grabzit.min.js library in the web page
<script src="grabzit.min.js"></script>
//include the code below to add the screenshot to the body tag
<script>
//use secret key to sign in. replace the url.
GrabzIt("Sign in to view your Application Key").ConvertURL("http://www.google.com").Create();
</script>
Then simply wait a short while and the image will automatically appear at the bottom of the page, without you needing to reload the page.
That's the simplest one. For more examples with image manipulation, attaching screenshots to elements and etc check the documentation.
I would say the simplest solution would be to wrap the object and delegate the contains call to a collection of the wrapped class. This is similar to the comparator but doesn't force you to sort the resulting collection, you can simply use ArrayList.contains().
public class Widget {
private String name;
private String desc;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
}
public abstract class EqualsHashcodeEnforcer<T> {
protected T wrapped;
public T getWrappedObject() {
return wrapped;
}
@Override
public boolean equals(Object obj) {
return equalsDelegate(obj);
}
@Override
public int hashCode() {
return hashCodeDelegate();
}
protected abstract boolean equalsDelegate(Object obj);
protected abstract int hashCodeDelegate();
}
public class WrappedWidget extends EqualsHashcodeEnforcer<Widget> {
@Override
protected boolean equalsDelegate(Object obj) {
if (obj == null) {
return false;
}
if (obj == getWrappedObject()) {
return true;
}
if (obj.getClass() != getWrappedObject().getClass()) {
return false;
}
Widget rhs = (Widget) obj;
return new EqualsBuilder().append(getWrappedObject().getName(),
rhs.getName()).append(getWrappedObject().getDesc(),
rhs.getDesc()).isEquals();
}
@Override
protected int hashCodeDelegate() {
return new HashCodeBuilder(121, 991).append(
getWrappedObject().getName()).append(
getWrappedObject().getDesc()).toHashCode();
}
}
I just wanted to illustrate that the built-in solutions (SQL-only) are not always the best ones. At first I thought that because Django's QuerySet.objects.order_by
method accepts multiple arguments, you could easily chain them:
ordered_authors = Author.objects.order_by('-score', 'last_name')[:30]
But, it does not work as you would expect. Case in point, first is a list of presidents sorted by score (selecting top 5 for easier reading):
>>> auths = Author.objects.order_by('-score')[:5]
>>> for x in auths: print x
...
James Monroe (487)
Ulysses Simpson (474)
Harry Truman (471)
Benjamin Harrison (467)
Gerald Rudolph (464)
Using Alex Martelli's solution which accurately provides the top 5 people sorted by last_name
:
>>> for x in sorted(auths, key=operator.attrgetter('last_name')): print x
...
Benjamin Harrison (467)
James Monroe (487)
Gerald Rudolph (464)
Ulysses Simpson (474)
Harry Truman (471)
And now the combined order_by
call:
>>> myauths = Author.objects.order_by('-score', 'last_name')[:5]
>>> for x in myauths: print x
...
James Monroe (487)
Ulysses Simpson (474)
Harry Truman (471)
Benjamin Harrison (467)
Gerald Rudolph (464)
As you can see it is the same result as the first one, meaning it doesn't work as you would expect.
One of your tables has the same column name's which brings a confusion in the query as to which columns of the tables are you referring to. Copy this code and run it.
SELECT
v.VendorName, i.InvoiceID, iL.InvoiceSequence, iL.InvoiceLineItemAmount
FROM Vendors AS v
JOIN Invoices AS i ON (v.VendorID = .VendorID)
JOIN InvoiceLineItems AS iL ON (i.InvoiceID = iL.InvoiceID)
WHERE
I.InvoiceID IN
(SELECT iL.InvoiceSequence
FROM InvoiceLineItems
WHERE iL.InvoiceSequence > 1)
ORDER BY
V.VendorName, i.InvoiceID, iL.InvoiceSequence, iL.InvoiceLineItemAmount
There can be many possible reasons for this failure.
Some are listed above. I faced the same issue, it is very hard to find the root cause of the failure.
I will recommend you to check the session timeout for shh from ssh_config file. Try to increase the session timeout and see if it fails again
How does [HttpContext.Current.User] know which usernames exist or do not exist?
Let's look at an example of one way this works. Suppose you are using Forms Authentication and the "OnAuthenticate" event fires. This event occurs "when the application authenticates the current request" (Reference Source).
Up until this point, the application has no idea who you are.
Since you are using Forms Authentication, it first checks by parsing the authentication cookie (usually .ASPAUTH) via a call to ExtractTicketFromCookie
. This calls FormsAuthentication.Decrypt
(This method is public; you can call this yourself!). Next, it calls Context.SetPrincipalNoDemand
, turning the cookie into a user and stuffing it into Context.User
(Reference Source).
You need to use the ui.item.label (the text) and ui.item.value (the id) properties
$('#selector').autocomplete({
source: url,
select: function (event, ui) {
$("#txtAllowSearch").val(ui.item.label); // display the selected text
$("#txtAllowSearchID").val(ui.item.value); // save selected id to hidden input
}
});
$('#button').click(function() {
alert($("#txtAllowSearchID").val()); // get the id from the hidden input
});
[Edit] You also asked how to create the multi-dimensional array...
You should be able create the array like so:
var $local_source = [[0,"c++"], [1,"java"], [2,"php"], [3,"coldfusion"],
[4,"javascript"], [5,"asp"], [6,"ruby"]];
Read more about how to work with multi-dimensional arrays here: http://www.javascriptkit.com/javatutors/literal-notation2.shtml
Adding on to what Hubro said, apparently get_highest_row()
has been deprecated. Using the max_row
and max_column
properties returns the row and column count. For example:
wb = load_workbook(path, use_iterators=True)
sheet = wb.worksheets[0]
row_count = sheet.max_row
column_count = sheet.max_column
The compiler cannot tell from that code if the function will ever reach the end and still return something. To make that clear, replace the last else if(...)
with just else
.
var max_date = dates.sort(function(d1, d2){
return d2-d1;
})[0];
Actually in Eclipse Indigo thru Oxygen, you have to go to the Types template Window -> Preferences -> Java -> Code Style -> Code templates -> (in right-hand pane) Comments -> double-click Types
and make sure it has the following, which it should have by default:
/**
* @author ${user}
*
* ${tags}
*/
and as far as I can tell, there is nothing in Eclipse to add the javadoc automatically to existing files in one batch. You could easily do it from the command line with sed
& awk
but that's another question.
If you are prepared to open each file individually, then selected the class / interface declaration line, e.g. public class AdamsClass { and then hit the key combo Shift + Alt + J and that will insert a new javadoc comment above, along with the author tag for your user. To experiment with other settings, go to Windows->Preferences->Java->Editor->Templates
.
For Apache HttpClient 4.5+ & Java8:
SSLContext sslContext = SSLContexts.custom()
.loadTrustMaterial((chain, authType) -> true).build();
SSLConnectionSocketFactory sslConnectionSocketFactory =
new SSLConnectionSocketFactory(sslContext, new String[]
{"SSLv2Hello", "SSLv3", "TLSv1","TLSv1.1", "TLSv1.2" }, null,
NoopHostnameVerifier.INSTANCE);
CloseableHttpClient client = HttpClients.custom()
.setSSLSocketFactory(sslConnectionSocketFactory)
.build();
But if your HttpClient use a ConnectionManager for seeking connection, e.g. like this:
PoolingHttpClientConnectionManager connectionManager = new
PoolingHttpClientConnectionManager();
CloseableHttpClient client = HttpClients.custom()
.setConnectionManager(connectionManager)
.build();
The HttpClients.custom().setSSLSocketFactory(sslConnectionSocketFactory)
has no effect, the problem is not resolved.
Because that the HttpClient use the specified connectionManager for seeking connection and the specified connectionManager haven't register our customized SSLConnectionSocketFactory. To resolve this, should register the The customized SSLConnectionSocketFactory in the connectionManager. The correct code should like this:
PoolingHttpClientConnectionManager connectionManager = new
PoolingHttpClientConnectionManager(RegistryBuilder.
<ConnectionSocketFactory>create()
.register("http",PlainConnectionSocketFactory.getSocketFactory())
.register("https", sslConnectionSocketFactory).build());
CloseableHttpClient client = HttpClients.custom()
.setConnectionManager(connectionManager)
.build();
var text = "Ann@26"
var editedText = text.Replace("@", "\t");
A concise way to do this is:
Map<Character,Integer> frequencies = new HashMap<>();
for (char ch : input.toCharArray())
frequencies.put(ch, frequencies.getOrDefault(ch, 0) + 1);
We use a for-each to loop through every character. The frequencies.getOrDefault()
gets value if key is present or returns(as default) its second argument.
My table had somehow been renamed to ' Customers'
i.e. with a leading space
This meant
a) queries broke
b) the table didn't appear where expected in the alphabetical order of my tables, which in my panic meant I couldn't see it!
RENAME TABLE ` Customer` TO `Customer`;
I had something similar this evening which was driving me batty. Submitting a form was giving me the values in $_REQUEST but not in $_POST.
Eventually I noticed that there were actually two requests going through on the network tab in firebug; first a POST with a 301 response, then a GET with a 200 response.
Hunting about the interwebs it sounded like most people thought this was to do with mod_rewrite causing the POST request to redirect and thus change to a GET.
In my case it wasn't mod_rewrite to blame, it was something far simpler... my URL for the POST also contained a GET query string which was starting without a trailing slash on the URL. It was this causing apache to redirect.
Spot the difference...
Bad: http://blah.de.blah/my/path?key=value&otherkey=othervalue
Good: http://blah.de.blah/my/path/?key=value&otherkey=othervalue
The bottom one doesn't cause a redirect and gives me $_POST!
If I need only to highlight the first word as a command, I often use properties
:
```properties
npm run build
```
I obtain something like:
npm run build
rm -rf
was much more performant than FileUtils.cleanDirectory
.Not a one-liner solution but after extensive benchmarking, we found that using rm -rf
was multiple times faster than using FileUtils.cleanDirectory
.
Of course, if you have a small or simple directory, it won't matter but in our case we had multiple gigabytes and deeply nested sub directories where it would take over 10 minutes with FileUtils.cleanDirectory
and only 1 minute with rm -rf
.
Here's our rough Java implementation to do that:
// Delete directory given and all subdirectories and files (i.e. recursively).
//
static public boolean clearDirectory( File file ) throws IOException, InterruptedException {
if ( file.exists() ) {
String deleteCommand = "rm -rf " + file.getAbsolutePath();
Runtime runtime = Runtime.getRuntime();
Process process = runtime.exec( deleteCommand );
process.waitFor();
file.mkdirs(); // Since we only want to clear the directory and not delete it, we need to re-create the directory.
return true;
}
return false;
}
Worth trying if you're dealing with large or complex directories.
I have a varargs-related fear, too:
If the caller passes in an explicit array to the method (as opposed to multiple parameters), you will receive a shared reference to that array.
If you need to store this array internally, you might want to clone it first to avoid the caller being able to change it later.
Object[] args = new Object[] { 1, 2, 3} ;
varArgMethod(args); // not varArgMethod(1,2,3);
args[2] = "something else"; // this could have unexpected side-effects
While this is not really different from passing in any kind of object whose state might change later, since the array is usually (in case of a call with multiple arguments instead of an array) a fresh one created by the compiler internally that you can safely use, this is certainly unexpected behaviour.
How do I add a junit 4 dependency correctly?
Assuming you're resolving against a standard Maven (or equivalent) repo:
dependencies {
...
testCompile "junit:junit:4.11" // Or whatever version
}
Run those tests in the folders of tests/model?
You define your test source set the same way:
sourceSets {
...
test {
java {
srcDirs = ["test/model"] // Note @Peter's comment below
}
}
}
Then invoke the tests as:
./gradlew test
EDIT: If you are using JUnit 5 instead, there are more steps to complete, you should follow this tutorial.
You can set the variable 'fileencodings' in your .vimrc.
This is a list of character encodings considered when starting to edit an existing file. When a file is read, Vim tries to use the first mentioned character encoding. If an error is detected, the next one in the list is tried. When an encoding is found that works, 'fileencoding' is set to it. If all fail, 'fileencoding' is set to an empty string, which means the value of 'encoding' is used.
See :help filencodings
If you often work with e.g. cp1252, you can add it there:
set fileencodings=ucs-bom,utf-8,cp1252,default,latin9
If you have iAds in your binary you will not be able to run it on anything before iOS 4.0 and it will be rejected if you try and submit a binary like this.
You can still run the simulator from 3.2 onwards after upgrading.
In the iPhone Simulator try selecting Hardware -> Version -> 3.2
It could be caused by a data conversion from .NET to SQL, for instance a datetime conversion error. For me it was a null reference to a datetime column.
Also, that is not an exact error message. You can see the exact error in watch at exception.InnerException.InnerException -> ResultView.
Necroing this question but there's an explanation that no-one seems to have considered.
STATISTICS - Statistics are not available or misleading
If all of the following are true:
Then sql server may be incorrectly assuming that the columns are uncorrelated, leading to lower than expected cardinality estimates for applying both restrictions and a poor execution plan being selected. The fix in this case would be to create a statistics object linking the two columns, which is not an expensive operation.
The other answer is very complete, but here is a rule of thumb:
call
is blocking:
call('notepad.exe')
print('hello') # only executed when notepad is closed
Popen
is non-blocking:
Popen('notepad.exe')
print('hello') # immediately executed
There are 3 ways I can think of:
The way that is easiest to explain is
:%s/phrase to delete//gc
but you can also (personally I use this second one more often) do a regular search for the phrase to delete
/phrase to delete
Vim will take you to the beginning of the next occurrence of the phrase.
Go into insert mode (hit i) and use the Delete key to remove the phrase.
Hit escape when you have deleted all of the phrase.
Now that you have done this one time, you can hit n to go to the next occurrence of the phrase and then hit the dot/period "." key to perform the delete action you just performed
Continue hitting n and dot until you are done.
Lastly you can do a search for the phrase to delete (like in second method) but this time, instead of going into insert mode, you
Count the number of characters you want to delete
Type that number in (with number keys)
Hit the x key - characters should get deleted
Continue through with n and dot like in the second method.
PS - And if you didn't know already you can do a capital n to move backwards through the search matches.
Here's how to enumerate an object's properties:
var params = { name: 'myname', age: 'myage' }
for (var key in params) {
alert(key + "=" + params[key]);
}
There are some basics difference between ICollection and IEnumerable
Simple Program:
using System;
using System.Collections;
using System.Collections.Generic;
namespace StackDemo
{
class Program
{
static void Main(string[] args)
{
List<Person> persons = new List<Person>();
persons.Add(new Person("John",30));
persons.Add(new Person("Jack", 27));
ICollection<Person> personCollection = persons;
IEnumerable<Person> personEnumeration = persons;
// IEnumeration
// IEnumration Contains only GetEnumerator method to get Enumerator and make a looping
foreach (Person p in personEnumeration)
{
Console.WriteLine("Name:{0}, Age:{1}", p.Name, p.Age);
}
// ICollection
// ICollection Add/Remove/Contains/Count/CopyTo
// ICollection is inherited from IEnumerable
personCollection.Add(new Person("Tim", 10));
foreach (Person p in personCollection)
{
Console.WriteLine("Name:{0}, Age:{1}", p.Name, p.Age);
}
Console.ReadLine();
}
}
class Person
{
public string Name { get; set; }
public int Age { get; set; }
public Person(string name, int age)
{
this.Name = name;
this.Age = age;
}
}
}
Another hints for Unexpected token
errors.
There are two major differences between javascript objects and json:
Correct JSON
{
"english": "bag",
"kana": "kaban",
"kanji": "K"
}
Error JSON 1
{
'english': 'bag',
'kana': 'kaban',
'kanji': 'K'
}
Error JSON 2
{
english: "bag",
kana: "kaban",
kanji: "K"
}
Remark
This is not a direct answer for that question. But it's an answer for Unexpected token
errors. So it may be help others who stumple upon that question.
To send a reload call to a React-Native app running in a android device: adb shell input keyboard text "rr"
You can select dropdown option value by name
// deom
jQuery("#option_id").find("option:contains('Monday')").each(function()
{
if( jQuery(this).text() == 'Monday' )
{
jQuery(this).attr("selected","selected");
}
});
You don't need awk for this...
echo aaa0.bbb.ccc | cut -d. -f1
cut -d. -f1 <<< aaa0.bbb.ccc
echo aaa0.bbb.ccc | { IFS=. read a _ ; echo $a ; }
{ IFS=. read a _ ; echo $a ; } <<< aaa0.bbb.ccc
x=aaa0.bbb.ccc; echo ${x/.*/}
Heavier options:
sed:
echo aaa0.bbb.ccc | sed 's/\..*//'
sed 's/\..*//' <<< aaa0.bbb.ccc
awk:
echo aaa0.bbb.ccc | awk -F. '{print $1}'
awk -F. '{print $1}' <<< aaa0.bbb.ccc
You can try converting your image from tiff to PNG, here is how to do it:
import com.sun.media.jai.codec.ImageCodec;
import com.sun.media.jai.codec.ImageDecoder;
import com.sun.media.jai.codec.ImageEncoder;
import com.sun.media.jai.codec.PNGEncodeParam;
import com.sun.media.jai.codec.TIFFDecodeParam;
import java.awt.image.RenderedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import javaxt.io.Image;
public class ImgConvTiffToPng {
public static byte[] convert(byte[] tiff) throws Exception {
byte[] out = new byte[0];
InputStream inputStream = new ByteArrayInputStream(tiff);
TIFFDecodeParam param = null;
ImageDecoder dec = ImageCodec.createImageDecoder("tiff", inputStream, param);
RenderedImage op = dec.decodeAsRenderedImage(0);
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
PNGEncodeParam jpgparam = null;
ImageEncoder en = ImageCodec.createImageEncoder("png", outputStream, jpgparam);
en.encode(op);
outputStream = (ByteArrayOutputStream) en.getOutputStream();
out = outputStream.toByteArray();
outputStream.flush();
outputStream.close();
return out;
}
This is an example that could work for you if what you need is not exactly the path, but a reference to the file working offline.
http://www.ab-d.fr/date/2008-07-12/
It is in french, but the code is javascript :)
This are the references the article points to: http://developer.mozilla.org/en/nsIDOMFile http://developer.mozilla.org/en/nsIDOMFileList
Another solution that helped me a lot is to update all libs in "Node.js and NPM". You need just mark all libs and click blue arrow - 'update'
If you have jQuery enabled you can use an escapeXml function and not have to worry about escaping arrows or special characters.
<pre>
${fn:escapeXml('
<!-- all your code -->
')};
</pre>
angualr uses the lighter version of jquery called as jqlite which means it doesnt have all the features of jQuery. here is a reference in angularjs docs about what you can use from jquery. Angular Element docs
In your case you need to find a div with ID or class name. for class name you can use
var elems =$element.find('div') //returns all the div's in the $elements
angular.forEach(elems,function(v,k)){
if(angular.element(v).hasClass('class-name')){
console.log(angular.element(v));
}}
or you can use much simpler way by query selector
angular.element(document.querySelector('#id'))
angular.element(elem.querySelector('.classname'))
it is not as flexible as jQuery but what
class Foo: is called old style class and class X(object): is called new style class.
Check this What is the difference between old style and new style classes in Python? . New style is recommended. Read about "unifying types and classes"
I was working on same. Check below statement. Worked for me!!
SELECT * FROM [Schema].[Table] WHERE [Column] LIKE '%' + @Parameter + '%'
This will work:
select * into DestinationDatabase.dbo.[TableName1] from (
Select * from sourceDatabase.dbo.[TableName1])Temp
A much better way is to use inline-block
, because you don't need to use clear:both
at the end of your list anymore.
Try this:
<ul>
<li>
<a href="#">some item</a>
</li>
<li>
<a href="#">another item</a>
</li>
</ul>
CSS:
ul > li{
display:inline-block;
}
Have a look at it here : http://jsfiddle.net/shahverdy/4N6Ap/
Using ASCII(RIGHT(ProductAlternateKey, 1))
you can see that the right most character in row 2 is a Line Feed or Ascii Character 10.
This can not be removed using the standard LTrim
RTrim
functions.
You could however use (REPLACE(ProductAlternateKey, CHAR(10), '')
You may also want to account for carriage returns and tabs. These three (Line feeds, carriage returns and tabs) are the usual culprits and can be removed with the following :
LTRIM(RTRIM(REPLACE(REPLACE(REPLACE(ProductAlternateKey, CHAR(10), ''), CHAR(13), ''), CHAR(9), '')))
If you encounter any more "white space" characters that can't be removed with the above then try one or all of the below:
--NULL
Replace([YourString],CHAR(0),'');
--Horizontal Tab
Replace([YourString],CHAR(9),'');
--Line Feed
Replace([YourString],CHAR(10),'');
--Vertical Tab
Replace([YourString],CHAR(11),'');
--Form Feed
Replace([YourString],CHAR(12),'');
--Carriage Return
Replace([YourString],CHAR(13),'');
--Column Break
Replace([YourString],CHAR(14),'');
--Non-breaking space
Replace([YourString],CHAR(160),'');
This list of potential white space characters could be used to create a function such as :
Create Function [dbo].[CleanAndTrimString]
(@MyString as varchar(Max))
Returns varchar(Max)
As
Begin
--NULL
Set @MyString = Replace(@MyString,CHAR(0),'');
--Horizontal Tab
Set @MyString = Replace(@MyString,CHAR(9),'');
--Line Feed
Set @MyString = Replace(@MyString,CHAR(10),'');
--Vertical Tab
Set @MyString = Replace(@MyString,CHAR(11),'');
--Form Feed
Set @MyString = Replace(@MyString,CHAR(12),'');
--Carriage Return
Set @MyString = Replace(@MyString,CHAR(13),'');
--Column Break
Set @MyString = Replace(@MyString,CHAR(14),'');
--Non-breaking space
Set @MyString = Replace(@MyString,CHAR(160),'');
Set @MyString = LTRIM(RTRIM(@MyString));
Return @MyString
End
Go
Which you could then use as follows:
Select
dbo.CleanAndTrimString(ProductAlternateKey) As ProductAlternateKey
from DimProducts
You can't set CURRENT_TIMESTAMP as default value with DATETIME.
But you can do it with TIMESTAMP.
See the difference here.
Words from this blog
The DEFAULT value clause in a data type specification indicates a default value for a column. With one exception, the default value must be a constant; it cannot be a function or an expression.
This means, for example, that you cannot set the default for a date column to be the value of a function such as NOW() or CURRENT_DATE.
The exception is that you can specify CURRENT_TIMESTAMP as the default for a TIMESTAMP column.
For a variable number of arguments like this the only way I'm aware of is to either generate the SQL explicitly or do something that involves populating a temporary table with the items you want and joining against the temp table.
You can use
helpers.<helper>
in Rails 5+ (or ActionController::Base.helpers.<helper>
)view_context.<helper>
(Rails 4 & 3) (WARNING: this instantiates a new view instance per call)@template.<helper>
(Rails 2) singleton.helper
include
the helper in the controller (WARNING: will make all helper methods into controller actions)In proto3, all fields are "optional" (in that it is not an error if the sender fails to set them). But, fields are no longer "nullable", in that there's no way to tell the difference between a field being explicitly set to its default value vs. not having been set at all.
If you need a "null" state (and there is no out-of-range value that you can use for this) then you will instead need to encode this as a separate field. For instance, you could do:
message Foo {
bool has_baz = 1; // always set this to "true" when using baz
int32 baz = 2;
}
Alternatively, you could use oneof
:
message Foo {
oneof baz {
bool baz_null = 1; // always set this to "true" when null
int32 baz_value = 2;
}
}
The oneof
version is more explicit and more efficient on the wire but requires understanding how oneof
values work.
Finally, another perfectly reasonable option is to stick with proto2. Proto2 is not deprecated, and in fact many projects (including inside Google) very much depend on proto2 features which are removed in proto3, hence they will likely never switch. So, it's safe to keep using it for the foreseeable future.
If your panel is 'not opaque' (transparent) you wont see your background color.
Also remember that you can pass a second argument to the .forEach()
function specifying the object to use as the this
keyword.
// myOjbect is the object you want to iterate.
// Notice the second argument (secondArg) we passed to .forEach.
Object.keys(myObject).forEach(function(element, key, _array) {
// element is the name of the key.
// key is just a numerical value for the array
// _array is the array of all the keys
// this keyword = secondArg
this.foo;
this.bar();
}, secondArg);
For the instance of
render :json => @projects, :include => :tasks
You are stating that you want to render @projects
as JSON, and include the association tasks
on the Project model in the exported data.
For the instance of
render :json => @projects, :callback => 'updateRecordDisplay'
You are stating that you want to render @projects
as JSON, and wrap that data in a javascript call that will render somewhat like:
updateRecordDisplay({'projects' => []})
This allows the data to be sent to the parent window and bypass cross-site forgery issues.
A static method belongs to the class itself and a non-static (aka instance) method belongs to each object that is generated from that class. If your method does something that doesn't depend on the individual characteristics of its class, make it static (it will make the program's footprint smaller). Otherwise, it should be non-static.
Example:
class Foo {
int i;
public Foo(int i) {
this.i = i;
}
public static String method1() {
return "An example string that doesn't depend on i (an instance variable)";
}
public int method2() {
return this.i + 1; // Depends on i
}
}
You can call static methods like this: Foo.method1()
. If you try that with method2, it will fail. But this will work: Foo bar = new Foo(1); bar.method2();
If you use XAMPP Path ( $cfg['Servers'][$i]['pmadb'] = 'phpmyadmin'; ) C:\xampp\phpmyadmin\config.inc.php (Probably XAMPP1.8 at Line Number 34)
Another Solution: I face same type problem "#1142 - SELECT command denied to user ''@'localhost' for table 'pma_recent'"
Some people don't like this, and it's more of a .NET convention than Java, but you can name your interfaces with a capital I prefix, for example:
IProductRepository - interface
ProductRepository, SqlProductRepository, etc. - implementations
The people opposed to this naming convention might argue that you shouldn't care whether you're working with an interface or an object in your code, but I find it easier to read and understand on-the-fly.
I wouldn't name the implementation class with a "Class" suffix. That may lead to confusion, because you can actually work with "class" (i.e. Type) objects in your code, but in your case, you're not working with the class object, you're just working with a plain-old object.
With JQuery, another way to check the current status of the radio buttons is to get the attribute 'checked'.
For Example:
<input type="radio" name="gender_male" value="Male" />
<input type="radio" name="gender_female" value="Female" />
In this case you can check the buttons using:
if ($("#gender_male").attr("checked") == true) {
...
}
An alternative way of sending a large number of repeating characters to a text field (for instance to test the maximum number of characters the field will allow) is to type a few characters and then repeatedly copy and paste them:
inputField.sendKeys('0123456789');
for(int i = 0; i < 100; i++) {
inputField.sendKeys(Key.chord(Key.CONTROL, 'a'));
inputField.sendKeys(Key.chord(Key.CONTROL, 'c'));
for(int i = 0; i < 10; i++) {
inputField.sendKeys(Key.chord(Key.CONTROL, 'v'));
}
}
Unfortunately pressing CTRL doesn't seem to work for IE unless REQUIRE_WINDOW_FOCUS
is enabled (which can cause other issues), but it works fine for Firefox and Chrome.
Actually 3 of the options mentioned by other work.
1.
soup_object= BeautifulSoup(markup,"html.parser") #Python HTML parser
pip install lxml
soup_object= BeautifulSoup(markup,'lxml') # C dependent parser
pip install html5lib
soup_object= BeautifulSoup(markup,'html5lib') # C dependent parser
Most of the other answers seem to be db specific.
General SQL query should be as follows:
select
sal
from
emp a
where
N = (
select
count(distinct sal)
from
emp b
where
a.sal <= b.sal
)
where
N = any value
and this query should be able to work on any database.
From MySQL 8.0 you could use
ALTER TABLE table_name RENAME COLUMN old_col_name TO new_col_name;
RENAME COLUMN:
Can change a column name but not its definition.
More convenient than CHANGE to rename a column without changing its definition.
You can also use EXIT_SUCCESS
instead of return 0;
. The macro EXIT_SUCCESS
is actually defined as zero, but makes your program more readable.
AWK works as a text interpreter that goes linewise for the whole document and that goes fieldwise for each line. Thus $1, $2...$n are references to the fields of each line ($1 is the first field, $2 is the second field, and so on...).
You can define a field separator by using the "-F" switch under the command line or within two brackets with "FS=...".
Now consider the answer of Jürgen:
echo "1: " | awk -F ":" '/1/ {print $1}'
Above the field, boundaries are set by ":" so we have two fields $1 which is "1" and $2 which is the empty space. After comes the regular expression "/1/" that instructs the filter to output the first field only when the interpreter stumbles upon a line containing such an expression (I mean 1).
The output of the "echo" command is one line that contains "1", so the filter will work...
When dealing with the following example:
echo "1: " | awk '/1/ -F ":" {print $1}'
The syntax is messy and the interpreter chose to ignore the part F ":" and switches to the default field splitter which is the empty space, thus outputting "1:" as the first field and there will be not a second field!
The answer of Jürgen contains the good syntax...
This should work
function updatePostID(val)
{
document.getElementById('PostID').value = val;
//and probably call document.forms[0].submit();
}
Then have a hidden field or other control for the PostID
@Html.Hidden("PostID", Model.addcomment.PostID)
//OR
@Html.HiddenFor(model => model.addcomment.PostID)
Try this.This one is written in typescript.
export function safeJsonParse(str: string) {
try {
return JSON.parse(str);
} catch (e) {
return str;
}
}
By comparing the solution below with the one that uses cumsum of numpy, This one takes almost half the time. This is because it does not need to go through the entire array to do the cumsum and then do all the subtraction. Moreover, the cumsum can be "dangerous" if the array is huge and the number are huge (possible overflow). Of course, also here the danger exists but at least are summed together only the essential numbers.
def moving_average(array_numbers, n):
if n > len(array_numbers):
return []
temp_sum = sum(array_numbers[:n])
averages = [temp_sum / float(n)]
for first_index, item in enumerate(array_numbers[n:]):
temp_sum += item - array_numbers[first_index]
averages.append(temp_sum / float(n))
return averages
After forking, use dup2(2)
to duplicate the file's FD into stdout's FD, then exec.
If you are not using any javascript/jquery for form validation, then a simple layout for your form would look like this.
within the body of your html document:
<form action="formHandler.php" name="yourForm" id="theForm" method="post">
<input type="text" name="fname" id="fname" />
<input type="submit" value="submit"/>
</form>
You need to ensure you have the submit button within the form tags, and an appropriate action assigned. Such as sending to a php file.
For a more direct answer, provide the code you are working with.
You may find the following of use: http://www.w3.org/TR/html401/interact/forms.html
This worked for me.
//used in an ASP.NET MVC app
private const string BatchFilePath = "/MyBatchFileDirectory/Mybatchfiles.bat";
var batchFile = HttpContext.Current.Server.MapPath(BatchFilePath);
Chrome wants to focus on a control that is required but still empty so that it can pop up the message 'Please fill out this field'. However, if the control is hidden at the point that Chrome wants to pop up the message, that is at the time of form submission, Chrome can't focus on the control because it is hidden, therefore the form won't submit.
So, to get around the problem, when a control is hidden by javascript, we also must remove the 'required' attribute from that control.
Use ng-click
in place of onclick
. and its as simple as that:
<a href="www.mysite.com" ng-click="return theFunction();">Item</a>
<script type="text/javascript">
function theFunction () {
// return true or false, depending on whether you want to allow
// the`href` property to follow through or not
}
</script>
It's just
var counter = 0;
$("#update").click(function() {
counter++;
});
Here is a really simple way to do it :)
Clone the repository
git clone <repository_url>
List all branches
git branch -a
Checkout the branch that you want
git checkout <name_of_branch>
try this
delimiter ;;
drop procedure if exists test2;;
create procedure test2()
begin
select ‘Hello World’;
end
;;
Just for completion.
This error might be as well the case if you have a foreign key with VARCHAR(..) and the charset of the referenced table is different from the table referencing it.
e.g. VARCHAR(50) in a Latin1 Table is different than the VARCHAR(50) in a UTF8 Table.
My suggestion would be to run compaudit and then just fix permissions on the directories found by the audit. Make sure the identified directories do not have write permissions for group or other.
If you want to redirect previous location or last request then you have to include user_agent
library:
$this->load->library('user_agent');
and then use at last in a function that you are using:
redirect($this->agent->referrer());
its working for me.
The key here I guess is to round up correctly first, then you can convert it to String.
function roundOf(n, p) {
const n1 = n * Math.pow(10, p + 1);
const n2 = Math.floor(n1 / 10);
if (n1 >= (n2 * 10 + 5)) {
return (n2 + 1) / Math.pow(10, p);
}
return n2 / Math.pow(10, p);
}
// All edge cases listed in this thread
roundOf(95.345, 2); // 95.35
roundOf(95.344, 2); // 95.34
roundOf(5.0364342423, 2); // 5.04
roundOf(0.595, 2); // 0.60
roundOf(0.335, 2); // 0.34
roundOf(0.345, 2); // 0.35
roundOf(551.175, 2); // 551.18
roundOf(0.3445434, 2); // 0.34
Now you can safely format this value with toFixed(p). So with your specific case:
roundOf(0.3445434, 2).toFixed(2); // 0.34
Deadlock occurs when a thread is waiting for other thread to finish and vice versa.
How to avoid?
- Avoid Nested Locks
- Avoid Unnecessary Locks
- Use thread join()
How do you detect it?
run this command in cmd:
jcmd $PID Thread.print
reference : geeksforgeeks
If you bind events to the onmouseover and onmouseout events in Jquery, you can then trigger that effect using mouseenter().
What are you trying to accomplish?
I want to correct little bit the above code
public class MainActivity extends ActionBarActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar mToolbar = (Toolbar) findViewById(R.id.toolbar);
DrawerLayout mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle mDrawerToggle = new ActionBarDrawerToggle(
this, mDrawerLayout, mToolbar,
R.string.navigation_drawer_open, R.string.navigation_drawer_close
);
mDrawerLayout.setDrawerListener(mDrawerToggle);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
}
and all the other things will remain same...
For those who are having problem Drawerlayout
overlaying toolbar
add android:layout_marginTop="?attr/actionBarSize"
to root layout of drawer content
On a rather unrelated note: more performance hacks!
When traversing the sequence, we can only get 3 possible cases in the 2-neighborhood of the current element N
(shown first):
To leap past these 2 elements means to compute (N >> 1) + N + 1
, ((N << 1) + N + 1) >> 1
and N >> 2
, respectively.
Let`s prove that for both cases (1) and (2) it is possible to use the first formula, (N >> 1) + N + 1
.
Case (1) is obvious. Case (2) implies (N & 1) == 1
, so if we assume (without loss of generality) that N is 2-bit long and its bits are ba
from most- to least-significant, then a = 1
, and the following holds:
(N << 1) + N + 1: (N >> 1) + N + 1:
b10 b1
b1 b
+ 1 + 1
---- ---
bBb0 bBb
where B = !b
. Right-shifting the first result gives us exactly what we want.
Q.E.D.: (N & 1) == 1 ? (N >> 1) + N + 1 == ((N << 1) + N + 1) >> 1
.
As proven, we can traverse the sequence 2 elements at a time, using a single ternary operation. Another 2× time reduction.
The resulting algorithm looks like this:
uint64_t sequence(uint64_t size, uint64_t *path) {
uint64_t n, i, c, maxi = 0, maxc = 0;
for (n = i = (size - 1) | 1; i > 2; n = i -= 2) {
c = 2;
while ((n = ((n & 3)? (n >> 1) + n + 1 : (n >> 2))) > 2)
c += 2;
if (n == 2)
c++;
if (c > maxc) {
maxi = i;
maxc = c;
}
}
*path = maxc;
return maxi;
}
int main() {
uint64_t maxi, maxc;
maxi = sequence(1000000, &maxc);
printf("%llu, %llu\n", maxi, maxc);
return 0;
}
Here we compare n > 2
because the process may stop at 2 instead of 1 if the total length of the sequence is odd.
Let`s translate this into assembly!
MOV RCX, 1000000;
DEC RCX;
AND RCX, -2;
XOR RAX, RAX;
MOV RBX, RAX;
@main:
XOR RSI, RSI;
LEA RDI, [RCX + 1];
@loop:
ADD RSI, 2;
LEA RDX, [RDI + RDI*2 + 2];
SHR RDX, 1;
SHRD RDI, RDI, 2; ror rdi,2 would do the same thing
CMOVL RDI, RDX; Note that SHRD leaves OF = undefined with count>1, and this doesn't work on all CPUs.
CMOVS RDI, RDX;
CMP RDI, 2;
JA @loop;
LEA RDX, [RSI + 1];
CMOVE RSI, RDX;
CMP RAX, RSI;
CMOVB RAX, RSI;
CMOVB RBX, RCX;
SUB RCX, 2;
JA @main;
MOV RDI, RCX;
ADD RCX, 10;
PUSH RDI;
PUSH RCX;
@itoa:
XOR RDX, RDX;
DIV RCX;
ADD RDX, '0';
PUSH RDX;
TEST RAX, RAX;
JNE @itoa;
PUSH RCX;
LEA RAX, [RBX + 1];
TEST RBX, RBX;
MOV RBX, RDI;
JNE @itoa;
POP RCX;
INC RDI;
MOV RDX, RDI;
@outp:
MOV RSI, RSP;
MOV RAX, RDI;
SYSCALL;
POP RAX;
TEST RAX, RAX;
JNE @outp;
LEA RAX, [RDI + 59];
DEC RDI;
SYSCALL;
Use these commands to compile:
nasm -f elf64 file.asm
ld -o file file.o
See the C and an improved/bugfixed version of the asm by Peter Cordes on Godbolt. (editor's note: Sorry for putting my stuff in your answer, but my answer hit the 30k char limit from Godbolt links + text!)
A very simple solution is to override
the toString()
method in the Node
. Then, you can call print by passing LinkedList
's head
.
You don't need to implement any kind of loop.
Code:
public class LinkedListNode {
...
//New
@Override
public String toString() {
return String.format("Node(%d, next = %s)", data, next);
}
}
public class LinkedList {
public static void main(String[] args) {
LinkedList l = new LinkedList();
l.insertFront(0);
l.insertFront(1);
l.insertFront(2);
l.insertFront(3);
//New
System.out.println(l.head);
}
}
Yes, it's OK - it's just like using it in an if
statement. Of course, you can't use a break
to break out of a loop from inside a switch.
If you want to parse a String to a char, whereas the String object represent more than one character, you just simply use the following expression: char c = (char) Integer.parseInt(s). Where s equals the String you want to parse. Most people forget that char's represent a 16-bit number, and thus can be a part of any numerical expression :)
This may be an old response but I used some examples from this post to create a comparator that would sort an ArrayList
of HashMap<String, String>
by one object in the list, that being the timestamp.
I have these objects:
ArrayList<Map<String, String>> alList = new ArrayList<Map<String, String>>();
The map objects are as follows:
Map<String, Object> map = new HashMap<>();
// of course this is the actual formatted date below in the timestamp
map.put("timestamp", "MM/dd/yyyy HH:mm:ss");
map.put("item1", "my text goes here");
map.put("item2", "my text goes here");
That mapping is what I use to load all my objects into the array list, using the alList.add(map)
function, within a loop.
Now, I created my own comparator:
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Map;
public class DateSorter implements Comparator {
public int compare(Object firstObjToCompare, Object secondObjToCompare) {
String firstDateString = ((HashMap<String, String>) firstObjToCompare).get("timestamp");
String secondDateString = ((HashMap<String, String>) secondObjToCompare).get("timestamp");
if (secondDateString == null || firstDateString == null) {
return 0;
}
// Convert to Dates
DateTimeFormatter dtf = DateTimeFormat.forPattern("MM/dd/yyyy HH:mm:ss");
DateTime firstDate = dtf.parseDateTime(firstDateString);
DateTime secondDate = dtf.parseDateTime(secondDateString);
if (firstDate.isAfter(secondDate)) return -1;
else if (firstDate.isBefore(secondDate)) return 1;
else return 0;
}
}
I can now just call the Comparator at any time on the array and it will sort my array, giving me the Latest timestamp in position 0 (top of the list) and the earliest timestamp at the end of the list. New posts get put to the top basically.
Collections.sort(alList, new DateSorter());
This may help someone out, which is why I posted it. Take into consideration the return statements within the compare() function. There are 3 types of results. Returning 0 if they are equal, returning >0 if the first date is before the second date and returning <0 if the first date is after the second date. If you want your list to be reversed, then just switch those two return statements! Simple =]
Sometime in the future Comment out the following code in web.config
<!--<system.codedom>
<compilers>
<compiler language="c#;cs;csharp" extension=".cs" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:6 /nowarn:1659;1699;1701" />
<compiler language="vb;vbs;visualbasic;vbscript" extension=".vb" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.VBCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:14 /nowarn:41008 /define:_MYTYPE=\"Web\" /optionInfer+" />
</compilers>
</system.codedom>-->
update the to the following code.
<system.web>
<authentication mode="None" />
<compilation debug="true" targetFramework="4.6.1" />
<httpRuntime targetFramework="4.6.1" />
<customErrors mode="Off"/>
<trust level="Full"/>
</system.web>
Faced the same issue. Indeed it was wrong SQL at the beginning of the file because when dumping I did:
mysqldump -u username --password=password db_name > dump.sql
Which wrote at the beginning of the file something that was in stdout which was:
mysqldump: [Warning] Using a password on the command line interface can be insecure.
Resulting in the restore raising that error.
So deleting the first line of the SQL dump enables a proper restore.
Looking at the way the restore was done in the original question, there is a high chance the dump was done similarly as mine, causing a stdout warning printing in the SQL file (if ever mysqldump was printing it back then).
You need to type result
to an array of string const result: string[] = [];
.
I just triggered the tests on a pull request to be re-run by clicking 'update branch' here:
The normal way of doing it is:
You don't need a JsonResult or jQuery for this.
I experienced that problem only when running on real device (iPhone SE). On simulator project worked as expected.
I did try all fixes from this very thread and from here. None of those worked for me.
For me problem was solved after restarting iPhone (sic!).
I did:
And it finally works. :)
If every other solution fails don't forget to try it out.
Color picker plugin for Interface Builder
There's a nice color picker from Panic which works well with IB: http://panic.com/~wade/picker/
Xcode plugin
This one gives you a GUI for choosing colors: http://www.youtube.com/watch?v=eblRfDQM0Go
Objective-C
UIColor *color = [UIColor colorWithRed:(160/255.0) green:(97/255.0) blue:(5/255.0) alpha:1.0];
Swift
let color = UIColor(red: 160/255, green: 97/255, blue: 5/255, alpha: 1.0)
Pods and libraries
There's a nice pod named MPColorTools
: https://github.com/marzapower/MPColorTools
This exception happened when I forgot to close the connections
I would use @HostListener decorator within your component:
import { HostListener } from '@angular/core';
@Component({
...
})
export class AppComponent {
@HostListener('document:keypress', ['$event'])
handleKeyboardEvent(event: KeyboardEvent) {
this.key = event.key;
}
}
There are also other options like:
host property within @Component
decorator
Angular recommends using @HostListener
decorator over host property https://angular.io/guide/styleguide#style-06-03
@Component({
...
host: {
'(document:keypress)': 'handleKeyboardEvent($event)'
}
})
export class AppComponent {
handleKeyboardEvent(event: KeyboardEvent) {
console.log(event);
}
}
renderer.listen
import { Component, Renderer2 } from '@angular/core';
@Component({
...
})
export class AppComponent {
globalListenFunc: Function;
constructor(private renderer: Renderer2) {}
ngOnInit() {
this.globalListenFunc = this.renderer.listen('document', 'keypress', e => {
console.log(e);
});
}
ngOnDestroy() {
// remove listener
this.globalListenFunc();
}
}
Observable.fromEvent
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/observable/fromEvent';
import { Subscription } from 'rxjs/Subscription';
@Component({
...
})
export class AppComponent {
subscription: Subscription;
ngOnInit() {
this.subscription = Observable.fromEvent(document, 'keypress').subscribe(e => {
console.log(e);
})
}
ngOnDestroy() {
this.subscription.unsubscribe();
}
}
I recommend to use SMO (Enable TCP/IP Network Protocol for SQL Server). However, it was not available in my case.
I rewrote the WMI commands from Krzysztof Kozielczyk to PowerShell.
# Enable TCP/IP
Get-CimInstance -Namespace root/Microsoft/SqlServer/ComputerManagement10 -ClassName ServerNetworkProtocol -Filter "InstanceName = 'SQLEXPRESS' and ProtocolName = 'Tcp'" |
Invoke-CimMethod -Name SetEnable
# Open the right ports in the firewall
New-NetFirewallRule -DisplayName 'MSSQL$SQLEXPRESS' -Direction Inbound -Action Allow -Protocol TCP -LocalPort 1433
# Modify TCP/IP properties to enable an IP address
$properties = Get-CimInstance -Namespace root/Microsoft/SqlServer/ComputerManagement10 -ClassName ServerNetworkProtocolProperty -Filter "InstanceName='SQLEXPRESS' and ProtocolName = 'Tcp' and IPAddressName='IPAll'"
$properties | ? { $_.PropertyName -eq 'TcpPort' } | Invoke-CimMethod -Name SetStringValue -Arguments @{ StrValue = '1433' }
$properties | ? { $_.PropertyName -eq 'TcpPortDynamic' } | Invoke-CimMethod -Name SetStringValue -Arguments @{ StrValue = '' }
# Restart SQL Server
Restart-Service 'MSSQL$SQLEXPRESS'
To change the encoding of your database:
Make sure the client encoding is set correctly during all this.
Source: http://archives.postgresql.org/pgsql-novice/2006-03/msg00210.php
Here is another way to do it.
import webbrowser
webbrowser.open("foobar.com")
Just try this one as a full copy paste in the shell and you will grasp it
# create the example file to be working on ..
cat << EOF > tmp.json
[
{ "card_id": "id-00", "card_id_type": "card_id_type-00"},
{"card_id": "id-01", "card_id_type": "card_id_type-01"},
{ "card_id": "id-02", "card_id_type": "card_id_type-02"}
]
EOF
# pipe the content of the file to the jq query, which gets the array of objects
# and select the attribute named "card_id" ONLY if it's neighbour attribute
# named "card_id_type" has the "card_id_type-01" value
# jq -r means give me ONLY the value of the jq query no quotes aka raw
cat tmp.json | jq -r '.[]| select (.card_id_type == "card_id_type-01")|.card_id'
id-01
or with an aws cli command
# list my vpcs or
# list the values of the tags which names are "Name"
aws ec2 describe-vpcs | jq -r '.| .Vpcs[].Tags[]|select (.Key == "Name") | .Value'|sort -nr
Something like this should resolve the issue..
Vue.component(
'example-component',
require('./components/ExampleComponent.vue').default);
I think you can try to firstly select all the text in the field and then send the new sequence:
from selenium.webdriver.common.keys import Keys
element.sendKeys(Keys.chord(Keys.CONTROL, "a"), "55");
Combined generics with double API. Guess it's a bit of cheating, but at least we need to write only one method:
static <T extends Number> boolean isNegative(T number)
{
return ((number.doubleValue() * Double.POSITIVE_INFINITY) == Double.NEGATIVE_INFINITY);
}
This answer came up when searching for "java invert boolean function". The example below will prevent certain static analysis tools from failing builds due to branching logic. This is useful if you need to invert a boolean and haven't built out comprehensive unit tests ;)
Boolean.valueOf(aBool).equals(false)
or alternatively:
Boolean.FALSE.equals(aBool)
or
Boolean.FALSE::equals
I can't repro, but I suspect that in your actual code there is a constraint somewhere that T : class
- you need to propagate that to make the compiler happy, for example (hard to say for sure without a repro example):
public class Derived<SomeModel> : Base<SomeModel> where SomeModel : class, IModel
^^^^^
see this bit
Java's parser in java.net.URI
is going to fail if the URI isn't fully encoded to its standards. For example, try to parse: http://www.google.com/search?q=cat|dog
. An exception will be thrown for the vertical bar.
urllib makes it easy to convert a string to a java.net.URI
. It will pre-process and escape the URL.
assertEquals("http://www.google.com/search?q=cat%7Cdog",
Urls.createURI("http://www.google.com/search?q=cat|dog").toString());
Setting val('')
will empty the input field. So you would use this:
Clear the input field when the page loads:
$(function(){
$('#shares').val('');
});
In my instance, the error was generated because one of my complex types had a property with no set method.
The serializer threw an exception because of that fact. Added internal set methods and it all worked fine.
Best way to find out why this is happening (in my opinion) is to enable trace logging.
I achieved this by adding the following section to my web.config
:
<system.diagnostics>
<sources>
<source name="System.ServiceModel.MessageLogging" switchValue="Warning,ActivityTracing">
<listeners>
<add name="traceListener"
type="System.Diagnostics.XmlWriterTraceListener"
initializeData= "c:\log\Traces.svclog" />
<add type="System.Diagnostics.DefaultTraceListener" name="Default" />
</listeners>
</source>
<source propagateActivity="true" name="System.ServiceModel" switchValue="Verbose,ActivityTracing">
<listeners>
<add name="traceListener"
type="System.Diagnostics.XmlWriterTraceListener"
initializeData= "c:\log\Traces.svclog" />
<add type="System.Diagnostics.DefaultTraceListener" name="Default" />
</listeners>
</source>
</sources>
<trace autoflush="true" />
</system.diagnostics>
Once set, I ran my client, got exception and checked the 'Traces.svclog' file. From there, I only needed to find the exception.
There is U+1F50D LEFT-POINTING MAGNIFYING GLASS () and U+1F50E RIGHT-POINTING MAGNIFYING GLASS ().
You should use (in HTML) 🔍
or 🔎
They are, however not supported by many fonts (fileformat.info only lists a few fonts as supporting the Codepoint with a proper glyph).
Also note that they are outside of the BMP, so some Unicode-capable software might have problems rendering them, even if they have fonts that support them.
Generally Unicode Glyphs can be searched using a site such as fileformat.info. This searches "only" in the names and properties of the Unicode glyphs, but they usually contain enough metadata to allow for good search results (for this answer I searched for "glass" and browsed the resulting list, for example)
You could escape the % in %20 like so:
print "Hello%%20World%s" %"!"
or you could try using the string formatting routines instead, like:
print "Hello%20World{0}".format("!")
Office 365 and OneDrive offer an embed feature. You can then include via IFrame.
I found that setting the iframe height and width to 100% works best. That way on ipad or any device for that matter it fits the screen.
<body style="margin:0px;padding:0px;overflow:hidden">
<iframe src="embed url" frameborder="0" style="overflow:hidden;overflow-x:hidden;overflow-y:hidden;height:100%;width:100%;position:absolute;top:0px;left:0px;right:0px;bottom:0px" height="100%" width="100%"></iframe>
</body>
If you're using jQuery you might want to check out jQuery.param()
http://api.jquery.com/jQuery.param/
Example:
var params = {
parameter1: 'value1',
parameter2: 'value2',
parameter3: 'value3'
};
?var query = $.param(params);
document.write(query);
For the first rule,
Click "greater than", then in the value option box, click on the cell criteria you want it to be less than, than use the format drop-down to select your color.
For the second,
Click "less than", then in the value option box, type "=.9*" and then click the cell criteria, then use the formatting just like step 1.
For the third,
Same as the second, except your formula is =".8*" rather than .9.
For some who still got this issue to solve even after applying the suggestion of this thread(i used to be one like that) add this line on your Application class, onCreate() method
AppCompatDelegate.setCompatVectorFromResourcesEnabled(true)
As suggested here and here sometimes this is required to access vectors from resources especially when you're dealing with menu items, etc
Make sure you have the prerequisite, a JVM (http://wiki.eclipse.org/Eclipse/Installation#Install_a_JVM) installed.
This will be a JRE and JDK package.
There are a number of sources which includes: http://www.oracle.com/technetwork/java/javase/downloads/index.html.
Java's substring
method fails when you try and get a substring starting at an index which is longer than the string.
An easy alternative is to use Apache Commons StringUtils.substring
:
public static String substring(String str, int start)
Gets a substring from the specified String avoiding exceptions.
A negative start position can be used to start n characters from the end of the String.
A null String will return null. An empty ("") String will return "".
StringUtils.substring(null, *) = null
StringUtils.substring("", *) = ""
StringUtils.substring("abc", 0) = "abc"
StringUtils.substring("abc", 2) = "c"
StringUtils.substring("abc", 4) = ""
StringUtils.substring("abc", -2) = "bc"
StringUtils.substring("abc", -4) = "abc"
Parameters:
str - the String to get the substring from, may be null
start - the position to start from, negative means count back from the end of the String by this many characters
Returns:
substring from start position, null if null String input
Note, if you can't use Apache Commons lib for some reason, you could just grab the parts you need from the source
// Substring
//-----------------------------------------------------------------------
/**
* <p>Gets a substring from the specified String avoiding exceptions.</p>
*
* <p>A negative start position can be used to start {@code n}
* characters from the end of the String.</p>
*
* <p>A {@code null} String will return {@code null}.
* An empty ("") String will return "".</p>
*
* <pre>
* StringUtils.substring(null, *) = null
* StringUtils.substring("", *) = ""
* StringUtils.substring("abc", 0) = "abc"
* StringUtils.substring("abc", 2) = "c"
* StringUtils.substring("abc", 4) = ""
* StringUtils.substring("abc", -2) = "bc"
* StringUtils.substring("abc", -4) = "abc"
* </pre>
*
* @param str the String to get the substring from, may be null
* @param start the position to start from, negative means
* count back from the end of the String by this many characters
* @return substring from start position, {@code null} if null String input
*/
public static String substring(final String str, int start) {
if (str == null) {
return null;
}
// handle negatives, which means last n characters
if (start < 0) {
start = str.length() + start; // remember start is negative
}
if (start < 0) {
start = 0;
}
if (start > str.length()) {
return EMPTY;
}
return str.substring(start);
}
enum
type in Java 5 and onwards for the purpose you have described. It is type safe.If you are talking about the difference between instance variable and class variable, instance variable exist per object created. While class variable has only one copy per class loader regardless of the number of objects created.
Java 5 and up enum
type
public enum Color{
RED("Red"), GREEN("Green");
private Color(String color){
this.color = color;
}
private String color;
public String getColor(){
return this.color;
}
public String toString(){
return this.color;
}
}
If you wish to change the value of the enum you have created, provide a mutator method.
public enum Color{
RED("Red"), GREEN("Green");
private Color(String color){
this.color = color;
}
private String color;
public String getColor(){
return this.color;
}
public void setColor(String color){
this.color = color;
}
public String toString(){
return this.color;
}
}
Example of accessing:
public static void main(String args[]){
System.out.println(Color.RED.getColor());
// or
System.out.println(Color.GREEN);
}
This topic is old but if other people like me search a solution, this is a solution that I have found:
Public Function DBStats() As Boolean
On Error GoTo errorHandler
If Not IsNull(myBase.Version) Then
DBStats = True
End If
Exit Function
errorHandler:
DBStats = False
End Function
So "myBase" is a Database Object, I have made a class to access to database (class with insert, update etc...) and on the module the class is use declare in an object (obviously) and I can test the connection with "[the Object].DBStats":
Dim BaseAccess As New myClass
BaseAccess.DBOpen 'I open connection
Debug.Print BaseAccess.DBStats ' I test and that tell me true
BaseAccess.DBClose ' I close the connection
Debug.Print BaseAccess.DBStats ' I test and tell me false
Edit : In DBOpen I use "OpenDatabase" and in DBClose I use ".Close" and "set myBase = nothing" Edit 2: In the function, if you are not connect, .version give you an error so if aren't connect, the errorHandler give you false
I decided to write my own script to ease some of the pain of setting up projects.
Run the following inside your project root:
wget -qO- https://raw.githubusercontent.com/defaye/bootstrap-laravel/master/bootstrap.sh | sh
Wait for the bootstrapping to complete and you're good to go.
Review the script before use.
All of these options work depending on your situation, but you may not see any of them work if you're using SSMS (as mentioned in some comments SSMS hides CR/LFs)
So rather than driving yourself round the bend, Check this setting in
Tools
|
Options
Well, your syntax doesn't match the link you included, which specifies:
CREATE TABLE name (column defs)
CONSTRAINT constraint_name -- This is new
UNIQUE (col_name1, col_name2) ON CONFLICT REPLACE
Your program will continue with the second if
statement in the case of y == x
, causing a ZeroDivisionError
. You need to make the statements mutually exclusive; the way to do that is to use elif
("else if") instead of if
:
import math
x = int(input("Enter a value for x: "))
y = int(input("Enter a value for y: "))
if y == x:
print(1)
elif y == 1: # see georg's comment
print(x)
elif y > x: # will be executed only if y != 1 and y != x
print(0)
else: # will be executed only if y != 1 and y != x and x <= y
a = math.factorial(x)
b = math.factorial(y)
c = math.factorial(x-y) # that appears to be useful to get the correct result
div = a // (b * c)
print(div)
Choosing to Project -> Clean should resolve this
In my case, I tried unlocking the file with tf lock
but was told I couldn't because the stale workspace on an old computer that no longer existed was a local workspace. I then tried deleting the workspace with tf workspace /delete
, but deleting the workspace did not remove the lock (and then I couldn't try to unlock it again because I just got an error saying the workspace no longer existed).
I ended up tf destroy
ing the file and checking it in again, which was pretty silly and had the undesirable effect of removing\ it from previous changesets, but at least got us working again. It wasn't that big a deal in this case since the file had never been changed since being checked in.
Alternatively, by changing a line of the above code:
# df.date = df.date.apply(lambda d: datetime.strptime(d, "%Y-%m-%d"))
df.date = df.date.apply(lambda d: datetime.datetime.fromtimestamp(int(d)).strftime('%Y-%m-%d'))
It should also work.
It's funny I had a similar issue and didn't find anything suitable and was aware of good old Dependency Walker so in the end I wrote one myself.
This deals with .NET specifically and will show what references an assembly has (and missing) recursively. It'll also show native library dependencies.
It's free (for personal use) and available here for anyone interested: www.netdepends.com
Feedback welcome.
you can delete the corresponding failed artifact directory in you local repository. And also you can simply use the -U
in the goal. It will do the work. This works with maven 3. So no need to downgrade to maven 2.
Call parent.remove(panel)
, where parent
is the container that you want the frame in and panel
is the panel you want to add.
Clear:both gives you that space between them.
For example your code:
<div style="float:left">Hello</div>
<div style="float:right">Howdy dere pardner</div>
Will currently display as :
Hello ................... Howdy dere pardner
If you add the following to above snippet,
<div style="clear:both"></div>
In between them it will display as:
Hello ................
Howdy dere pardner
giving you that space between hello and Howdy dere pardner.
Js fiiddle http://jsfiddle.net/Qk5vR/1/
One more cause for the "secret key not available" message: GPG version mismatch.
Practical example: I had been using GPG v1.4. Switching packaging systems, the MacPorts supplied gpg was removed, and revealed another gpg binary in the path, this one version 2.0. For decryption, it was unable to locate the secret key and gave this very error. For encryption, it complained about an unusable public key. However, gpg -k and -K both listed valid keys, which was the cause of major confusion.
For large numbers of events this might help:
var element = document.getElementById("myId");
var myEvents = "click touchstart touchend".split(" ");
var handler = function (e) {
do something
};
for (var i=0, len = myEvents.length; i < len; i++) {
element.addEventListener(myEvents[i], handler, false);
}
Update 06/2017:
Now that new language features are more widely available you could simplify adding a limited list of events that share one listener.
const element = document.querySelector("#myId");
function handleEvent(e) {
// do something
}
// I prefer string.split because it makes editing the event list slightly easier
"click touchstart touchend touchmove".split(" ")
.map(name => element.addEventListener(name, handleEvent, false));
If you want to handle lots of events and have different requirements per listener you can also pass an object which most people tend to forget.
const el = document.querySelector("#myId");
const eventHandler = {
// called for each event on this element
handleEvent(evt) {
switch (evt.type) {
case "click":
case "touchstart":
// click and touchstart share click handler
this.handleClick(e);
break;
case "touchend":
this.handleTouchend(e);
break;
default:
this.handleDefault(e);
}
},
handleClick(e) {
// do something
},
handleTouchend(e) {
// do something different
},
handleDefault(e) {
console.log("unhandled event: %s", e.type);
}
}
el.addEventListener(eventHandler);
Update 05/2019:
const el = document.querySelector("#myId");
const eventHandler = {
handlers: {
click(e) {
// do something
},
touchend(e) {
// do something different
},
default(e) {
console.log("unhandled event: %s", e.type);
}
},
// called for each event on this element
handleEvent(evt) {
switch (evt.type) {
case "click":
case "touchstart":
// click and touchstart share click handler
this.handlers.click(e);
break;
case "touchend":
this.handlers.touchend(e);
break;
default:
this.handlers.default(e);
}
}
}
Object.keys(eventHandler.handlers)
.map(eventName => el.addEventListener(eventName, eventHandler))