You have not provided providers in your module:
<strike>import { HttpModule } from '@angular/http';</strike>
import { HttpClientModule, HttpClient } from '@angular/common/http';
@NgModule({
imports: [
BrowserModule,
HttpClientModule,
BrowserAnimationsModule,
FormsModule,
AppRoutingModule
],
providers: [ HttpClientModule, ... ]
// ...
})
export class MyModule { /* ... */ }
You will need to add the HttpClientTestingModule
to the TestBed configuration when running ng test
and getting the "No provider for HttpClient" error:
// Http testing module and mocking controller
import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing';
// Other imports
import { TestBed } from '@angular/core/testing';
import { HttpClient, HttpErrorResponse } from '@angular/common/http';
describe('HttpClient testing', () => {
let httpClient: HttpClient;
let httpTestingController: HttpTestingController;
beforeEach(() => {
TestBed.configureTestingModule({
imports: [ HttpClientTestingModule ]
});
// Inject the http service and test controller for each test
httpClient = TestBed.get(HttpClient);
httpTestingController = TestBed.get(HttpTestingController);
});
it('works', () => {
});
});
Use this line of code in your css
border: 1px solid #000 !important;
or if you want border only in left and right side of container then use:
border-right: 1px solid #000 !important;
border-left: 1px solid #000 !important;
I realise this is an old post, but just in case anyone else is looking, you can use Contains
by providing the case insensitive string equality comparer like so:
using System.Linq;
// ...
if (testList.Contains(keyword, StringComparer.OrdinalIgnoreCase))
{
Console.WriteLine("Keyword Exists");
}
This has been available since .net 2.0 according to msdn.
I think
event.preventDefault()
is the w3c specified way of canceling events.
You can read this in the W3C spec on Event cancelation.
Also you can't use return false in every situation. When giving a javascript function in the href attribute and if you return false then the user will be redirected to a page with false string written.
You can use a string comparison parameter (available from .net 2.1 and above) String.Contains Method.
public bool Contains (string value, StringComparison comparisonType);
Example:
string title = "ASTRINGTOTEST";
title.Contains("string", StringComparison.InvariantCultureIgnoreCase);
tl;dr
All maven POMs inherit from a base Super POM.
The snippet below is part of the Super POM for Maven 3.5.4.
<repositories>
<repository>
<id>central</id>
<name>Central Repository</name>
<url>https://repo.maven.apache.org/maven2</url>
<layout>default</layout>
<snapshots>
<enabled>false</enabled>
</snapshots>
</repository>
</repositories>
I was playing around with cmder (http://gooseberrycreative.com/cmder/) and I wanted to count the lines of html,css,java and javascript. While some of the answers above worked, or
pattern in grep didn't - I found here (https://unix.stackexchange.com/questions/37313/how-do-i-grep-for-multiple-patterns) that I had to escape it
So this is what I use now:
git ls-files | grep "\(.html\|.css\|.js\|.java\)$" | xargs wc -l
I came to this question but it turned out my problem was that I was using setInterval when I should have been using the angular $interval provider. This is also the case for setTimeout (use $timeout instead). I know it's not the answer to the OP's question, but it might help some, as it helped me.
You should initialize yours recordings. You are passing to adapter null
ArrayList<String> recordings = null; //You are passing this null
Let's assume this is your class:
class Test
{
private $baz = 1;
public function foo() { ... }
public function bar()
{
printf("baz = %d\n", $this->baz);
}
public static function staticMethod() { echo "static method\n"; }
}
From within the foo()
method, let's look at the different options:
$this->staticMethod();
So that calls staticMethod()
as an instance method, right? It does not. This is because the method is declared as public static
the interpreter will call it as a static method, so it will work as expected. It could be argued that doing so makes it less obvious from the code that a static method call is taking place.
$this::staticMethod();
Since PHP 5.3 you can use $var::method()
to mean <class-of-$var>::
; this is quite convenient, though the above use-case is still quite unconventional. So that brings us to the most common way of calling a static method:
self::staticMethod();
Now, before you start thinking that the ::
is the static call operator, let me give you another example:
self::bar();
This will print baz = 1
, which means that $this->bar()
and self::bar()
do exactly the same thing; that's because ::
is just a scope resolution operator. It's there to make parent::
, self::
and static::
work and give you access to static variables; how a method is called depends on its signature and how the caller was called.
To see all of this in action, see this 3v4l.org output.
using select-object
for example:
Get-ADUser -Filter * -SearchBase 'OU=Users & Computers, DC=aaaaaaa, DC=com' -Properties DisplayName | select -expand displayname | Export-CSV "ADUsers.csv"
In case you are getting this in the eclipse IDE, even after setting the parameters
--launcher.XXMaxPermSize
, -XX:MaxPermSize
, etc, still if you are getting the same error, it most likely is that the eclipse is using a buggy version of JRE which would have been installed by some third party applications and set to default. These buggy versions do not pick up the PermSize parameters and so no matter whatever you set, you still keep getting these memory errors. So, in your eclipse.ini add the following parameters:
-vm <path to the right JRE directory>/<name of javaw executable>
Also make sure you set the default JRE in the preferences in the eclipse to the correct version of java.
Here's an example where the absence of b
would throw a TypeError
exception in Python 3.x
>>> f=open("new", "wb")
>>> f.write("Hello Python!")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'str' does not support the buffer interface
Adding a b
prefix would fix the problem.
Preface - a note on compatibility: other answers may only work in Python 2 - this answer should work perfectly well in Python 2 and 3. If writing Python 3 only, you might leave out explicitly inheriting from object
, but otherwise the code should remain the same.
Adding a Method to an Existing Object Instance
I've read that it is possible to add a method to an existing object (e.g. not in the class definition) in Python.
I understand that it's not always a good decision to do so. But, how might one do this?
I don't recommend this. This is a bad idea. Don't do it.
Here's a couple of reasons:
Thus, I suggest that you not do this unless you have a really good reason. It is far better to define the correct method in the class definition or less preferably to monkey-patch the class directly, like this:
Foo.sample_method = sample_method
Since it's instructive, however, I'm going to show you some ways of doing this.
Here's some setup code. We need a class definition. It could be imported, but it really doesn't matter.
class Foo(object):
'''An empty class to demonstrate adding a method to an instance'''
Create an instance:
foo = Foo()
Create a method to add to it:
def sample_method(self, bar, baz):
print(bar + baz)
__get__
Dotted lookups on functions call the __get__
method of the function with the instance, binding the object to the method and thus creating a "bound method."
foo.sample_method = sample_method.__get__(foo)
and now:
>>> foo.sample_method(1,2)
3
First, import types, from which we'll get the method constructor:
import types
Now we add the method to the instance. To do this, we require the MethodType constructor from the types
module (which we imported above).
The argument signature for types.MethodType is (function, instance, class)
:
foo.sample_method = types.MethodType(sample_method, foo, Foo)
and usage:
>>> foo.sample_method(1,2)
3
First, we create a wrapper function that binds the method to the instance:
def bind(instance, method):
def binding_scope_fn(*args, **kwargs):
return method(instance, *args, **kwargs)
return binding_scope_fn
usage:
>>> foo.sample_method = bind(foo, sample_method)
>>> foo.sample_method(1,2)
3
A partial function applies the first argument(s) to a function (and optionally keyword arguments), and can later be called with the remaining arguments (and overriding keyword arguments). Thus:
>>> from functools import partial
>>> foo.sample_method = partial(sample_method, foo)
>>> foo.sample_method(1,2)
3
This makes sense when you consider that bound methods are partial functions of the instance.
If we try to add the sample_method in the same way as we might add it to the class, it is unbound from the instance, and doesn't take the implicit self as the first argument.
>>> foo.sample_method = sample_method
>>> foo.sample_method(1,2)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: sample_method() takes exactly 3 arguments (2 given)
We can make the unbound function work by explicitly passing the instance (or anything, since this method doesn't actually use the self
argument variable), but it would not be consistent with the expected signature of other instances (if we're monkey-patching this instance):
>>> foo.sample_method(foo, 1, 2)
3
You now know several ways you could do this, but in all seriousness - don't do this.
The output can be redirected to a text file and then read it back.
import subprocess
import os
import tempfile
def execute_to_file(command):
"""
This function execute the command
and pass its output to a tempfile then read it back
It is usefull for process that deploy child process
"""
temp_file = tempfile.NamedTemporaryFile(delete=False)
temp_file.close()
path = temp_file.name
command = command + " > " + path
proc = subprocess.run(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True)
if proc.stderr:
# if command failed return
os.unlink(path)
return
with open(path, 'r') as f:
data = f.read()
os.unlink(path)
return data
if __name__ == "__main__":
path = "Somepath"
command = 'ecls.exe /files ' + path
print(execute(command))
this worked for me:
Private Function arrIsEmpty(arr as variant)
On Error Resume Next
arrIsEmpty = False
arrIsEmpty = IsNumeric(UBound(arr))
End Function
I have a Maven3 project using JUnit 4.12 and Java8.
In order to get the path of a file called myxml.xml
under src/test/resources
, I do this from within the test case:
@Test
public void testApp()
{
File inputXmlFile = new File(this.getClass().getResource("/myxml.xml").getFile());
System.out.println(inputXmlFile.getAbsolutePath());
...
}
Tested on Ubuntu 14.04 with IntelliJ IDE. Reference here.
The problem you face is that you try to assign the return of imshow
(which is an matplotlib.image.AxesImage
to an existing axes object.
The correct way of plotting image data to the different axes in axarr
would be
f, axarr = plt.subplots(2,2)
axarr[0,0].imshow(image_datas[0])
axarr[0,1].imshow(image_datas[1])
axarr[1,0].imshow(image_datas[2])
axarr[1,1].imshow(image_datas[3])
The concept is the same for all subplots, and in most cases the axes instance provide the same methods than the pyplot (plt) interface.
E.g. if ax
is one of your subplot axes, for plotting a normal line plot you'd use ax.plot(..)
instead of plt.plot()
. This can actually be found exactly in the source from the page you link to.
Check the location whether it's the right location of the git project.
Not PIL, but imageio.imread
might still be interesting:
import imageio
im = scipy.misc.imread('um_000000.png', flatten=False, mode='RGB')
im = imageio.imread('Figure_1.png', pilmode='RGB')
print(im.shape)
gives
(480, 640, 3)
so it is (height, width, channels). So the pixel at position (x, y)
is
color = tuple(im[y][x])
r, g, b = color
scipy.misc.imread
is deprecated in SciPy 1.0.0 (thanks for the reminder, fbahr!)
Starting from this @Kartik Patel example , I have changed a little maybe now is more clear about static variable
public class Variable
{
public static string StaticName = "Sophia ";
public string nonStName = "Jenna ";
public void test()
{
StaticName = StaticName + " Lauren";
Console.WriteLine(" static ={0}",StaticName);
nonStName = nonStName + "Bean ";
Console.WriteLine(" NeStatic neSt={0}", nonStName);
}
}
class Program
{
static void Main(string[] args)
{
Variable var = new Variable();
var.test();
Variable var1 = new Variable();
var1.test();
Variable var2 = new Variable();
var2.test();
Console.ReadKey();
}
}
Output
static =Sophia Lauren
NeStatic neSt=Jenna Bean
static =Sophia Lauren Lauren
NeStatic neSt=Jenna Bean
static =Sophia Lauren Lauren Lauren
NeStatic neSt=Jenna Bean
Class Variable VS Instance Variable in C#
Static Class Members C# OR Class Variable
class A
{
// Class variable or " static member variable" are declared with
//the "static " keyword
public static int i=20;
public int j=10; //Instance variable
public static string s1="static class variable"; //Class variable
public string s2="instance variable"; // instance variable
}
class Program
{
static void Main(string[] args)
{
A obj1 = new A();
// obj1 instance variables
Console.WriteLine("obj1 instance variables ");
Console.WriteLine(A.i);
Console.WriteLine(obj1.j);
Console.WriteLine(obj1.s2);
Console.WriteLine(A.s1);
A obj2 = new A();
// obj2 instance variables
Console.WriteLine("obj2 instance variables ");
Console.WriteLine(A.i);
Console.WriteLine(obj2.j);
Console.WriteLine(obj2.s2);
Console.WriteLine(A.s1);
Console.ReadKey();
}
}
}
https://en.wikipedia.org/wiki/Class_variable
https://en.wikipedia.org/wiki/Instance_variable
In case you're interested in bundling automatically your scripts separately from vendors ones:
var webpack = require('webpack'),
pkg = require('./package.json'), //loads npm config file
html = require('html-webpack-plugin');
module.exports = {
context : __dirname + '/app',
entry : {
app : __dirname + '/app/index.js',
vendor : Object.keys(pkg.dependencies) //get npm vendors deps from config
},
output : {
path : __dirname + '/dist',
filename : 'app.min-[hash:6].js'
},
plugins: [
//Finally add this line to bundle the vendor code separately
new webpack.optimize.CommonsChunkPlugin('vendor', 'vendor.min-[hash:6].js'),
new html({template : __dirname + '/app/index.html'})
]
};
You can read more about this feature in official documentation.
in Swift 4
in cellForRowAt indexPath:
cell.prescriptionButton.addTarget(self, action: Selector("onClicked:"), for: .touchUpInside)
function that run after user pressed button:
@objc func onClicked(sender: UIButton){
let tag = sender.tag
}
Correct me if I'm mistaken, but the previous example, I believe, is just slightly out of sync with the latest version of James Newton's Json.NET library.
var o = JObject.Parse(stringFullOfJson);
var page = (int)o["page"];
var totalPages = (int)o["total_pages"];
Something like this should do it :
UPDATE table1
SET table1.Price = table2.price
FROM table1 INNER JOIN table2 ON table1.id = table2.id
You can also try this:
UPDATE table1
SET price=(SELECT price FROM table2 WHERE table1.id=table2.id);
If you're only looking for a webkit version this is nifty: http://s3.amazonaws.com/37assets/svn/463-single_spinner.html from http://37signals.com/svn/posts/2577-loading-spinner-animation-using-css-and-webkit
Simply create a Class Name and define your style there like this :
table.tdfont td {
font-size: 0.9em;
}
this
refers to the current instance of the class (object) your equals-method belongs to. When you test this
against an object, the testing method (which is equals(Object obj)
in your case) will check wether or not the object is equal to the current instance (referred to as this
).
An example:
Object obj = this; this.equals(obj); //true Object obj = this; new Object().equals(obj); //false
Several answers have pointed at uintptr_t
and #include <stdint.h>
as 'the' solution. That is, I suggest, part of the answer, but not the whole answer. You also need to look at where the function is called with the message ID of FOO.
Consider this code and compilation:
$ cat kk.c
#include <stdio.h>
static void function(int n, void *p)
{
unsigned long z = *(unsigned long *)p;
printf("%d - %lu\n", n, z);
}
int main(void)
{
function(1, 2);
return(0);
}
$ rmk kk
gcc -m64 -g -O -std=c99 -pedantic -Wall -Wshadow -Wpointer-arith \
-Wcast-qual -Wstrict-prototypes -Wmissing-prototypes \
-D_FILE_OFFSET_BITS=64 -D_LARGEFILE_SOURCE kk.c -o kk
kk.c: In function 'main':
kk.c:10: warning: passing argument 2 of 'func' makes pointer from integer without a cast
$
You will observe that there is a problem at the calling location (in main()
) — converting an integer to a pointer without a cast. You are going to need to analyze your function()
in all its usages to see how values are passed to it. The code inside my function()
would work if the calls were written:
unsigned long i = 0x2341;
function(1, &i);
Since yours are probably written differently, you need to review the points where the function is called to ensure that it makes sense to use the value as shown. Don't forget, you may be finding a latent bug.
Also, if you are going to format the value of the void *
parameter (as converted), look carefully at the <inttypes.h>
header (instead of stdint.h
— inttypes.h
provides the services of stdint.h
, which is unusual, but the C99 standard says [t]he header <inttypes.h>
includes the header <stdint.h>
and extends it with
additional facilities provided by hosted implementations) and use the PRIxxx macros in your format strings.
Also, my comments are strictly applicable to C rather than C++, but your code is in the subset of C++ that is portable between C and C++. The chances are fair to good that my comments apply.
I used this way in my code
$(function(){
$('.block').affix();
})
This should work
function validate() {
if ($('#remeber').is(':checked')) {
alert("checked");
} else {
alert("You didn't check it! Let me check it for you.");
}
}
Use aapt
from the SDK like
aapt dump badging yourpkg.apk
This will print the package name together with other info.
the tools is located in
<sdk_home>/build-tools/android-<api_level>
or
<sdk_home>/platform-tools
or
<sdk_home>/platforms/android-<api_level>/tools
Updated according to geniusburger's comment. Thanks!
You can process your output synchronously or asynchronously.
1. Synchronous example
static void runCommand()
{
Process process = new Process();
process.StartInfo.FileName = "cmd.exe";
process.StartInfo.Arguments = "/c DIR"; // Note the /c command (*)
process.StartInfo.UseShellExecute = false;
process.StartInfo.RedirectStandardOutput = true;
process.StartInfo.RedirectStandardError = true;
process.Start();
//* Read the output (or the error)
string output = process.StandardOutput.ReadToEnd();
Console.WriteLine(output);
string err = process.StandardError.ReadToEnd();
Console.WriteLine(err);
process.WaitForExit();
}
Note that it's better to process both output and errors: they must be handled separately.
(*) For some commands (here StartInfo.Arguments
) you must add the /c
directive, otherwise the process freezes in the WaitForExit()
.
2. Asynchronous example
static void runCommand()
{
//* Create your Process
Process process = new Process();
process.StartInfo.FileName = "cmd.exe";
process.StartInfo.Arguments = "/c DIR";
process.StartInfo.UseShellExecute = false;
process.StartInfo.RedirectStandardOutput = true;
process.StartInfo.RedirectStandardError = true;
//* Set your output and error (asynchronous) handlers
process.OutputDataReceived += new DataReceivedEventHandler(OutputHandler);
process.ErrorDataReceived += new DataReceivedEventHandler(OutputHandler);
//* Start process and handlers
process.Start();
process.BeginOutputReadLine();
process.BeginErrorReadLine();
process.WaitForExit();
}
static void OutputHandler(object sendingProcess, DataReceivedEventArgs outLine)
{
//* Do your stuff with the output (write to console/log/StringBuilder)
Console.WriteLine(outLine.Data);
}
If you don't need to do complicate operations with the output, you can bypass the OutputHandler method, just adding the handlers directly inline:
//* Set your output and error (asynchronous) handlers
process.OutputDataReceived += (s, e) => Console.WriteLine(e.Data);
process.ErrorDataReceived += (s, e) => Console.WriteLine(e.Data);
Updating to use tibble()
You can pass a named vector of length greater than 1 to the by
argument of left_join()
:
library(dplyr)
d1 <- tibble(
x = letters[1:3],
y = LETTERS[1:3],
a = rnorm(3)
)
d2 <- tibble(
x2 = letters[3:1],
y2 = LETTERS[3:1],
b = rnorm(3)
)
left_join(d1, d2, by = c("x" = "x2", "y" = "y2"))
I believe once database rules are written accurately, it will be enough to protect your data. Moreover, there are guidelines that one can follow to structure your database accordingly. For example, making a UID node under users, and putting all under information under it. After that, you will need to implement a simple database rule as below
"rules": {
"users": {
"$uid": {
".read": "auth != null && auth.uid == $uid",
".write": "auth != null && auth.uid == $uid"
}
}
}
}
No other user will be able to read other users' data, moreover, domain policy will restrict requests coming from other domains. One can read more about it on Firebase Security rules
Please see the answer by Martin Smith for a better illustations and explanations of the different joins, including and especially differences between FULL OUTER JOIN
, RIGHT OUTER JOIN
and LEFT OUTER JOIN
.
These two table form a basis for the representation of the JOIN
s below:
SELECT *
FROM citizen
CROSS JOIN postalcode
The result will be the Cartesian products of all combinations. No JOIN
condition required:
INNER JOIN
is the same as simply: JOIN
SELECT *
FROM citizen c
JOIN postalcode p ON c.postal = p.postal
The result will be combinations that satisfies the required JOIN
condition:
LEFT OUTER JOIN
is the same as LEFT JOIN
SELECT *
FROM citizen c
LEFT JOIN postalcode p ON c.postal = p.postal
The result will be everything from citizen
even if there are no matches in postalcode
. Again a JOIN
condition is required:
All examples have been run on an Oracle 18c. They're available at dbfiddle.uk which is also where screenshots of tables came from.
CREATE TABLE citizen (id NUMBER,
name VARCHAR2(20),
postal NUMBER, -- <-- could do with a redesign to postalcode.id instead.
leader NUMBER);
CREATE TABLE postalcode (id NUMBER,
postal NUMBER,
city VARCHAR2(20),
area VARCHAR2(20));
INSERT INTO citizen (id, name, postal, leader)
SELECT 1, 'Smith', 2200, null FROM DUAL
UNION SELECT 2, 'Green', 31006, 1 FROM DUAL
UNION SELECT 3, 'Jensen', 623, 1 FROM DUAL;
INSERT INTO postalcode (id, postal, city, area)
SELECT 1, 2200, 'BigCity', 'Geancy' FROM DUAL
UNION SELECT 2, 31006, 'SmallTown', 'Snizkim' FROM DUAL
UNION SELECT 3, 31006, 'Settlement', 'Moon' FROM DUAL -- <-- Uuh-uhh.
UNION SELECT 4, 78567390, 'LookoutTowerX89', 'Space' FROM DUAL;
JOIN
and WHERE
CROSS JOIN
resulting in rows as The General Idea/INNER JOIN
:
SELECT *
FROM citizen c
CROSS JOIN postalcode p
WHERE c.postal = p.postal -- < -- The WHERE condition is limiting the resulting rows
Using CROSS JOIN
to get the result of a LEFT OUTER JOIN
requires tricks like adding in a NULL
row. It's omitted.
INNER JOIN
becomes a cartesian products. It's the same as The General Idea/CROSS JOIN
:
SELECT *
FROM citizen c
JOIN postalcode p ON 1 = 1 -- < -- The ON condition makes it a CROSS JOIN
This is where the inner join can really be seen as the cross join with results not matching the condition removed. Here none of the resulting rows are removed.
Using INNER JOIN
to get the result of a LEFT OUTER JOIN
also requires tricks. It's omitted.
LEFT JOIN
results in rows as The General Idea/CROSS JOIN
:
SELECT *
FROM citizen c
LEFT JOIN postalcode p ON 1 = 1 -- < -- The ON condition makes it a CROSS JOIN
LEFT JOIN
results in rows as The General Idea/INNER JOIN
:
SELECT *
FROM citizen c
LEFT JOIN postalcode p ON c.postal = p.postal
WHERE p.postal IS NOT NULL -- < -- removed the row where there's no mathcing result from postalcode
An image internet search on "sql join cross inner outer" will show a multitude of Venn diagrams. I used to have a printed copy of one on my desk. But there are issues with the representation.
Venn diagram are excellent for set theory, where an element can be in one or both sets. But for databases, an element in one "set" seem, to me, to be a row in a table, and therefore not also present in any other tables. There is no such thing as one row present in multiple tables. A row is unique to the table.
Self joins are a corner case where each element is in fact the same in both sets. But it's still not free of any of the issues below.
The set A
represents the set on the left (the citizen
table) and the set B
is the set on the right (the postalcode
table) in below discussion.
Every element in both sets are matched with every element in the other set, meaning we need A
amount of every B
elements and B
amount of every A
elements to properly represent this Cartesian product. Set theory isn't made for multiple identical elements in a set, so I find Venn diagrams to properly represent it impractical/impossible. It doesn't seem that UNION
fits at all.
The rows are distinct. The UNION
is 7 rows in total. But they're incompatible for a common SQL
results set. And this is not how a CROSS JOIN
works at all:
Trying to represent it like this:
..but now it just looks like an INTERSECTION
, which it's certainly not. Furthermore there's no element in the INTERSECTION
that is actually in any of the two distinct sets. However, it looks very much like the searchable results similar to this:
For reference one searchable result for CROSS JOIN
s can be seen at Tutorialgateway. The INTERSECTION
, just like this one, is empty.
The value of an element depends on the JOIN
condition. It's possible to represent this under the condition that every row becomes unique to that condition. Meaning id=x
is only true for one row. Once a row in table A
(citizen
) matches multiple rows in table B
(postalcode
) under the JOIN
condition, the result has the same problems as the CROSS JOIN
: The row needs to be represented multiple times, and the set theory isn't really made for that. Under the condition of uniqueness, the diagram could work though, but keep in mind that the JOIN
condition determines the placement of an element in the diagram. Looking only at the values of the JOIN
condition with the rest of the row just along for the ride:
This representation falls completely apart when using an INNER JOIN
with a ON 1 = 1
condition making it into a CROSS JOIN
.
With a self-JOIN
, the rows are in fact idential elements in both tables, but representing the tables as both A
and B
isn't very suitable. For example a common self-JOIN
condition that makes an element in A
to be matching a different element in B is ON A.parent = B.child
, making the match from A
to B
on seperate elements. From the examples that would be a SQL
like this:
SELECT *
FROM citizen c1
JOIN citizen c2 ON c1.id = c2.leader
Meaning Smith is the leader of both Green and Jensen.
Again the troubles begin when one row has multiple matches to rows in the other table. This is further complicated because the OUTER JOIN
can be though of as to match the empty set. But in set theory the union of any set C
and an empty set, is always just C
. The empty set adds nothing. The representation of this LEFT OUTER JOIN
is usually just showing all of A
to illustrate that rows in A
are selected regardless of whether there is a match or not from B
. The "matching elements" however has the same problems as the illustration above. They depend on the condition. And the empty set seems to have wandered over to A
:
Finding all rows from a CROSS JOIN
with Smith and postalcode on the Moon:
SELECT *
FROM citizen c
CROSS JOIN postalcode p
WHERE c.name = 'Smith'
AND p.area = 'Moon';
Now the Venn diagram isn't used to reflect the JOIN
. It's used only for the WHERE
clause:
..and that makes sense.
As explained an INNER JOIN
is not really an INTERSECT
. However INTERSECT
s can be used on results of seperate queries. Here a Venn diagram makes sense, because the elements from the seperate queries are in fact rows that either belonging to just one of the results or both. Intersect will obviously only return results where the row is present in both queries. This SQL
will result in the same row as the one above WHERE
, and the Venn diagram will also be the same:
SELECT *
FROM citizen c
CROSS JOIN postalcode p
WHERE c.name = 'Smith'
INTERSECT
SELECT *
FROM citizen c
CROSS JOIN postalcode p
WHERE p.area = 'Moon';
An OUTER JOIN
is not a UNION
. However UNION
work under the same conditions as INTERSECT
, resulting in a return of all results combining both SELECT
s:
SELECT *
FROM citizen c
CROSS JOIN postalcode p
WHERE c.name = 'Smith'
UNION
SELECT *
FROM citizen c
CROSS JOIN postalcode p
WHERE p.area = 'Moon';
which is equivalent to:
SELECT *
FROM citizen c
CROSS JOIN postalcode p
WHERE c.name = 'Smith'
OR p.area = 'Moon';
..and gives the result:
Also here a Venn diagram makes sense:
An important note is that these only work when the structure of the results from the two SELECT's are the same, enabling a comparison or union. The results of these two will not enable that:
SELECT *
FROM citizen
WHERE name = 'Smith'
SELECT *
FROM postalcode
WHERE area = 'Moon';
..trying to combine the results with UNION
gives a
ORA-01790: expression must have same datatype as corresponding expression
For further interest read Say NO to Venn Diagrams When Explaining JOINs and sql joins as venn diagram. Both also cover EXCEPT
.
Since this is a top hit on Google, I'd like to give an updated answer.
Using ES6 classes makes inheritance and method overriding a lot easier:
'use strict';
class A {
speak() {
console.log("I'm A");
}
}
class B extends A {
speak() {
super.speak();
console.log("I'm B");
}
}
var a = new A();
a.speak();
// Output:
// I'm A
var b = new B();
b.speak();
// Output:
// I'm A
// I'm B
The super
keyword refers to the parent class when used in the inheriting class. Also, all methods on the parent class are bound to the instance of the child, so you don't have to write super.method.apply(this);
.
As for compatibility: the ES6 compatibility table shows only the most recent versions of the major players support classes (mostly). V8 browsers have had them since January of this year (Chrome and Opera), and Firefox, using the SpiderMonkey JS engine, will see classes next month with their official Firefox 45 release. On the mobile side, Android still does not support this feature, while iOS 9, release five months ago, has partial support.
Fortunately, there is Babel, a JS library for re-compiling Harmony code into ES5 code. Classes, and a lot of other cool features in ES6 can make your Javascript code a lot more readable and maintainable.
wmic bios get serialnumber
if run from a command line (start-run should also do the trick) prints out on screen the Serial Number of the product,
(for example in a toshiba laptop it would print out the serial number of the laptop.
with this serial number you can then identify your laptop model if you need ,from the makers service website-usually..:):)
I had to do exactly that.:):)
You can use this simple method like :
qsFromDate = '2017-05-10';
$("#dtMinDate").datepicker("setDate", new Date(qsFromDate));
$('#dtMinDate').datepicker('update');
Add
[config]="{backdrop: 'static'}"
to the model code.
find /the_path_you_want_to_find -name index.html
You can use property dangerouslySetInnerHTML
, like this
const Component = React.createClass({_x000D_
iframe: function () {_x000D_
return {_x000D_
__html: this.props.iframe_x000D_
}_x000D_
},_x000D_
_x000D_
render: function() {_x000D_
return (_x000D_
<div>_x000D_
<div dangerouslySetInnerHTML={ this.iframe() } />_x000D_
</div>_x000D_
);_x000D_
}_x000D_
});_x000D_
_x000D_
const iframe = '<iframe src="https://www.example.com/show?data..." width="540" height="450"></iframe>'; _x000D_
_x000D_
ReactDOM.render(_x000D_
<Component iframe={iframe} />,_x000D_
document.getElementById('container')_x000D_
);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>_x000D_
<div id="container"></div>
_x000D_
also, you can copy all attributes from the string(based on the question, you get iframe as a string from a server) which contains <iframe>
tag and pass it to new <iframe>
tag, like that
/**_x000D_
* getAttrs_x000D_
* returns all attributes from TAG string_x000D_
* @return Object_x000D_
*/_x000D_
const getAttrs = (iframeTag) => {_x000D_
var doc = document.createElement('div');_x000D_
doc.innerHTML = iframeTag;_x000D_
_x000D_
const iframe = doc.getElementsByTagName('iframe')[0];_x000D_
return [].slice_x000D_
.call(iframe.attributes)_x000D_
.reduce((attrs, element) => {_x000D_
attrs[element.name] = element.value;_x000D_
return attrs;_x000D_
}, {});_x000D_
}_x000D_
_x000D_
const Component = React.createClass({_x000D_
render: function() {_x000D_
return (_x000D_
<div>_x000D_
<iframe {...getAttrs(this.props.iframe) } />_x000D_
</div>_x000D_
);_x000D_
}_x000D_
});_x000D_
_x000D_
const iframe = '<iframe src="https://www.example.com/show?data..." width="540" height="450"></iframe>'; _x000D_
_x000D_
ReactDOM.render(_x000D_
<Component iframe={iframe} />,_x000D_
document.getElementById('container')_x000D_
);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>_x000D_
<div id="container"><div>
_x000D_
That's right. If you create a shelf, other people doing a get latest won't see your code.
It puts your code changes onto the server, which is probably better backed up than your work PC.
It enables you to pick up your changes on another machine, should you feel the urge to work from home.
Others can see your shelves (though I think this may be optional) so they can review your code prior to a check-in.
It's been a while since I C++'d but these answers are off a bit.
As far as the size goes, 'int' isn't anything. It's a notional value of a standard integer; assumed to be fast for purposes of things like iteration. It doesn't have a preset size.
So, the answers are correct with respect to the differences between int and uint, but are incorrect when they talk about "how large they are" or what their range is. That size is undefined, or more accurately, it will change with the compiler and platform.
It's never polite to discuss the size of your bits in public.
When you compile a program, int does have a size, as you've taken the abstract C/C++ and turned it into concrete machine code.
So, TODAY, practically speaking with most common compilers, they are correct. But do not assume this.
Specifically: if you're writing a 32 bit program, int will be one thing, 64 bit, it can be different, and 16 bit is different. I've gone through all three and briefly looked at 6502 shudder
A brief google search shows this: https://www.tutorialspoint.com/cprogramming/c_data_types.htm This is also good info: https://docs.oracle.com/cd/E19620-01/805-3024/lp64-1/index.html
use int if you really don't care how large your bits are; it can change.
Use size_t and ssize_t if you want to know how large something is.
If you're reading or writing binary data, don't use int. Use a (usually platform/source dependent) specific keyword. WinSDK has plenty of good, maintainable examples of this. Other platforms do too.
I've spent a LOT of time going through code from people that "SMH" at the idea that this is all just academic/pedantic. These ate the people that write unmaintainable code. Sure, it's easy to use type 'int' and use it without all the extra darn typing. It's a lot of work to figure out what they really meant, and a bit mind-numbing.
It's crappy coding when you mix int.
use int and uint when you just want a fast integer and don't care about the range (other than signed/unsigned).
I created this library JS PHP Import which you can download from github, and use whenever and wherever you want.
The library allows importing php functions and class methods into javascript browser environment thus they can be accessed as javascript functions and methods by using their actual names. The code uses javascript promises so you can chain functions returns.
I hope it may useful to you.
Example:
<script>
$scandir(PATH_TO_FOLDER).then(function(result) {
resultObj.html(result.join('<br>'));
});
$system('ls -l').then(function(result) {
resultObj.append(result);
});
$str_replace(' ').then(function(result) {
resultObj.append(result);
});
// Chaining functions
$testfn(34, 56).exec(function(result) { // first call
return $testfn(34, result); // second call with the result of the first call as a parameter
}).exec(function(result) {
resultObj.append('result: ' + result + '<br><br>');
});
</script>
My solution to the problem got WA(wrong answer), then i changed one of int
to long long int
and it gave AC(accept). Previously, I was trying to do long long int += int * int
, and after I rectify it to long long int += long long int * int
. Googling I came up with,
Conditions for Type Conversion:
Conditions Met ---> Conversion
Either operand is of type long double. ---> Other operand is converted to type long double.
Preceding condition not met and either operand is of type double. ---> Other operand is converted to type double.
Preceding conditions not met and either operand is of type float. ---> Other operand is converted to type float.
Preceding conditions not met (none of the operands are of floating types). ---> Integral promotions are performed on the operands as follows:
Integer types smaller than int are promoted when an operation is performed on them. If all values of the original type can be represented as an int, the value of the smaller type is converted to an int; otherwise, it is converted to an unsigned int. Integer promotions are applied as part of the usual arithmetic conversions to certain argument expressions; operands of the unary +, -, and ~ operators; and operands of the shift operators.
Integer Conversion Rank:
long long int
shall be greater than the rank of long int
, which shall be greater than the rank of int
, which shall be greater than the rank of short int
, which shall be greater than the rank of signed char
.char
shall equal the rank of signed char
and unsigned char
.Usual Arithmetic Conversions:
After inspecting the sample website you provided, I found that the author might achieve the effect by using a library called Stellar.js, take a look at the library site, cheers!
A nice approach that i have seen often and I had been used actually is to inject some NULL type element (or a created one, like uint THIS_IS_INFINITY = 82862863263;
) at end of the array.
Then at the loop condition check, TYPE *pagesWords
is some kind of pointer array:
int pagesWordsLength = sizeof(pagesWords) / sizeof(pagesWords[0]);
realloc (pagesWords, sizeof(pagesWords[0]) * (pagesWordsLength + 1);
pagesWords[pagesWordsLength] = MY_NULL;
for (uint i = 0; i < 1000; i++)
{
if (pagesWords[i] == MY_NULL)
{
break;
}
}
This solution won't word if array is filled with struct
types.
It works, when you use both lines:
Application.ActiveWorkbook.Worksheets("data").Range("C1", "C20000") = Format(Date, "yyyy-mm-dd")
Application.ActiveWorkbook.Worksheets("data").Range("C1", "C20000").NumberFormat = "yyyy-mm-dd"
You can set the context to be poster
or manually set fig_size
.
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
np.random.seed(0)
n, p = 40, 8
d = np.random.normal(0, 2, (n, p))
d += np.log(np.arange(1, p + 1)) * -5 + 10
# plot
sns.set_style('ticks')
fig, ax = plt.subplots()
# the size of A4 paper
fig.set_size_inches(11.7, 8.27)
sns.violinplot(data=d, inner="points", ax=ax)
sns.despine()
fig.savefig('example.png')
git reset is what you want, but I'm going to add a couple extra things you might find useful that the other answers didn't mention.
git reset --hard HEAD
resets your changes back to the last commit that your local repo has tracked. If you made a commit, did not push it to GitHub, and want to throw that away too, see @absiddiqueLive's answer.
git clean -df
will discard any new files or directories that you may have added, in case you want to throw those away. If you haven't added any, you don't have to run this.
git pull
(or if you are using git shell with the GitHub client) git sync
will get the new changes from GitHub.
Edit from way in the future:
I updated my git shell the other week and noticed that the git sync
command is no longer defined by default. For the record, typing git sync
was equivalent to git pull && git push
in bash. I find it still helpful so it is in my bashrc.
try to send content type header from server use this just before echoing
header('Content-Type: application/json');
Handles either type of line break
str.replace(new RegExp('\r?\n','g'), '<br />');
If you have a complicated folder structure, such as
- Your application
- assets
- images
- profile.jpg
- web
- server
- index.js
If you want to serve assets/images
from index.js
app.use('/images', express.static(path.join(__dirname, '..', 'assets', 'images')))
To view from your browser
http://localhost:4000/images/profile.jpg
If you need more clarification comment, I'll elaborate.
That data:image/png;base64
URL is cool, I’ve never run into it before. The long encrypted link is the actual image, i.e. no image call to the server. See RFC 2397 for details.
Side note: I have had trouble getting larger base64 images to render on IE8. I believe IE8 has a 32K limit that can be problematic for larger files. See this other StackOverflow thread for details.
Set an environment variable called ASPNETCORE_ENVIRONMENT
with the name of the environment (e.g. Production
). Then do one of two things:
IHostingEnvironment
into Startup.cs
, then use that (env
here) to check: env.IsEnvironment("Production")
. Do not check using env.EnvironmentName == "Production"
!Startup
classes or individual Configure
/ConfigureServices
functions. If a class or the functions match these formats, they will be used instead of the standard options on that environment.
Startup{EnvironmentName}()
(entire class) || example: StartupProduction()
Configure{EnvironmentName}()
|| example: ConfigureProduction()
Configure{EnvironmentName}Services()
|| example: ConfigureProductionServices()
The .NET Core docs describe how to accomplish this. Use an environment variable called ASPNETCORE_ENVIRONMENT
that's set to the environment you want, then you have two choices.
The
IHostingEnvironment
service provides the core abstraction for working with environments. This service is provided by the ASP.NET hosting layer, and can be injected into your startup logic via Dependency Injection. The ASP.NET Core web site template in Visual Studio uses this approach to load environment-specific configuration files (if present) and to customize the app’s error handling settings. In both cases, this behavior is achieved by referring to the currently specified environment by callingEnvironmentName
orIsEnvironment
on the instance ofIHostingEnvironment
passed into the appropriate method.
NOTE: Checking the actual value of env.EnvironmentName
is not recommended!
If you need to check whether the application is running in a particular environment, use
env.IsEnvironment("environmentname")
since it will correctly ignore case (instead of checking ifenv.EnvironmentName == "Development"
for example).
When an ASP.NET Core application starts, the
Startup
class is used to bootstrap the application, load its configuration settings, etc. (learn more about ASP.NET startup). However, if a class exists namedStartup{EnvironmentName}
(for exampleStartupDevelopment
), and theASPNETCORE_ENVIRONMENT
environment variable matches that name, then thatStartup
class is used instead. Thus, you could configureStartup
for development, but have a separateStartupProduction
that would be used when the app is run in production. Or vice versa.In addition to using an entirely separate
Startup
class based on the current environment, you can also make adjustments to how the application is configured within aStartup
class. TheConfigure()
andConfigureServices()
methods support environment-specific versions similar to theStartup
class itself, of the formConfigure{EnvironmentName}()
andConfigure{EnvironmentName}Services()
. If you define a methodConfigureDevelopment()
it will be called instead ofConfigure()
when the environment is set to development. Likewise,ConfigureDevelopmentServices()
would be called instead ofConfigureServices()
in the same environment.
Yes:
test2.removeAll(test1)
Although this will mutate test2
, so create a copy if you need to preserve it.
Also, you probably meant <Integer>
instead of <int>
.
Complementing in C# with SQL:
SqlConnection conn = new SqlConnection("ConnectionString");
conn.Open();
SqlCommand comm = new SqlCommand("SELECT COUNT(*) FROM table_name", conn);
Int32 count = Convert.ToInt32(comm.ExecuteScalar());
if (count > 0)
{
lblCount.Text = Convert.ToString(count.ToString()); //For example a Label
}
else
{
lblCount.Text = "0";
}
conn.Close(); //Remember close the connection
I had a different approach , used bootstrap panel to show it little more rich. Just to help someone and improve the answer.
.text-on-pannel {_x000D_
background: #fff none repeat scroll 0 0;_x000D_
height: auto;_x000D_
margin-left: 20px;_x000D_
padding: 3px 5px;_x000D_
position: absolute;_x000D_
margin-top: -47px;_x000D_
border: 1px solid #337ab7;_x000D_
border-radius: 8px;_x000D_
}_x000D_
_x000D_
.panel {_x000D_
/* for text on pannel */_x000D_
margin-top: 27px !important;_x000D_
}_x000D_
_x000D_
.panel-body {_x000D_
padding-top: 30px !important;_x000D_
}
_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />_x000D_
<div class="container">_x000D_
<div class="panel panel-primary">_x000D_
<div class="panel-body">_x000D_
<h3 class="text-on-pannel text-primary"><strong class="text-uppercase"> Title </strong></h3>_x000D_
<p> Your Code </p>_x000D_
</div>_x000D_
</div>_x000D_
<div>
_x000D_
Note: We need to change the styles in order to use different header size.
If you want to add the driver paths on Windows 10:
Right click on the "This PC" icon and select "Properties"
Click on “Advanced System Settings”
Click on “Environment Variables” at the bottom of the screen
In the “User Variables” section highlight “Path” and click “Edit”
Add the paths to your variables by clicking “New” and typing in the path for the driver you are adding and hitting enter.
Once you done entering in the path, click “OK”
Keep clicking “OK” until you have closed out all the screens
As default, the first vagrant instance use ssh port as 2222, and its ip address is 127.0.0.1 (You may need adjust the port with real virtual host)
==> default: Forwarding ports...
default: 22 (guest) => 2222 (host) (adapter 1)
So you can run below command to copy your local file to vagrant instance. password is the same as username which is vagrant
.
scp -P 2222 your_file [email protected]:.
You can also copy the file back to your local host.
scp -P 2222 [email protected]:/PATH/filename .
Now for the missing class problem.
I'm an Eclipse Java EE developer and have been in the habit for many years of adding third-party libraries via the "User Library" mechanism in Build Path. Of course, there are at least 3 ways to add a third-party library, the one I use is the most elegant, in my humble opinion.
This will not work, however, for Android, whose Dalvik "JVM" cannot handle an ordinary Java-compiled class, but must have it converted to a special format. This does not happen when you add a library in the way I'm wont to do it.
Instead, follow the (widely available) instructions for importing the third-party library, then adding it using Build Path (which makes it known to Eclipse for compilation purposes). Here is the step-by-step:
NOTE
Step 5 may not be needed, if the lib is already included in your build path. Just ensure that its existence first before adding it.
What you've done here accomplishes two things:
I marked OregonGhost's answer +1, then I tried to use the iteration and realised it wasn't quite right because Enum.GetNames returns strings. You want Enum.GetValues:
public MyColours GetColours(string colour)
{
foreach (MyColours mc in Enum.GetValues(typeof(MyColours)))
if (mc.ToString() == surveySystem)
return mc;
return MyColors.Default;
}
While you asked how to kill a window resp. pane, I often wouldn't want to kill it but simply to get it back to a working state (the layout of panes is of importance to me, killing a pane destroys it so I must recreate it); tmux provides the respawn
commands to that effect: respawn-pane
resp. respawn-window
. Just that people like me may find this solution here.
The default schema for the user could be changed with the following query and avoids changing the property every time a table is to be created.
USE [DBName]
GO
ALTER USER [YourUserName] WITH DEFAULT_SCHEMA = [YourSchema]
GO
If you don't assume the 32-bit constraint, just return a randomly generated 64-bit number (or 128-bit if you're a pessimist). The chance of collision is 1 in 2^64/(4*10^9) = 4611686018.4
(roughly 1 in 4 billion). You'd be right most of the time!
(Joking... kind of.)
Including all referenced DLL files from your projectreferences in the Website project is not always a good idea, especially when you're using dependency injection: your web project just want to add a reference to the interface DLL file/project, not any concrete implementation DLL file.
Because if you add a reference directly to an implementation DLL file/project, you can't prevent your developer from calling a "new" on concrete classes of the implementation DLL file/project instead of via the interface. It's also you've stated a "hardcode" in your website to use the implementation.
I have done with below single git command:
git clone [url] -b [branch-name] --single-branch
IMHO returning a null
is a bad solution because now you have the problem of sending and interpreting it at the (likely) front end client.
I had the same error and I solved it by simply returning a List<FooObject>
.
I used JDBCTemplate.query()
.
At the front end (Angular web client), I simply examine the list and if it is empty (of zero length), treat it as no records found.
Unicode escapes only work in unicode strings, so this
a="\u2026"
is actually a string of 6 characters: '\', 'u', '2', '0', '2', '6'.
To make unicode out of this, use decode('unicode-escape')
:
a="\u2026"
print repr(a)
print repr(a.decode('unicode-escape'))
## '\\u2026'
## u'\u2026'
When in doubt, follow MVC conventions.
Create a viewModel if you haven't already that contains a property for JobID
public class Model
{
public string JobId {get; set;}
public IEnumerable<MyCurrentModel> myCurrentModel { get; set; }
//...any other properties you may need
}
Strongly type your view
@model Fully.Qualified.Path.To.Model
Add a hidden field for JobId to the form
using (@Html.BeginForm("myMethod", "Home", FormMethod.Post))
{
//...
@Html.HiddenFor(m => m.JobId)
}
And accept the model as the parameter in your controller action:
[HttpPost]
public FileStreamResult myMethod(Model model)
{
sting str = model.JobId;
}
>>> average = [1,3,2,1,1,0,24,23,7,2,727,2,7,68,7,83,2]
>>> matches = [i for i in range(0,len(average)) if average[i]<2 or average[i]>4]
>>> matches
[0, 3, 4, 5, 6, 7, 8, 10, 12, 13, 14, 15]
You are doing mistake in "configuration_page.jsp" file. here in this file , function loadXMLDoc() 's line number 2 should be like this:
var config=document.getElementsByName('configselect').value;
because you have declared only the name
attribute in your <select>
tag. So you should get this element by name.
After correcting this, it will run without any JavaScript error
Quick and dirty version:
byte[] fileBytes = File.ReadAllBytes(inputFilename);
StringBuilder sb = new StringBuilder();
foreach(byte b in fileBytes)
{
sb.Append(Convert.ToString(b, 2).PadLeft(8, '0'));
}
File.WriteAllText(outputFilename, sb.ToString());
Just do System.out.println(e.getActionCommand());
inside actionPerformed(ActionEvent e)
function. This will tell you which command is just performed.
or
if(e.getActionCommand().equals("Add")){
System.out.println("Add button pressed");
}
Usage depends on whether the component's parent has a layout manager or not.
setSize()
-- use when a parent layout manager does not exist;setPreferredSize()
(also its related setMinimumSize
and setMaximumSize
) -- use when a parent layout manager exists.The setSize()
method probably won't do anything if the component's parent is using a layout manager; the places this will typically have an effect would be on top-level components (JFrame
s and JWindow
s) and things that are inside of scrolled panes. You also must call setSize()
if you've got components inside a parent without a layout manager.
Generally, setPreferredSize()
will lay out the components as expected if a layout manager is present; most layout managers work by getting the preferred (as well as minimum and maximum) sizes of their components, then using setSize()
and setLocation()
to position those components according to the layout's rules.
For example, a BorderLayout
tries to make the bounds of its "north" region equal to the preferred size of its north component---they may end up larger or smaller than that, depending on the size of the JFrame
, the size of the other components in the layout, and so on.
You can use 100vw
(viewport width). 100vw
means 100% of the viewport. vw
is supported by all major browsers, including IE9+.
<div id="container" style="width: 960px">
<div id="help_panel" style="width: 100vw; margin: 0 auto;">
Content goes here.
</div>
</div>
The other answer is correct, but for completeness, here are other ways:
List<SomeClass> list = mapper.readValue(jsonString, new TypeReference<List<SomeClass>>() { });
SomeClass[] array = mapper.readValue(jsonString, SomeClass[].class);
I would suggest better cek first if the current page has a hash. Otherwise it will be undefined
.
$(window).on('load', function(){
if( location.hash && location.hash.length ) {
var hash = decodeURIComponent(location.hash.substr(1));
$('ul'+hash+':first').show();;
}
});
The iterator of _.each
is called with 3 parameters (element, index, list)
. So yes, for _.each
you cab get the index.
You can do the same in sortBy
For simple UTF-8 encoding, with slightly better compatibility than TextEncoder
, Blob does the trick. Won't work in very old browsers though.
new Blob([""]).size; // -> 4
I think it would be better to write like this.
git rm --cache *//UserInterfaceState.xcuserstate**
You don't need to convert it. List<T>
implements the IEnumerable<T>
interface so it is already an enumerable.
This means that it is perfectly fine to have the following:
public IEnumerable<Book> GetBooks()
{
List<Book> books = FetchEmFromSomewhere();
return books;
}
as well as:
public void ProcessBooks(IEnumerable<Book> books)
{
// do something with those books
}
which could be invoked:
List<Book> books = FetchEmFromSomewhere();
ProcessBooks(books);
You can try setting preferred-install
to "dist"
in Composer config.
Heap allocations are possible for static variables if you use the lazy_static macro as seen in the docs
Using this macro, it is possible to have statics that require code to be executed at runtime in order to be initialized. This includes anything requiring heap allocations, like vectors or hash maps, as well as anything that requires function calls to be computed.
// Declares a lazily evaluated constant HashMap. The HashMap will be evaluated once and
// stored behind a global static reference.
use lazy_static::lazy_static;
use std::collections::HashMap;
lazy_static! {
static ref PRIVILEGES: HashMap<&'static str, Vec<&'static str>> = {
let mut map = HashMap::new();
map.insert("James", vec!["user", "admin"]);
map.insert("Jim", vec!["user"]);
map
};
}
fn show_access(name: &str) {
let access = PRIVILEGES.get(name);
println!("{}: {:?}", name, access);
}
fn main() {
let access = PRIVILEGES.get("James");
println!("James: {:?}", access);
show_access("Jim");
}
Swift doesn't have its own Date type, but you to use the existing Cocoa NSDate
type, e.g:
class Date {
class func from(year: Int, month: Int, day: Int) -> Date {
let gregorianCalendar = NSCalendar(calendarIdentifier: .gregorian)!
var dateComponents = DateComponents()
dateComponents.year = year
dateComponents.month = month
dateComponents.day = day
let date = gregorianCalendar.date(from: dateComponents)!
return date
}
class func parse(_ string: String, format: String = "yyyy-MM-dd") -> Date {
let dateFormatter = DateFormatter()
dateFormatter.timeZone = NSTimeZone.default
dateFormatter.dateFormat = format
let date = dateFormatter.date(from: string)!
return date
}
}
Which you can use like:
var date = Date.parse("2014-05-20")
var date = Date.from(year: 2014, month: 05, day: 20)
You should install the mysql
first:
yum install python-devel mysql-community-devel -y
Then you can install mysqlclient
:
pip install mysqlclient
Once logged in to cqlsh or cassandra-cli. run below commands
desc keyspaces;
or
describe keyspaces;
or
select * from system_schema.keyspaces;
show keyspaces;
Use the built-in timestamps
option for your Schema.
var ItemSchema = new Schema({
name: { type: String, required: true, trim: true }
},
{
timestamps: true
});
This will automatically add createdAt
and updatedAt
fields to your schema.
http://www.amk.ca/python/writing/DB-API.html
Be careful when you simply append values of variables to your statements:
Imagine a user naming himself ';DROP TABLE Users;'
--
That's why you need to use sql escaping, which Python provides for you when you use the cursor.execute in a decent manner. Example in the url is:
cursor.execute("insert into Attendees values (?, ?, ?)", (name,
seminar, paid) )
First composer requires doctrine/dbal
, then:
$table->longText('column_name')->change();
Well, I figured it out myself, right after posting, which is the most embarassing way. :)
It seems every member of a StackPanel will simply fill its minimum requested size.
In the DockPanel, I had docked things in the wrong order. If the TextBox or ListBox is the only docked item without an alignment, or if they are the last added, they WILL fill the remaining space as wanted.
I would love to see a more elegant method of handling this, but it will do.
You can check with String == null
This works for me
String foo = null;
if(foo == null){
System.out.println("String is null");
}
View -> Datasets (bottom of menu, above Refresh)
The reason DISTINCT
and GROUP BY
work on entire rows is that your query returns entire rows.
To help you understand: Try to write out by hand what the query should return and you will see that it is ambiguous what to put in the non-duplicated columns.
If you literally don't care what is in the other columns, don't return them. Returning a random row for each e-mail address seems a little useless to me.
Ok I've done it. I'm sharing this code in case someone else will need it:
super.draw(canvas, mapView, true);
Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
paint.setStrokeWidth(2);
paint.setColor(android.graphics.Color.RED);
paint.setStyle(Paint.Style.FILL_AND_STROKE);
paint.setAntiAlias(true);
Point point1_draw = new Point();
Point point2_draw = new Point();
Point point3_draw = new Point();
mapView.getProjection().toPixels(point1, point1_draw);
mapView.getProjection().toPixels(point2, point2_draw);
mapView.getProjection().toPixels(point3, point3_draw);
Path path = new Path();
path.setFillType(Path.FillType.EVEN_ODD);
path.moveTo(point1_draw.x,point1_draw.y);
path.lineTo(point2_draw.x,point2_draw.y);
path.lineTo(point3_draw.x,point3_draw.y);
path.lineTo(point1_draw.x,point1_draw.y);
path.close();
canvas.drawPath(path, paint);
//canvas.drawLine(point1_draw.x,point1_draw.y,point2_draw.x,point2_draw.y, paint);
return true;
Thanks for the hint Nicolas!
You have to do a result.next() before you can access the result. It's a very common idiom to do
ResultSet rs = stmt.executeQuery();
while (rs.next())
{
int foo = rs.getInt(1);
...
}
How I can get rid of it so it doesnt display it?
People here are trying to tell you that it's unprofessional (and it is), but in your case you should simply add following to the start of your application:
error_reporting(E_ERROR|E_WARNING);
This will disable E_NOTICE reporting. E_NOTICES are not errors, but notices, as the name says. You'd better check this stuff out and proof that undefined variables don't lead to errors. But the common case is that they are just informal, and perfectly normal for handling form input with PHP.
Also, next time Google the error message first.
There is a better solution now: Vertical align anything with just 3 lines of CSS
Go to this link
Download version tar.gz for windows and just extract files to the folder by your needs. On the left pane, you can select which version of openjdk to download
Tutorial: unzip as expected. You need to set system variable PATH to include your directory with openjdk so you can type java -version in console.
I got this error when I dynamically read data from a WebRequest
and never closed the Response
.
protected System.IO.Stream GetStream(string url)
{
try
{
System.IO.Stream stream = null;
var request = System.Net.WebRequest.Create(url);
var response = request.GetResponse();
if (response != null) {
stream = response.GetResponseStream();
// I never closed the response thus resulting in the error
response.Close();
}
response = null;
request = null;
return stream;
}
catch (Exception) { }
return null;
}
Make a bat file with the following in it:
copy /y C:\temp\log1k.txt C:\temp\log1k_copied.txt
However, I think there are issues if there are spaces in your directory names. Notice this was copied to the same directory, but that doesn't matter. If you want to see how it runs, make another bat file that calls the first and outputs to a log:
C:\temp\test.bat > C:\temp\test.log
(assuming the first bat file was called test.bat and was located in that directory)
You have a pointer to an object. Therefore, you need to access a field of an object that's pointed to by the pointer. To dereference the pointer you use *
, and to access a field, you use .
, so you can use:
cout << (*kwadrat).val1;
Note that the parentheses are necessary. This operation is common enough that long ago (when C was young) they decided to create a "shorthand" method of doing it:
cout << kwadrat->val1;
These are defined to be identical. As you can see, the ->
basically just combines a *
and a .
into a single operation. If you were dealing directly with an object or a reference to an object, you'd be able to use the .
without dereferencing a pointer first:
Kwadrat kwadrat2(2,3,4);
cout << kwadrat2.val1;
The ::
is the scope resolution operator. It is used when you only need to qualify the name, but you're not dealing with an individual object at all. This would be primarily to access a static data member:
struct something {
static int x; // this only declares `something::x`. Often found in a header
};
int something::x; // this defines `something::x`. Usually in .cpp/.cc/.C file.
In this case, since x
is static
, it's not associated with any particular instance of something
. In fact, it will exist even if no instance of that type of object has been created. In this case, we can access it with the scope resolution operator:
something::x = 10;
std::cout << something::x;
Note, however, that it's also permitted to access a static member as if it was a member of a particular object:
something s;
s.x = 1;
At least if memory serves, early in the history of C++ this wasn't allowed, but the meaning is unambiguous, so they decided to allow it.
Here is how you would add query string parameters using HttpClient 4.2 and later:
URIBuilder builder = new URIBuilder("http://example.com/");
builder.setParameter("parts", "all").setParameter("action", "finish");
HttpPost post = new HttpPost(builder.build());
The resulting URI would look like:
http://example.com/?parts=all&action=finish
If you want to get all Employee name in mysql which having at least one uppercase letter than apply this query.
SELECT * FROM registration WHERE `name` REGEXP BINARY '[A-Z]';
Let's take this:
class Person(val name:String,var age:Int )
def person =new Person("Kumar",12)
person.age=20
println(person.age)
and rewrite it with equivalent code
class Person(val name:String,var age:Int )
def person =new Person("Kumar",12)
(new Person("Kumar", 12)).age_=(20)
println((new Person("Kumar", 12)).age)
See, def
is a method. It will execute each time it is called, and each time it will return (a) new Person("Kumar", 12)
. And these is no error in the "assignment" because it isn't really an assignment, but just a call to the age_=
method (provided by var
).
As a more general answer http://sourceforge.net/p/predef/wiki/Home/ maintains a list of macros for detecting specicic compilers, operating systems, architectures, standards and more.
I don't know what your string
is, but I'm going to assume that it manages its own memory.
You have two solutions:
1: Return a struct
which contains all the types you need.
struct Tuple {
int a;
string b;
};
struct Tuple getPair() {
Tuple r = { 1, getString() };
return r;
}
void foo() {
struct Tuple t = getPair();
}
2: Use pointers to pass out values.
void getPair(int* a, string* b) {
// Check that these are not pointing to NULL
assert(a);
assert(b);
*a = 1;
*b = getString();
}
void foo() {
int a, b;
getPair(&a, &b);
}
Which one you choose to use depends largely on personal preference as to whatever semantics you like more.
It should be understood that from a performance standpoint there are no differences between @temp tables and #temp tables that favor variables. They reside in the same place (tempdb) and are implemented the same way. All the differences appear in additional features. See this amazingly complete writeup: https://dba.stackexchange.com/questions/16385/whats-the-difference-between-a-temp-table-and-table-variable-in-sql-server/16386#16386
Although there are cases where a temp table can't be used such as in table or scalar functions, for most other cases prior to v2016 (where even filtered indexes can be added to a table variable) you can simply use a #temp table.
The drawback to using named indexes (or constraints) in tempdb is that the names can then clash. Not just theoretically with other procedures but often quite easily with other instances of the procedure itself which would try to put the same index on its copy of the #temp table.
To avoid name clashes, something like this usually works:
declare @cmd varchar(500)='CREATE NONCLUSTERED INDEX [ix_temp'+cast(newid() as varchar(40))+'] ON #temp (NonUniqueIndexNeeded);';
exec (@cmd);
This insures the name is always unique even between simultaneous executions of the same procedure.
no, the difference between +
and \;
should be reversed. +
appends the files to the end of the exec command then runs the exec command and \;
runs the command for each file.
The problem is find . -type f -iname '*.cpp' -exec mv {} ./test/ \+
should be find . -type f -iname '*.cpp' -exec mv {} ./test/ +
no need to escape it or terminate the +
xargs I haven't used in a long time but I think works like +.
Yes, i also I fixed it changing in the js libraries to the unminified.
For example, in the tag, change:
<script type="text/javascript" src="js/jquery.ui.core.min.js"></script>
<script type="text/javascript" src="js/jquery.ui.widget.min.js"></script>
<script type="text/javascript" src="js/jquery.ui.rcarousel.min.js"></script>
For:
<script type="text/javascript" src="js/jquery.ui.core.js"></script>
<script type="text/javascript" src="js/jquery.ui.widget.js"></script>
<script type="text/javascript" src="js/jquery.ui.rcarousel.js"></script>
Quiting the 'min' as unminified.
Thanks for the idea.
This can also be if the application does not support the TLS version the SMTP host is using.
For example, trying to configure an SMTP server that uses TLSv1.2 without fallback, when your application(or java program using an older javax.mail JAR) supports only upto TLSv1.1.
You need to add parentheses after a method call, else the compiler will think you're talking about the method itself (a delegate type), whereas you're actually talking about the return value of that method.
string t = obj.getTitle();
Extra Non-Essential Information
Also, have a look at properties. That way you could use title as if it were a variable, while, internally, it works like a function. That way you don't have to write the functions getTitle()
and setTitle(string value)
, but you could do it like this:
public string Title // Note: public fields, methods and properties use PascalCasing
{
get // This replaces your getTitle method
{
return _title; // Where _title is a field somewhere
}
set // And this replaces your setTitle method
{
_title = value; // value behaves like a method parameter
}
}
Or you could use auto-implemented properties, which would use this by default:
public string Title { get; set; }
And you wouldn't have to create your own backing field (_title
), the compiler would create it itself.
Also, you can change access levels for property accessors (getters and setters):
public string Title { get; private set; }
You use properties as if they were fields, i.e.:
this.Title = "Example";
string local = this.Title;
Use encode() function along with hardcoded String value given in a single quote.
Ex:
file.write(answers[i] + '\n'.encode())
OR
line.split(' +++$+++ '.encode())
In Cocoa, to compare dates, use one of isEqualToDate
, compare
, laterDate
, and earlierDate
methods on NSDate
objects, instantiated with the dates you need.
Documentation:
http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSDate_Class/Reference/Reference.html#//apple_ref/occ/instm/NSDate/isEqualToDate:
http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSDate_Class/Reference/Reference.html#//apple_ref/occ/instm/NSDate/earlierDate:
http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSDate_Class/Reference/Reference.html#//apple_ref/occ/instm/NSDate/laterDate:
http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSDate_Class/Reference/Reference.html#//apple_ref/occ/instm/NSDate/compare:
Shift+F5 quickly clears the cache.
There is also the solution of using CDATA
. Example:
<string name="test"><![CDATA[Hello world]]></string>
But in general I think \u0020
is good enough.
Here's a very simple use case and has nothing to do with thread safety.
To share an object between lambda invocations, the AtomicReference
is an option:
public void doSomethingUsingLambdas() {
AtomicReference<YourObject> yourObjectRef = new AtomicReference<>();
soSomethingThatTakesALambda(() -> {
yourObjectRef.set(youObject);
});
soSomethingElseThatTakesALambda(() -> {
YourObject yourObject = yourObjectRef.get();
});
}
I'm not saying this is good design or anything (it's just a trivial example), but if you have have the case where you need to share an object between lambda invocations, the AtomicReference
is an option.
In fact you can use any object that holds a reference, even a Collection that has only one item. However, the AtomicReference is a perfect fit.
You can easily achieve what you want using the appendix
package. Here's a sample file that shows you how. The key is the titletoc
option when calling the package. It takes whatever value you've defined in \appendixname
and the default value is Appendix
.
\documentclass{report}
\usepackage[titletoc]{appendix}
\begin{document}
\tableofcontents
\chapter{Lorem ipsum}
\section{Dolor sit amet}
\begin{appendices}
\chapter{Consectetur adipiscing elit}
\chapter{Mauris euismod}
\end{appendices}
\end{document}
The output looks like
If the images are generated via an ASP Response.Write()
, make sure you don't call Response.Close();
. Chrome doesn't like it.
this question asked in 2009 but i want to share my codes:
Public Function RowSearch(ByVal dttable As DataTable, ByVal searchcolumns As String()) As DataTable
Dim x As Integer
Dim y As Integer
Dim bln As Boolean
Dim dttable2 As New DataTable
For x = 0 To dttable.Columns.Count - 1
dttable2.Columns.Add(dttable.Columns(x).ColumnName)
Next
For x = 0 To dttable.Rows.Count - 1
For y = 0 To searchcolumns.Length - 1
If String.IsNullOrEmpty(searchcolumns(y)) = False Then
If searchcolumns(y) = CStr(dttable.Rows(x)(y + 1) & "") & "" Then
bln = True
Else
bln = False
Exit For
End If
End If
Next
If bln = True Then
dttable2.Rows.Add(dttable.Rows(x).ItemArray)
End If
Next
Return dttable2
End Function
For me, it worked deleting my actual configuration and creating a new one, adding domains like this:
Windows c c++ 10% C# Perl Linux C MAC Obective c Android Java c++ Solaris c c++
I hope you get the answer.
tar.gz file is just a tar file that's been gzipped. Both tar and gzip are available for windows.
If you like GUIs (Graphical user interface), 7zip can pack with both tar and gzip.
It seems you may be more comfortable with developing in PHP you let this hold you back from utilizing the full potential with web applications.
It is indeed possible to have PHP render partials and whole views, but I would not recommend it.
To fully utilize the possibilities of HTML and javascript to make a web application, that is, a web page that acts more like an application and relies heavily on client side rendering, you should consider letting the client maintain all responsibility of managing state and presentation. This will be easier to maintain, and will be more user friendly.
I would recommend you to get more comfortable thinking in a more API centric approach. Rather than having PHP output a pre-rendered view, and use angular for mere DOM manipulation, you should consider having the PHP backend output the data that should be acted upon RESTFully, and have Angular present it.
Using PHP to render the view:
/user/account
if($loggedIn)
{
echo "<p>Logged in as ".$user."</p>";
}
else
{
echo "Please log in.";
}
How the same problem can be solved with an API centric approach by outputting JSON like this:
api/auth/
{
authorized:true,
user: {
username: 'Joe',
securityToken: 'secret'
}
}
and in Angular you could do a get, and handle the response client side.
$http.post("http://example.com/api/auth", {})
.success(function(data) {
$scope.isLoggedIn = data.authorized;
});
To blend both client side and server side the way you proposed may be fit for smaller projects where maintainance is not important and you are the single author, but I lean more towards the API centric way as this will be more correct separation of conserns and will be easier to maintain.
Use orderBy:
df.orderBy('column_name', ascending=False)
Complete answer:
group_by_dataframe.count().filter("`count` >= 10").orderBy('count', ascending=False)
http://spark.apache.org/docs/2.0.0/api/python/pyspark.sql.html
I think this function is missed here in previous answers:
.val( function(index, value) )
In the Project’s Settings, add /FORCE:MULTIPLE
to the Linker’s Command Line options.
From MSDN: "Use /FORCE:MULTIPLE to create an output file whether or not LINK finds more than one definition for a symbol."
Hello...I have created a java client server application in swing for caesar cipher...I have created a new formula that can decrypt the text properly... sorry only for lower case..!
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.io.*;
import java.net.*;
import java.util.*;
public class ceasarserver extends JFrame implements ActionListener {
static String cs = "abcdefghijklmnopqrstuvwxyz";
static JLabel l1, l2, l3, l5, l6;
JTextField t1;
JButton close, b1;
static String en;
int num = 0;
JProgressBar progress;
ceasarserver() {
super("SERVER");
JPanel p = new JPanel(new GridLayout(10, 1));
l1 = new JLabel("");
l2 = new JLabel("");
l3 = new JLabel("");
l5 = new JLabel("");
l6 = new JLabel("Enter the Key...");
t1 = new JTextField(30);
progress = new JProgressBar(0, 20);
progress.setValue(0);
progress.setStringPainted(true);
close = new JButton("Close");
close.setMnemonic('C');
close.setPreferredSize(new Dimension(300, 25));
close.addActionListener(this);
b1 = new JButton("Decrypt");
b1.setMnemonic('D');
b1.addActionListener(this);
p.add(l1);
p.add(l2);
p.add(l3);
p.add(l6);
p.add(t1);
p.add(b1);
p.add(progress);
p.add(l5);
p.add(close);
add(p);
setVisible(true);
pack();
}
public void actionPerformed(ActionEvent e) {
if (e.getSource() == close)
System.exit(0);
else if (e.getSource() == b1) {
int key = Integer.parseInt(t1.getText());
String d = "";
int i = 0, j, k;
while (i < en.length()) {
j = cs.indexOf(en.charAt(i));
k = (j + (26 - key)) % 26;
d = d + cs.charAt(k);
i++;
}
while (num < 21) {
progress.setValue(num);
try {
Thread.sleep(100);
} catch (InterruptedException ex) {
}
progress.setValue(num);
Rectangle progressRect = progress.getBounds();
progressRect.x = 0;
progressRect.y = 0;
progress.paintImmediately(progressRect);
num++;
}
l5.setText("Decrypted text: " + d);
}
}
public static void main(String args[]) throws IOException {
new ceasarserver();
String strm = new String();
ServerSocket ss = new ServerSocket(4321);
l1.setText("Secure data transfer Server Started....");
Socket s = ss.accept();
l2.setText("Client Connected !");
while (true) {
Scanner br1 = new Scanner(s.getInputStream());
en = br1.nextLine();
l3.setText("Client:" + en);
}
}
The client class:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.io.*;
import java.net.*;
import java.util.*;
public class ceasarclient extends JFrame {
String cs = "abcdefghijklmnopqrstuvwxyz";
static JLabel l1, l2, l3, l4, l5;
JButton b1, b2, b3;
JTextField t1, t2;
JProgressBar progress;
int num = 0;
String en = "";
ceasarclient(final Socket s) {
super("CLIENT");
JPanel p = new JPanel(new GridLayout(10, 1));
setSize(500, 500);
t1 = new JTextField(30);
b1 = new JButton("Send");
b1.setMnemonic('S');
b2 = new JButton("Close");
b2.setMnemonic('C');
l1 = new JLabel("Welcome to Secure Data transfer!");
l2 = new JLabel("Enter the word here...");
l3 = new JLabel("");
l4 = new JLabel("Enter the Key:");
b3 = new JButton("Encrypt");
b3.setMnemonic('E');
t2 = new JTextField(30);
progress = new JProgressBar(0, 20);
progress.setValue(0);
progress.setStringPainted(true);
p.add(l1);
p.add(l2);
p.add(t1);
p.add(l4);
p.add(t2);
p.add(b3);
p.add(progress);
p.add(b1);
p.add(l3);
p.add(b2);
add(p);
setVisible(true);
b1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
PrintWriter pw = new PrintWriter(s.getOutputStream(), true);
pw.println(en);
} catch (Exception ex) {
}
;
l3.setText("Encrypted Text Sent.");
}
});
b3.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String strw = t1.getText();
int key = Integer.parseInt(t2.getText());
int i = 0, j, k;
while (i < strw.length()) {
j = cs.indexOf(strw.charAt(i));
k = (j + key) % 26;
en = en + cs.charAt(k);
i++;
}
while (num < 21) {
progress.setValue(num);
try {
Thread.sleep(100);
} catch (InterruptedException exe) {
}
progress.setValue(num);
Rectangle progressRect = progress.getBounds();
progressRect.x = 0;
progressRect.y = 0;
progress.paintImmediately(progressRect);
num++;
}
}
});
b2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
pack();
}
public static void main(String args[]) throws IOException {
final Socket s = new Socket(InetAddress.getLocalHost(), 4321);
new ceasarclient(s);
}
}
systemd
sudo systemctl stop mysqld.service && sudo yum remove -y mariadb mariadb-server && sudo rm -rf /var/lib/mysql /etc/my.cnf
sysvinit
sudo service mysql stop && sudo apt-get remove mariadb mariadb-server && sudo rm -rf /var/lib/mysql /etc/my.cnf
When you say you tried to use OR, how exactly did you try and use it? In your case, what you will need to do would be something like so:
String newStr4 = strr.split("2012")[0];
if(newStr4.startsWith("Mon") || newStr4.startsWith("Tues")...)
str4.add(newStr4);
footer {
margin-top:calc(5% + 60px);
}
This works fine
I know this post is old, but what i had to do in the case of the above answers on Linux machine was:
sudo chmod +x directory
I suspect you're only reporting the last error in a stack like this:
ORA-04068: existing state of packages has been discarded
ORA-04061: existing state of package body "schema.package" has been invalidated
ORA-04065: not executed, altered or dropped package body "schema.package"
ORA-06508: PL/SQL: could not find program unit being called: "schema.package"
If so, that's because your package is stateful:
The values of the variables, constants, and cursors that a package declares (in either its specification or body) comprise its package state. If a PL/SQL package declares at least one variable, constant, or cursor, then the package is stateful; otherwise, it is stateless.
When you recompile the state is lost:
If the body of an instantiated, stateful package is recompiled (either explicitly, with the "ALTER PACKAGE Statement", or implicitly), the next invocation of a subprogram in the package causes Oracle Database to discard the existing package state and raise the exception ORA-04068.
After PL/SQL raises the exception, a reference to the package causes Oracle Database to re-instantiate the package, which re-initializes it...
You can't avoid this if your package has state. I think it's fairly rare to really need a package to be stateful though, so you should revisit anything you have declared in the package, but outside a function or procedure, to see if it's really needed at that level. Since you're on 10g though, that includes constants, not just variables and cursors.
But the last paragraph from the quoted documentation means that the next time you reference the package in the same session, you won't get the error and it will work as normal (until you recompile again).
Mount your sql-dump under/docker-entrypoint-initdb.d/yourdump.sql
utilizing a volume mount
mysql:
image: mysql:latest
container_name: mysql-container
ports:
- 3306:3306
volumes:
- ./dump.sql:/docker-entrypoint-initdb.d/dump.sql
environment:
MYSQL_ROOT_PASSWORD: secret
MYSQL_DATABASE: name_db
MYSQL_USER: user
MYSQL_PASSWORD: password
This will trigger an import of the sql-dump during the start of the container, see https://hub.docker.com/_/mysql/ under "Initializing a fresh instance"
we are in 2017 now you can also use ES2016
var a = 'abc123.8<blah>';
console.log([...a].filter( e => isFinite(e)).join(''));
or
console.log([...'abc123.8<blah>'].filter( e => isFinite(e)).join(''));
The result is
1238
If you are using C++11
, you should probably use stoi
because it can distinguish between an error and parsing "0"
.
try {
int number = std::stoi("1234abc");
} catch (std::exception const &e) {
// This could not be parsed into a number so an exception is thrown.
// atoi() would return 0, which is less helpful if it could be a valid value.
}
It should be noted that "1234abc" is implicitly converted from a char[]
to a std:string
before being passed to stoi()
.
Not using awk but the simplest way I was able to get this done was to just use csvtool. I had other use cases as well to use csvtool and it can handle the quotes or delimiters appropriately if they appear within the column data itself.
csvtool format '%(2)\n' input.csv
csvtool format '%(2),%(3),%(4)\n' input.csv
Replacing 2 with the column number will effectively extract the column data you are looking for.
if you have a dataframe where some columns are numeric and some are other (character or factor) and you only want to do the correlations for the numeric columns, you could do the following:
set.seed(10)
x = as.data.frame(matrix(rnorm(100), ncol = 10))
x$L1 = letters[1:10]
x$L2 = letters[11:20]
cor(x)
Error in cor(x) : 'x' must be numeric
but
cor(x[sapply(x, is.numeric)])
V1 V2 V3 V4 V5 V6 V7
V1 1.00000000 0.3025766 -0.22473884 -0.72468776 0.18890578 0.14466161 0.05325308
V2 0.30257657 1.0000000 -0.27871430 -0.29075170 0.16095258 0.10538468 -0.15008158
V3 -0.22473884 -0.2787143 1.00000000 -0.22644156 0.07276013 -0.35725182 -0.05859479
V4 -0.72468776 -0.2907517 -0.22644156 1.00000000 -0.19305921 0.16948333 -0.01025698
V5 0.18890578 0.1609526 0.07276013 -0.19305921 1.00000000 0.07339531 -0.31837954
V6 0.14466161 0.1053847 -0.35725182 0.16948333 0.07339531 1.00000000 0.02514081
V7 0.05325308 -0.1500816 -0.05859479 -0.01025698 -0.31837954 0.02514081 1.00000000
V8 0.44705527 0.1698571 0.39970105 -0.42461411 0.63951574 0.23065830 -0.28967977
V9 0.21006372 -0.4418132 -0.18623823 -0.25272860 0.15921890 0.36182579 -0.18437981
V10 0.02326108 0.4618036 -0.25205899 -0.05117037 0.02408278 0.47630138 -0.38592733
V8 V9 V10
V1 0.447055266 0.210063724 0.02326108
V2 0.169857120 -0.441813231 0.46180357
V3 0.399701054 -0.186238233 -0.25205899
V4 -0.424614107 -0.252728595 -0.05117037
V5 0.639515737 0.159218895 0.02408278
V6 0.230658298 0.361825786 0.47630138
V7 -0.289679766 -0.184379813 -0.38592733
V8 1.000000000 0.001023392 0.11436143
V9 0.001023392 1.000000000 0.15301699
V10 0.114361431 0.153016985 1.00000000
This may not be a very good solution but in my case, I solve it like this.
from multiprocessing import Pool
def foo1(data):
self = data.get('slf')
lst = data.get('lst')
return sum(lst) + self.foo2()
class Foo(object):
def __init__(self, a, b):
self.a = a
self.b = b
def foo2(self):
return self.a**self.b
def foo(self):
p = Pool(5)
lst = [1, 2, 3]
result = p.map(foo1, (dict(slf=self, lst=lst),))
return result
if __name__ == '__main__':
print(Foo(2, 4).foo())
I had to pass self
to my function as I have to access attributes and functions of my class through that function. This is working for me. Corrections and suggestions are always welcome.
echo '<pre>' . htmlspecialchars("<div><b>raw HTML</b></div>") . '</pre>';
I think that's what you're looking for?
In other words, use htmlspecialchars() in PHP
Free read-only viewers:
tail
." It's really a log file analyzer, not a large file viewer, and in one test it required 10 seconds and 700 MB of RAM to load a 250 MB file. But its killer features are the columnizer (parse logs that are in CSV, JSONL, etc. and display in a spreadsheet format) and the highlighter (show lines with certain words in certain colors). Also supports file following, tabs, multifiles, bookmarks, search, plugins, and external tools.Free editors:
Builtin programs (no installation required):
MORE
, not the Unix more
. A console program that allows you to view a file, one screen at a time.Web viewers:
Paid editors:
Also something that can go wrong: Make sure you exit Docker for Mac (possibly all other kind of docker installations as well).
plt.rcParams['figure.figsize'] = (15, 5)
I have eclipse JRE 8.112 , not sure if that matters but what i did was this:
This solved my problem.
You could use AJAX to send a POST request if you don't want forms.
Using jquery $.post method it is pretty simple:
$.post('/foo.php', { key1: 'value1', key2: 'value2' }, function(result) {
alert('successfully posted key1=value1&key2=value2 to foo.php');
});
xmlns - xml namespace. It's just a method to avoid element name conflicts. For example:
<config xmlns:rnc="URI1" xmlns:bsc="URI2">
<rnc:node>
<rnc:rncId>5</rnc:rncId>
</rnc:node>
<bsc:node>
<bsc:cId>5</bsc:cId>
</bsc:node>
</config>
Two different node
elements in one xml file. Without namespaces this file would not be valid.
Mongodb and Mongoose are two completely different things!
Mongodb is the database itself, while Mongoose is an object modeling tool for Mongodb
EDIT: As pointed out MongoDB is the npm package, thanks!
This fixed the same issue for me:
My eclipse is installed in /usr/local/bin/eclipse
1) Changed permission for eclipse from root to owner: sudo chown -R $USER eclipse
2) Right click on project/Maven
right click on Update Maven
select Force update maven project
With new features of ES6 block level scoping is managed:
var funcs = [];
for (let i = 0; i < 3; i++) { // let's create 3 functions
funcs[i] = function() { // and store them in funcs
console.log("My value: " + i); // each should log its value.
};
}
for (let j = 0; j < 3; j++) {
funcs[j](); // and now let's run each one to see
}
The code in OP's question is replaced with let
instead of var
.
example:
public class CurrencyDenom {
public static final int PENNY = 1;
public static final int NICKLE = 5;
public static final int DIME = 10;
public static final int QUARTER = 25;}
Limitation of java Constants
1) No Type-Safety: First of all it’s not type-safe; you can assign any valid int value to int e.g. 99 though there is no coin to represent that value.
2) No Meaningful Printing: printing value of any of these constant will print its numeric value instead of meaningful name of coin e.g. when you print NICKLE it will print "5" instead of "NICKLE"
3) No namespace: to access the currencyDenom constant we need to prefix class name e.g. CurrencyDenom.PENNY instead of just using PENNY though this can also be achieved by using static import in JDK 1.5
Advantage of enum
1) Enums in Java are type-safe and has there own name-space. It means your enum will have a type for example "Currency" in below example and you can not assign any value other than specified in Enum Constants.
public enum Currency {PENNY, NICKLE, DIME, QUARTER};
Currency coin = Currency.PENNY;
coin = 1; //compilation error
2) Enum in Java are reference type like class or interface and you can define constructor, methods and variables inside java Enum which makes it more powerful than Enum in C and C++ as shown in next example of Java Enum type.
3) You can specify values of enum constants at the creation time as shown in below example: public enum Currency {PENNY(1), NICKLE(5), DIME(10), QUARTER(25)}; But for this to work you need to define a member variable and a constructor because PENNY (1) is actually calling a constructor which accepts int value , see below example.
public enum Currency {
PENNY(1), NICKLE(5), DIME(10), QUARTER(25);
private int value;
private Currency(int value) {
this.value = value;
}
};
Reference: https://javarevisited.blogspot.com/2011/08/enum-in-java-example-tutorial.html
Try this..
#!/usr/bin/env python
import gtk.gdk
import time
import random
while 1 :
# generate a random time between 120 and 300 sec
random_time = random.randrange(120,300)
# wait between 120 and 300 seconds (or between 2 and 5 minutes)
print "Next picture in: %.2f minutes" % (float(random_time) / 60)
time.sleep(random_time)
w = gtk.gdk.get_default_root_window()
sz = w.get_size()
print "The size of the window is %d x %d" % sz
pb = gtk.gdk.Pixbuf(gtk.gdk.COLORSPACE_RGB,False,8,sz[0],sz[1])
pb = pb.get_from_drawable(w,w.get_colormap(),0,0,0,0,sz[0],sz[1])
ts = time.time()
filename = "screenshot"
filename += str(ts)
filename += ".png"
if (pb != None):
pb.save(filename,"png")
print "Screenshot saved to "+filename
else:
print "Unable to get the screenshot."
$("#yourobj").attr('type');
A little extension on the answer of jsbueno:
#!/usr/bin/env python
import cairo
import rsvg
from xml.dom import minidom
def convert_svg_to_png(svg_file, output_file):
# Get the svg files content
with open(svg_file) as f:
svg_data = f.read()
# Get the width / height inside of the SVG
doc = minidom.parse(svg_file)
width = int([path.getAttribute('width') for path
in doc.getElementsByTagName('svg')][0])
height = int([path.getAttribute('height') for path
in doc.getElementsByTagName('svg')][0])
doc.unlink()
# create the png
img = cairo.ImageSurface(cairo.FORMAT_ARGB32, width, height)
ctx = cairo.Context(img)
handler = rsvg.Handle(None, str(svg_data))
handler.render_cairo(ctx)
img.write_to_png(output_file)
if __name__ == '__main__':
from argparse import ArgumentParser
parser = ArgumentParser()
parser.add_argument("-f", "--file", dest="svg_file",
help="SVG input file", metavar="FILE")
parser.add_argument("-o", "--output", dest="output", default="svg.png",
help="PNG output file", metavar="FILE")
args = parser.parse_args()
convert_svg_to_png(args.svg_file, args.output)
Python 3.6+ (2017)
In the recent versions of Python one would use f-strings (see also PEP498).
With f-strings one should use double {{
or }}
n = 42
print(f" {{Hello}} {n} ")
produces the desired
{Hello} 42
If you need to resolve an expression in the brackets instead of using literal text you'll need three sets of brackets:
hello = "HELLO"
print(f"{{{hello.lower()}}}")
produces
{hello}
Note: Most modern browsers will now allow you to navigate objects in the developer console. This answer is antiquated.
This method will walk through object properties and write them to the console with increasing indent:
function enumerate(o,s){
//if s isn't defined, set it to an empty string
s = typeof s !== 'undefined' ? s : "";
//if o is null, we need to output and bail
if(typeof o == "object" && o === null){
console.log(s+k+": null");
} else {
//iterate across o, passing keys as k and values as v
$.each(o, function(k,v){
//if v has nested depth
if(typeof v == "object" && v !== null){
//write the key to the console
console.log(s+k+": ");
//recursively call enumerate on the nested properties
enumerate(v,s+" ");
} else {
//log the key & value
console.log(s+k+": "+String(v));
}
});
}
}
Just pass it the object you want to iterate through:
var response = $.ajax({
url: myurl,
dataType: "json"
})
.done(function(a){
console.log("Returned values:");
enumerate(a);
})
.fail(function(){ console.log("request failed");});
I had the same problem when trying out Android Studio. I already had projects running on the ADT under SDK 18. No need to hack the manifest files.
Fixed by:
export ANDROID_HOME= pathtobundle/adt-bundle-linux-x86_64-20130729/sdk
If you don't have the ADT installed, and just want the SDK, it seems like a good solution is to install everything and then point Android Studio to the just the packaged SDK.
cd pathtobundle
wget http://dl.google.com/android/adt/adt-bundle-linux-x86_64-20130729.zip
unzip *.zip
As someone else said, you may need to run the SDK Manager to install the desired packages before running Studio.
This is the easiest setup on a Linux Ubuntu machine I have come across. Crazy to see all the queries live.
Find and open your MySQL configuration file, usually /etc/mysql/my.cnf on Ubuntu. Look for the section that says “Logging and Replication”
#
# * Logging and Replication
#
# Both location gets rotated by the cronjob.
# Be aware that this log type is a performance killer.
log = /var/log/mysql/mysql.log
Just uncomment the “log” variable to turn on logging. Restart MySQL with this command:
sudo /etc/init.d/mysql restart
Now we’re ready to start monitoring the queries as they come in. Open up a new terminal and run this command to scroll the log file, adjusting the path if necessary.
tail -f /var/log/mysql/mysql.log
Now run your application. You’ll see the database queries start flying by in your terminal window. (make sure you have scrolling and history enabled on the terminal)
FROM http://www.howtogeek.com/howto/database/monitor-all-sql-queries-in-mysql/
You can also use ReadString with \n as a separator:
f, err := os.Open(filename)
if err != nil {
fmt.Println("error opening file ", err)
os.Exit(1)
}
defer f.Close()
r := bufio.NewReader(f)
for {
path, err := r.ReadString(10) // 0x0A separator = newline
if err == io.EOF {
// do something here
break
} else if err != nil {
return err // if you return error
}
}
To be efficient, and random, it might be best to have two different queries.
Something like...
SELECT table_id FROM table
Then, in your chosen language, pick a random id, then pull that row's data.
SELECT * FROM table WHERE table_id = $rand_id
But that's not really a good idea if you're expecting to have lots of rows in the table. It would be better if you put some kind of limit on what you randomly select from. For publications, maybe randomly pick from only items posted within the last year.
print("imageURLString = " + imageURLString!)
just use !
While you use .on(), it's basically a live query that you are using.
On the other hand, .ready (as in your case) is a static query. While using it, you can dynamically update data and do not have to wait for the page to load. You can simply pass on the values into your database (if required) when a particular value is entered.
The use of live queries is common in forms where we enter data (account or posts or even comments).
Change alert(buttons[i].text);
to alert(i);
.remove()
is deprecated. instead we can use deleteMany
DateTime.deleteMany({}, callback)
.
A shorter alternative to the previously mentioned stash approach would be:
Temporarily move the changes to a stash.
git stash
Create and switch to a new branch and then pop the stash to it in just one step.
git stash branch new_branch_name
Then just add
and commit
the changes to this new branch.
That most likely refers to a connection issue. It could be either that your internet connection was down, or the web service you are trying to use was down. I suggest using this service to see if the web service is online or not: http://downforeveryoneorjustme.com/
pd.to_numeric
with errors='coerce'
# Setup
s = pd.Series(['1', '2', '3', '4', '.'])
s
0 1
1 2
2 3
3 4
4 .
dtype: object
pd.to_numeric(s, errors='coerce')
0 1.0
1 2.0
2 3.0
3 4.0
4 NaN
dtype: float64
If you need the NaN
s filled in, use Series.fillna
.
pd.to_numeric(s, errors='coerce').fillna(0, downcast='infer')
0 1
1 2
2 3
3 4
4 0
dtype: float64
Note, downcast='infer'
will attempt to downcast floats to integers where possible. Remove the argument if you don't want that.
From v0.24+, pandas introduces a Nullable Integer type, which allows integers to coexist with NaNs. If you have integers in your column, you can use
pd.__version__ # '0.24.1' pd.to_numeric(s, errors='coerce').astype('Int32') 0 1 1 2 2 3 3 4 4 NaN dtype: Int32
There are other options to choose from as well, read the docs for more.
DataFrames
If you need to extend this to DataFrames, you will need to apply it to each row. You can do this using DataFrame.apply
.
# Setup.
np.random.seed(0)
df = pd.DataFrame({
'A' : np.random.choice(10, 5),
'C' : np.random.choice(10, 5),
'B' : ['1', '###', '...', 50, '234'],
'D' : ['23', '1', '...', '268', '$$']}
)[list('ABCD')]
df
A B C D
0 5 1 9 23
1 0 ### 3 1
2 3 ... 5 ...
3 3 50 2 268
4 7 234 4 $$
df.dtypes
A int64
B object
C int64
D object
dtype: object
df2 = df.apply(pd.to_numeric, errors='coerce')
df2
A B C D
0 5 1.0 9 23.0
1 0 NaN 3 1.0
2 3 NaN 5 NaN
3 3 50.0 2 268.0
4 7 234.0 4 NaN
df2.dtypes
A int64
B float64
C int64
D float64
dtype: object
You can also do this with DataFrame.transform
; although my tests indicate this is marginally slower:
df.transform(pd.to_numeric, errors='coerce')
A B C D
0 5 1.0 9 23.0
1 0 NaN 3 1.0
2 3 NaN 5 NaN
3 3 50.0 2 268.0
4 7 234.0 4 NaN
If you have many columns (numeric; non-numeric), you can make this a little more performant by applying pd.to_numeric
on the non-numeric columns only.
df.dtypes.eq(object)
A False
B True
C False
D True
dtype: bool
cols = df.columns[df.dtypes.eq(object)]
# Actually, `cols` can be any list of columns you need to convert.
cols
# Index(['B', 'D'], dtype='object')
df[cols] = df[cols].apply(pd.to_numeric, errors='coerce')
# Alternatively,
# for c in cols:
# df[c] = pd.to_numeric(df[c], errors='coerce')
df
A B C D
0 5 1.0 9 23.0
1 0 NaN 3 1.0
2 3 NaN 5 NaN
3 3 50.0 2 268.0
4 7 234.0 4 NaN
Applying pd.to_numeric
along the columns (i.e., axis=0
, the default) should be slightly faster for long DataFrames.
I had this problem with Blend for Visual Studio 2015. The Toolbox would just not appear anymore. This turns out to be because Blend is not Visual Studio!
(You can edit your code in Blend and build and run it... It certainly seems like Visual Studio, but it isn't. I'm not sure what the purpose of Blend is...)
You can tell you are in Blend if the task bar icon has big "B" in it. To switch from Blend to Visual Studio, go to View
-> Edit in Visual Studio...
. It will open up another application that looks just like Blend, except the Solution Explorer is on the right instead of the left, and now you have a toolbox...
Use the DotNetZip library at http://www.codeplex.com/DotNetZip
class library and toolset for manipulating zip files. Use VB, C# or any .NET language to easily create, extract, or update zip files...
DotNetZip works on PCs with the full .NET Framework, and also runs on mobile devices that use the .NET Compact Framework. Create and read zip files in VB, C#, or any .NET language, or any scripting environment...
If all you want is a better DeflateStream or GZipStream class to replace the one that is built-into the .NET BCL, DotNetZip has that, too. DotNetZip's DeflateStream and GZipStream are available in a standalone assembly, based on a .NET port of Zlib. These streams support compression levels and deliver much better performance than the built-in classes. There is also a ZlibStream to complete the set (RFC 1950, 1951, 1952)...
The nature of wanting to include the row where A == 5
and all rows upto but not including the row where A == 8
means we will end up using iloc
(loc
includes both ends of slice).
In order to get the index labels we use idxmax
. This will return the first position of the maximum value. I run this on a boolean series where A == 5
(then when A == 8
) which returns the index value of when A == 5
first happens (same thing for A == 8
).
Then I use searchsorted
to find the ordinal position of where the index label (that I found above) occurs. This is what I use in iloc
.
i5, i8 = df.index.searchsorted([df.A.eq(5).idxmax(), df.A.eq(8).idxmax()])
df.iloc[i5:i8]
numpy
you can further enhance this by using the underlying numpy objects the analogous numpy functions. I wrapped it up into a handy function.
def find_between(df, col, v1, v2):
vals = df[col].values
mx1, mx2 = (vals == v1).argmax(), (vals == v2).argmax()
idx = df.index.values
i1, i2 = idx.searchsorted([mx1, mx2])
return df.iloc[i1:i2]
find_between(df, 'A', 5, 8)
try this
SELECT group_name, employees, surveys, COUNT( surveys ) AS test1,
concat(round(( surveys/employees * 100 ),2),'%') AS percentage
FROM a_test
GROUP BY employees
Marquee (<marquee>
) is a deprecated and not a valid HTML tag. You can use many jQuery plugins to do. One of it, is jQuery News Ticker. There are many more!
besides str.join
which is the most natural way, a possibility is to use io.StringIO
and abusing writelines
to write all elements in one go:
import io
a = ['a','b','c','d']
out = io.StringIO()
out.writelines(a)
print(out.getvalue())
prints:
abcd
When using this approach with a generator function or an iterable which isn't a tuple
or a list
, it saves the temporary list creation that join
does to allocate the right size in one go (and a list of 1-character strings is very expensive memory-wise).
If you're low in memory and you have a lazily-evaluated object as input, this approach is the best solution.
I tried differently for the same issue and worked .
Go to your project location in hard drive. ex: /home/user/workspace/project/settings and Delete this file org.eclipse.core.resources.prefs
For full details check out bellow link
http://errorkode.com/viewtopic.php?f=20&t=8&sid=40cff1661bf0ace12878d6d6fb7e75ac
For additional details see the SVNBook: "Status of working copy files and directories".
The common statuses:
U: Working file was updated
G: Changes on the repo were automatically merged into the working copy
M: Working copy is modified
C: This file conflicts with the version in the repo
?: This file is not under version control
!: This file is under version control but is missing or incomplete
A: This file will be added to version control (after commit)
A+: This file will be moved (after commit)
D: This file will be deleted (after commit)
S: This signifies that the file or directory has been switched from the path of the rest of the working copy (using svn switch) to a branch
I: Ignored
X: External definition
~: Type changed
R: Item has been replaced in your working copy. This means the file was scheduled for deletion, and then a new file with the same name was scheduled for addition in its place.
L : Item is locked
E: Item existed, as it would have been created, by an svn update.
In Spring Boot 2, the easiest way is to declare in your application.properties:
spring.jackson.serialization.WRITE_ENUMS_USING_TO_STRING=true
spring.jackson.deserialization.READ_ENUMS_USING_TO_STRING=true
and define the toString() method of your enums.
It depends on whether you process IDNs before or after the IDN toASCII
algorithm (that is, do you see the domain name pa??de??µa.d???µ?
in Greek or as xn--hxajbheg2az3al.xn--jxalpdlp
?).
In the latter case—where you are handling IDNs through the punycode—the old RFC 1123 rules apply:
U+0041 through U+005A (A-Z), U+0061 through U+007A (a-z) case folded as each other, U+0030 through U+0039 (0-9) and U+002D (-).
and U+002E (.) of course; the rules for labels allow the others, with dots between labels.
If you are seeing it in IDN form, the allowed characters are much varied, see http://unicode.org/reports/tr36/idn-chars.html for a handy chart of all valid characters.
Chances are your network code will deal with the punycode, but your display code (or even just passing strings to and from other layers) with the more human-readable form as nobody running a server on the ????????. domain wants to see their server listed as being on .xn--mgberp4a5d4ar
.
you can use attribute placeholder
<input type="text" name="email" placeholder="[email protected]" size="30" />
or try this for older browsers
<input type="text" name="email" value="[email protected]" size="30" onblur="if(this.value==''){this.value='[email protected]';}" onfocus="if(this.value=='[email protected]'){this.value='';}">
I'm using a helper function to create what I call a "flat promise" -
function flatPromise() {
let resolve, reject;
const promise = new Promise((res, rej) => {
resolve = res;
reject = rej;
});
return { promise, resolve, reject };
}
And I'm using it like so -
function doSomethingAsync() {
// Get your promise and callbacks
const { resolve, reject, promise } = flatPromise();
// Do something amazing...
setTimeout(() => {
resolve('done!');
}, 500);
// Pass your promise to the world
return promise;
}
See full working example -
function flatPromise() {_x000D_
_x000D_
let resolve, reject;_x000D_
_x000D_
const promise = new Promise((res, rej) => {_x000D_
resolve = res;_x000D_
reject = rej;_x000D_
});_x000D_
_x000D_
return { promise, resolve, reject };_x000D_
}_x000D_
_x000D_
function doSomethingAsync() {_x000D_
_x000D_
// Get your promise and callbacks_x000D_
const { resolve, reject, promise } = flatPromise();_x000D_
_x000D_
// Do something amazing..._x000D_
setTimeout(() => {_x000D_
resolve('done!');_x000D_
}, 500);_x000D_
_x000D_
// Pass your promise to the world_x000D_
return promise;_x000D_
}_x000D_
_x000D_
(async function run() {_x000D_
_x000D_
const result = await doSomethingAsync()_x000D_
.catch(err => console.error('rejected with', err));_x000D_
console.log(result);_x000D_
_x000D_
})();
_x000D_
Edit: I have created an NPM package called flat-promise and the code is also available on GitHub.
I ran into a similar problem because my master was set to " # of executor (The maximum number of concurrent builds that Jenkins may perform on this agent).
Go to Jenkins --> Manage Jenkins --> Manage Nodes, and click on the configure button of your master node (increase the number of executor to run mutiple jobs at a time).
In Chrome, click the 3 dots and click More tools and click developer. On the console, type console.dir(yourObject).Click this link to view an example image
I was Working with Elastic SQL plugin. Query is done with GET method using cURL as below:
curl -XGET http://localhost:9200/_sql/_explain -H 'Content-Type: application/json' \
-d 'SELECT city.keyword as city FROM routes group by city.keyword order by city'
I exposed a custom port at public server, doing a reverse proxy with Basic Auth set.
This code, works fine plus Basic Auth Header:
$host = 'http://myhost.com:9200';
$uri = "/_sql/_explain";
$auth = "john:doe";
$data = "SELECT city.keyword as city FROM routes group by city.keyword order by city";
function restCurl($host, $uri, $data = null, $auth = null, $method = 'DELETE'){
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $host.$uri);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
if ($method == 'POST')
curl_setopt($ch, CURLOPT_POST, 1);
if ($auth)
curl_setopt($ch, CURLOPT_USERPWD, $auth);
if (strlen($data) > 0)
curl_setopt($ch, CURLOPT_POSTFIELDS,$data);
$resp = curl_exec($ch);
if(!$resp){
$resp = (json_encode(array(array("error" => curl_error($ch), "code" => curl_errno($ch)))));
}
curl_close($ch);
return $resp;
}
$resp = restCurl($host, $uri); //DELETE
$resp = restCurl($host, $uri, $data, $auth, 'GET'); //GET
$resp = restCurl($host, $uri, $data, $auth, 'POST'); //POST
$resp = restCurl($host, $uri, $data, $auth, 'PUT'); //PUT
If you want to remove/clean all the values from local storage than use
localStorage.clear();
And if you want to remove the specific item from local storage than use the following code
localStorage.removeItem(key);
TIP:
comment out pid and socket file, if you can't connect to server..
mysql could be connecting with incorrect pid and/or socket file,
so when you try to connect to server trough command-line it "looks"
at the incorrect pid/socket file...
### comment out pid and socket file, if you can't connect to server..
#pid-file=/var/run/mysql/mysqld.pid #socket=/var/lib/mysql/mysql.sock
select * from SomeTable where 1=1
I needed to solve the same problem for a portable class library (PCL) that I'm working on. In this case, I don't have access to System.Web so I can't use ParseQueryString.
Instead I used System.Net.Http.FormUrlEncodedContent
like so:
var url = new UriBuilder("http://example.com");
url.Query = new FormUrlEncodedContent(new Dictionary<string,string>()
{
{"param1", "val1"},
{"param2", "val2"},
{"param3", "val3"},
}).ReadAsStringAsync().Result;
You need to write it like sprintf(aa, "%9.7lf", a)
Check out http://en.wikipedia.org/wiki/Printf for some more details on format codes.
Boom Check this for java Lovers :D We can modify it according to our need:
List<Pair<String, View.OnClickListener>> pairsList = new ArrayList<>();
pairsList.add(new Pair<>("38,50", v -> {
Intent intent = new Intent(SignUpActivity.this, WebActivity.class);
intent.putExtra("which", "tos");
startActivity(intent);
}));
pairsList.add(new Pair<>("81,95", v -> {
Intent intent = new Intent(SignUpActivity.this, WebActivity.class);
intent.putExtra("which", "policy");
startActivity(intent);
}));
makeLinks(pairsList); // Method calling
private void makeLinks(List<Pair<String, View.OnClickListener>> pairsList) {
SpannableString ss = new SpannableString(By signing up, I’m agree to PAKRISM’s Terms of Use and confirms that I have read Privacy Policy);
for (Pair<String, View.OnClickListener> pair : pairsList) {
ClickableSpan clickableSpan = new ClickableSpan() {
@Override
public void onClick(View textView) {
//Toast.makeText(MyApplication.getAppContext(), "Clicked!", Toast.LENGTH_SHORT).show();
pair.second.onClick(textView);
}
@Override
public void updateDrawState(TextPaint ds) {
ds.linkColor = ContextCompat.getColor(SignUpActivity.this, R.color.primary_main);
ds.setUnderlineText(true);
super.updateDrawState(ds);
}
};
String[] indexes = pair.first.split(",");
ss.setSpan(clickableSpan, Integer.parseInt(indexes[0]), Integer.parseInt(indexes[1]), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
}
TextView tv = findViewById(R.id.txtView);
tv.setText(ss);
tv.setMovementMethod(LinkMovementMethod.getInstance());
}
Bing Maps API has a REST service that returns traffic info
lstResult.Clear();
foreach (ManagementObject drive in new ManagementObjectSearcher("select * from Win32_DiskDrive where InterfaceType='USB'").Get())
{
foreach (ManagementObject partition in new ManagementObjectSearcher("ASSOCIATORS OF {Win32_DiskDrive.DeviceID='" + drive["DeviceID"] + "'} WHERE AssocClass = Win32_DiskDriveToDiskPartition").Get())
{
foreach (ManagementObject disk in new ManagementObjectSearcher("ASSOCIATORS OF {Win32_DiskPartition.DeviceID='" + partition["DeviceID"] + "'} WHERE AssocClass = Win32_LogicalDiskToPartition").Get())
{
foreach (var item in disk.Properties)
{
object value = disk.GetPropertyValue(item.Name);
}
string valor = disk["Name"].ToString();
lstResult.Add(valor);
}
}
}
}
I generally try to avoid expressions with ng-show and ng-hide as they were designed as booleans, not conditionals. If I need both conditional and boolean logic, I prefer to put in the conditional logic using ng-if as the first check, then add in an additional check for the boolean logic with ng-show and ng-hide
Howerver, if you want to use a conditional for ng-show or ng-hide, here is a link with some examples: Conditional Display using ng-if, ng-show, ng-hide, ng-include, ng-switch
use request.getContextPath()
instead of ${pageContext.request.contextPath}
in JSP expression language.
<%
String contextPath = request.getContextPath();
%>
out.println(contextPath);
output: willPrintMyProjectcontextPath
As @ThierryTemplier said for receiving data from server and also transmitting model between components (to keep intellisense list and make design time error), it's fine to use interface but I think for sending data to server (DTOs) it's better to use class to take advantages of auto mapping DTO from model.
For any of you calling back to the same server for your IFRAME, pass this simple header inside the IFRAME page:
Content-Security-Policy: frame-ancestors 'self'
Or, add this to your web server's CSP configuration.
You already have built-in method for that: -
List<String> species = Arrays.asList(speciesArr);
NOTE: - You should use List<String> species
not ArrayList<String> species
.
Arrays.asList
returns a different ArrayList
-> java.util.Arrays.ArrayList
which cannot be typecasted to java.util.ArrayList
.
Then you would have to use addAll
method, which is not so good. So just use List<String>
NOTE: - The list returned by Arrays.asList
is a fixed size list. If you want to add something to the list, you would need to create another list, and use addAll
to add elements to it. So, then you would better go with the 2nd way as below: -
String[] arr = new String[1];
arr[0] = "rohit";
List<String> newList = Arrays.asList(arr);
// Will throw `UnsupportedOperationException
// newList.add("jain"); // Can't do this.
ArrayList<String> updatableList = new ArrayList<String>();
updatableList.addAll(newList);
updatableList.add("jain"); // OK this is fine.
System.out.println(newList); // Prints [rohit]
System.out.println(updatableList); //Prints [rohit, jain]
Here the defination of Rendersection from MSDN
In layout pages, renders the content of a named section.MSDN
In _layout.cs page put
@RenderSection("Bottom",false)
Here render the content of bootom section and specifies false
boolean property to specify whether the section is required or not.
@section Bottom{
This message form bottom.
}
That meaning if you want to bottom section in all pages, then you must use false as the second parameter at Rendersection method.
I had the same problem and I solved it as follows:
check the node-sass
version used in the current project
go to node-sass
release:
"https://github.com/sass/node-sass/releases/tag/v@.@.@" (put your node-sass version here)
check the Supported Environment table and see if your Node version exist in it
if it is not, downgrade your node version to the latest version existing in the table
I know it's not the perfect solution but I didn't find anything else in my case.
A datetime.timedelta
corresponds to the difference between two dates, not a date itself. It's only expressed in terms of days, seconds, and microseconds, since larger time units like months and years don't decompose cleanly (is 30 days 1 month or 0.9677 months?).
If you want to convert a timedelta
into hours and minutes, you can use the total_seconds()
method to get the total number of seconds and then do some math:
x = datetime.timedelta(1, 5, 41038) # Interval of 1 day and 5.41038 seconds
secs = x.total_seconds()
hours = int(secs / 3600)
minutes = int(secs / 60) % 60
If it's reconnecting and getting connection ID 2, the server has almost definitely just crashed.
Contact the server admin and get them to diagnose the problem. No non-malicious SQL should crash the server, and the output of mysqldump certainly should not.
It is probably the case that the server admin has made some big operational error such as assigning buffer sizes of greater than the architecture's address-space limits, or more than virtual memory capacity. The MySQL error-log will probably have some relevant information; they will be monitoring this if they are competent anyway.
If method 1 has to be executed after method 2, 3, 4. The following code snippet can be the solution for this using Deferred object in JavaScript.
function method1(){_x000D_
var dfd = new $.Deferred();_x000D_
setTimeout(function(){_x000D_
console.log("Inside Method - 1"); _x000D_
method2(dfd); _x000D_
}, 5000);_x000D_
return dfd.promise();_x000D_
}_x000D_
_x000D_
function method2(dfd){_x000D_
setTimeout(function(){_x000D_
console.log("Inside Method - 2"); _x000D_
method3(dfd); _x000D_
}, 3000);_x000D_
}_x000D_
_x000D_
function method3(dfd){_x000D_
setTimeout(function(){_x000D_
console.log("Inside Method - 3"); _x000D_
dfd.resolve();_x000D_
}, 3000);_x000D_
}_x000D_
_x000D_
function method4(){ _x000D_
console.log("Inside Method - 4"); _x000D_
}_x000D_
_x000D_
var call = method1();_x000D_
_x000D_
$.when(call).then(function(cb){_x000D_
method4();_x000D_
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
_x000D_
Gmail: OAuth
Client ID
and Secret ID
. Finally click OK to close the credentials pop up.Google API
. Click on Overview in the left pane.Google API
under Social APIs section.That’s all from the Google part.
Come back to your application, open App_start/Startup.Auth.cs
and uncomment the following snippet
app.UseGoogleAuthentication(new GoogleOAuth2AuthenticationOptions()
{
ClientId = "",
ClientSecret = ""
});
Update the ClientId
and ClientSecret
with the values from Google API
credentials which you have created already.
Gmail
id.Gmail
id into your application database.java.util.MissingResourceException: Can't find bundle for base name org.jfree.chart.LocalizationBundle, locale en_US
To the point, the exception message tells in detail that you need to have either of the following files in the classpath:
/org/jfree/chart/LocalizationBundle.properties
or
/org/jfree/chart/LocalizationBundle_en.properties
or
/org/jfree/chart/LocalizationBundle_en_US.properties
Also see the official Java tutorial about resourcebundles for more information.
But as this is actually a 3rd party managed properties file, you shouldn't create one yourself. It should be already available in the JFreeChart JAR file. So ensure that you have it available in the classpath during runtime. Also ensure that you're using the right version, the location of the propertiesfile inside the package tree might have changed per JFreeChart version.
When executing a JAR file, you can use the -cp
argument to specify the classpath. E.g.:
java -jar -cp c:/path/to/jfreechart.jar yourfile.jar
Alternatively you can specify the classpath as class-path
entry in the JAR's manifest file. You can use in there relative paths which are relative to the JAR file itself. Do not use the %CLASSPATH%
environment variable, it's ignored by JAR's and everything else which aren't executed with java.exe
without -cp
, -classpath
and -jar
arguments.
Check this one out, too:
$(document).ready(function() {
if($("input:radio[name='yourRadioGroupName'][value='yourvalue']").is(":checked")) {
//its checked
}
});