The Java 5 documentation also recommends using this method for the same purpose.
This method can only be used to measure elapsed time and is not related to any other notion of system or wall-clock time.
Add this attribute to you activity in manifest file. android:noHistory="true"
You can use termcolor for this:
sudo pip install termcolor
To print a colored bold:
from termcolor import colored
print(colored('Hello', 'green', attrs=['bold']))
For more information, see termcolor on PyPi.
simple-colors is another package with similar syntax:
from simple_colors import *
print(green('Hello', ['bold'])
The equivalent in colorama may be Style.BRIGHT
.
Felipsmartins is correct.
It is worth mentioning that it is because you cannot really use the -d/--data option if this is not a POST request. But this is still possible if you use the -G option.
Which means you can do this:
curl -X DELETE -G 'http://localhost:5000/locations' -d 'id=3'
Here it is a bit silly but when you are on the command line and you have a lot of parameters, it is a lot tidier.
I am saying this because cURL commands are usually quite long, so it is worth making it on more than one line escaping the line breaks.
curl -X DELETE -G \
'http://localhost:5000/locations' \
-d id=3 \
-d name=Mario \
-d surname=Bros
This is obviously a lot more comfortable if you use zsh. I mean when you need to re-edit the previous command because zsh lets you go line by line. (just saying)
Hope it helps.
There is no direct way to do this - Java has no Map literals (yet - I think they were proposed for Java 8).
Some people like this:
Map<String,String> test = new HashMap<String, String>(){{
put("test","test"); put("test","test");}};
This creates an anonymous subclass of HashMap, whose instance initializer puts these values. (By the way, a map can't contain twice the same value, your second put will overwrite the first one. I'll use different values for the next examples.)
The normal way would be this (for a local variable):
Map<String,String> test = new HashMap<String, String>();
test.put("test","test");
test.put("test1","test2");
If your test
map is an instance variable, put the initialization in a constructor or instance initializer:
Map<String,String> test = new HashMap<String, String>();
{
test.put("test","test");
test.put("test1","test2");
}
If your test
map is a class variable, put the initialization in a static initializer:
static Map<String,String> test = new HashMap<String, String>();
static {
test.put("test","test");
test.put("test1","test2");
}
If you want your map to never change, you should after the initialization wrap your map by Collections.unmodifiableMap(...)
. You can do this in a static initializer too:
static Map<String,String> test;
{
Map<String,String> temp = new HashMap<String, String>();
temp.put("test","test");
temp.put("test1","test2");
test = Collections.unmodifiableMap(temp);
}
(I'm not sure if you can now make test
final ... try it out and report here.)
As also explained in this Wikipedia article Curve orientation, given 3 points p
, q
and r
on the plane (i.e. with x and y coordinates), you can calculate the sign of the following determinant
If the determinant is negative (i.e. Orient(p, q, r) < 0
), then the polygon is oriented clockwise (CW). If the determinant is positive (i.e. Orient(p, q, r) > 0
), the polygon is oriented counterclockwise (CCW). The determinant is zero (i.e. Orient(p, q, r) == 0
) if points p
, q
and r
are collinear.
In the formula above, we prepend the ones in front of the coordinates of p
, q
and r
because we are using homogeneous coordinates.
Not being a developer I found a solution in running multiple ps commands in one line. E.g:
powershell "& 'c:\path with spaces\to\executable.exe' -arguments ; second command ; etc
By placing a " (double quote) before the & (ampersand) it executes the executable. In none of the examples I have found this was mentioned. Without the double quotes the ps prompt opens and waits for input.
There were several problems in your code. Here you have a functional version you can analyze (Lets set 'hello' as the target word):
word = 'hello'
so_far = "-" * len(word) # Create variable so_far to contain the current guess
while word != so_far: # if still not complete
print(so_far)
guess = input('>> ') # get a char guess
if guess in word:
print("\nYes!", guess, "is in the word!")
new = ""
for i in range(len(word)):
if guess == word[i]:
new += guess # fill the position with new value
else:
new += so_far[i] # same value as before
so_far = new
else:
print("try_again")
print('finish')
I tried to write it for py3k with a py2k ide, be careful with errors.
Stumbled upon this one but you can get it by using the following as long as you import numpy.
import numpy as np
[y, x] = np.shape(img[:,:,0])
It works because you ignore all but one color and then the image is just 2D so shape tells you how bid it is. Still kinda new to Python but seems like a simple way to do it.
Girls and guys we are in 2019 and we do not have that much time for typing... So lets do this cool new fancy ECMAScript 2016:
Object.keys(obj).forEach(e => console.log(`key=${e} value=${obj[e]}`));
As per this question's answer
You will want something like this:
<bindings> <basicHttpBinding> <binding name="basicHttp" allowCookies="true" maxReceivedMessageSize="20000000" maxBufferSize="20000000" maxBufferPoolSize="20000000"> <readerQuotas maxDepth="32" maxArrayLength="200000000" maxStringContentLength="200000000"/> </binding> </basicHttpBinding> </bindings>
Please also read comments to the accepted answer there, those contain valuable input.
I've needed this and after some research I came up with this (jQuery needed):
First, right after the <body>
tag add this:
<div id="loading">
<img id="loading-image" src="images/ajax-loader.gif" alt="Loading..." />
</div>
Then add the style class for the div and image to your CSS:
#loading {
width: 100%;
height: 100%;
top: 0;
left: 0;
position: fixed;
display: block;
opacity: 0.7;
background-color: #fff;
z-index: 99;
text-align: center;
}
#loading-image {
position: absolute;
top: 100px;
left: 240px;
z-index: 100;
}
Then, add this javascript to your page (preferably at the end of your page, before your closing </body>
tag, of course):
<script>
$(window).load(function() {
$('#loading').hide();
});
</script>
Finally, adjust the position of the loading image and the background-colour
of the loading div with the style class.
This is it, should work just fine. But of course you have to have an ajax-loader.gif
somewhere. Freebies here. (Right-click > Save Image As...)
After utilizing some of the answers above, don't forget that after an apt install, a total reboot might be in order.
URL url = new URL("http://www.google.com/humans.txt");
HttpURLConnection http = (HttpURLConnection)url.openConnection();
int statusCode = http.getResponseCode();
Here is small utility class that converts JSON to DataFrame and back: Hope you find this helpful.
# -*- coding: utf-8 -*-
from pandas.io.json import json_normalize
class DFConverter:
#Converts the input JSON to a DataFrame
def convertToDF(self,dfJSON):
return(json_normalize(dfJSON))
#Converts the input DataFrame to JSON
def convertToJSON(self, df):
resultJSON = df.to_json(orient='records')
return(resultJSON)
In my case I had a panda Series where the values are tuples of characters:
Out[67]
0 (H, H, H, H)
1 (H, H, H, T)
2 (H, H, T, H)
3 (H, H, T, T)
4 (H, T, H, H)
Therefore I could use indexing to filter the series, but to create the index I needed apply
. My condition is "find all tuples which have exactly one 'H'".
series_of_tuples[series_of_tuples.apply(lambda x: x.count('H')==1)]
I admit it is not "chainable", (i.e. notice I repeat series_of_tuples
twice; you must store any temporary series into a variable so you can call apply(...) on it).
There may also be other methods (besides .apply(...)
) which can operate elementwise to produce a Boolean index.
Many other answers (including accepted answer) using the chainable functions like:
.compress()
.where()
.loc[]
[]
These accept callables (lambdas) which are applied to the Series, not to the individual values in those series!
Therefore my Series of tuples behaved strangely when I tried to use my above condition / callable / lambda, with any of the chainable functions, like .loc[]
:
series_of_tuples.loc[lambda x: x.count('H')==1]
Produces the error:
KeyError: 'Level H must be same as name (None)'
I was very confused, but it seems to be using the Series.count series_of_tuples.count(...)
function , which is not what I wanted.
I admit that an alternative data structure may be better:
This creates a series of strings (i.e. by concatenating the tuple; joining the characters in the tuple on a single string)
series_of_tuples.apply(''.join)
So I can then use the chainable Series.str.count
series_of_tuples.apply(''.join).str.count('H')==1
According to the go documentation, Unix returns a local time.
Unix returns the local Time corresponding to the given Unix time
This means the output would depend on the machine your code runs on, which, most often is what you need, but sometimes, you may want to have the value in UTC.
To do so, I adapted the snippet to make it return a time in UTC:
i, err := strconv.ParseInt("1405544146", 10, 64)
if err != nil {
panic(err)
}
tm := time.Unix(i, 0)
fmt.Println(tm.UTC())
This prints on my machine (in CEST)
2014-07-16 20:55:46 +0000 UTC
You'll need to use DrawEllipse if you want to draw a circle using GDI+.
An example is here: http://www.websupergoo.com/helpig6net/source/3-examples/9-drawgdi.htm
You could create interfaces for animal classes (class in the biological meaning), such as public interface Equidae
for horses and public interface Avialae
for birds (I'm no biologist, so the terms may be wrong).
Then you can still create a
public class Bird implements Avialae {
}
and
public class Horse implements Equidae {}
and also
public class Pegasus implements Avialae, Equidae {}
In order to reduce duplicate code, you could create an abstract class that contains most of the common code of the animals you want to implement.
public abstract class AbstractHorse implements Equidae {}
public class Horse extends AbstractHorse {}
public class Pegasus extends AbstractHorse implements Avialae {}
I'd like to add one more detail. As Brian remarks, this is something the OP already knew.
However, I want to emphasize, that I suggest to bypass the "multi-inheritance" problem with interfaces and that I don't recommend to use interfaces that represent already a concrete type (such as Bird) but more a behavior (others refer to duck-typing, which is good, too, but I mean just: the biological class of birds, Avialae). I also don't recommend to use interface names starting with a capital 'I', such as IBird
, which just tells nothing about why you need an interface. That's the difference to the question: construct the inheritance hierarchy using interfaces, use abstract classes when useful, implement concrete classes where needed and use delegation if appropriate.
ExpressiveAnnotations gives you such a possibility:
[Required]
[AssertThat("Length(FieldA) + Length(FieldB) + Length(FieldC) + Length(FieldD) > 50")]
public string FieldA { get; set; }
Code and explanation from Pointer Basics:
The dereference operation starts at the pointer and follows its arrow over to access its pointee. The goal may be to look at the pointee state or to change the pointee state. The dereference operation on a pointer only works if the pointer has a pointee -- the pointee must be allocated and the pointer must be set to point to it. The most common error in pointer code is forgetting to set up the pointee. The most common runtime crash because of that error in the code is a failed dereference operation. In Java the incorrect dereference will be flagged politely by the runtime system. In compiled languages such as C, C++, and Pascal, the incorrect dereference will sometimes crash, and other times corrupt memory in some subtle, random way. Pointer bugs in compiled languages can be difficult to track down for this reason.
void main() {
int* x; // Allocate the pointer x
x = malloc(sizeof(int)); // Allocate an int pointee,
// and set x to point to it
*x = 42; // Dereference x to store 42 in its pointee
}
echo do_shortcode('[CONTACT-US-FORM]');
Use this in your template.
Look here for more: Do Shortcode
The format
method was introduced in Python 2.6. It is more capable and not much more difficult to use:
>>> "Hello {}, my name is {}".format('john', 'mike')
'Hello john, my name is mike'.
>>> "{1}, {0}".format('world', 'Hello')
'Hello, world'
>>> "{greeting}, {}".format('world', greeting='Hello')
'Hello, world'
>>> '%s' % name
"{'s1': 'hello', 's2': 'sibal'}"
>>> '%s' %name['s1']
'hello'
For this example you really should just use an outer join.
declare
begin
FOR attr_rec IN (
select attr
from USER_TABLE u
left outer join attribute_table a
on ( u.USERTYPE = 'X' and a.user_id = u.id )
) LOOP
<process records>
<if primary key of attribute_table is null
then the attribute does not exist for this user.>
END LOOP;
END;
Already answered above but wanted to share.
Will not work in IE though. thanks for mentioning it @Mahmoud
var array1 = [1, 2, 3];_x000D_
_x000D_
console.log(array1.includes(2));_x000D_
// expected output: true_x000D_
_x000D_
var pets = ['cat', 'dog', 'bat'];_x000D_
_x000D_
console.log(pets.includes('cat'));_x000D_
// expected output: true_x000D_
_x000D_
console.log(pets.includes('at'));_x000D_
// expected output: false
_x000D_
got some reference Here. they also have Polyfill for above.
This worked for me (i wanted to make id primary and set auto increment)
ALTER TABLE table_name
CHANGE id
id
INT PRIMARY KEY AUTO_INCREMENT;
It really depends on how the server on the other side is configured and with what modules for how it handles a blob post. You can try putting the desired name in the path for your post.
request.open(
"POST",
"/upload/myname.bmp",
true
);
You can use tail command as follows:
tail -100 <log file> > newLogfile
Now last 100 lines will be present in newLogfile
EDIT:
More recent versions of tail as mentioned by twalberg use command:
tail -n 100 <log file> > newLogfile
Well, this solution might sound very silly, but can save you in certain conditions.
A friend of mine just ran into accidentally committing very some huge files (four auto-generated files ranging between 3GB to 5GB each) and then made some additional code commits on top of that before realizing the problem that git push
wasn't working any longer!
The files had been listed in .gitignore
but after renaming the container folder, they got exposed and committed! And now there were a few more commits of the code on top of that, but push
was running forever (trying to upload GB of data!) and finally would fail due to Github's file size limits.
The problem with interactive rebase or anything similar was that they would deal with poking around these huge files and would take forever to do anything. Nevertheless, after spending almost an hour in the CLI, we weren't sure if the files (and deltas) are actually removed from the history or simply not included in the current commits. The push wasn't working either and my friend was really stuck.
So, the solution I came up with was:
~/Project-old
.~/Project
). cp -r
the files from ~/Project-old
folder to ~/Project
. mv
ed, and included in .gitignore
properly. .git
folder in the recently-cloned ~/Project
by the old one. That's where the logs of the problematic history lives!push
'ed.The biggest problem with this solution is, it deals with manual copying some files, and also it merges all the recent commits into one (obviously with a new commit-hash.) B
The big benefits are that, it is very clear in every step, it works great for huge files (as well as sensitive ones), and it doesn't leave any trace in history behind!
When you declare
var a=[];
you are declaring a empty array.
But when you are declaring
var a={};
you are declaring a Object .
Although Array is also Object in Javascript but it is numeric key paired values. Which have all the functionality of object but Added some few method of Array like Push,Splice,Length and so on.
So if you want Some values where you need to use numeric keys use Array. else use object. you can Create object like:
var a={name:"abc",age:"14"};
And can access values like
console.log(a.name);
Check at the server side that it is listening at the port 2080. First try to confirm it on the server machine by issuing telnet to that port:
telnet localhost 2080
If it is listening, it is able to respond.
If a parameter is passed as Any to your function, you can test on a special type like so :
func isADate ( aValue : Any?) -> Bool{
if (aValue as? Date) != nil {
print ("a Date")
return true
}
else {
print ("This is not a date ")
return false
}
}
You need to decode data from input string into unicode, before using it, to avoid encoding problems.
field.text = data.decode("utf8")
Very late but try this out:
SELECT ColumnID, Column1, value --Do not change 'value' name. Leave it as it is.
FROM tbl_Sample
CROSS APPLY STRING_SPLIT(Tags, ','); --'Tags' is the name of column containing comma separated values
So we were having this: tbl_Sample :
ColumnID| Column1 | Tags
--------|-----------|-------------
1 | ABC | 10,11,12
2 | PQR | 20,21,22
After running this query:
ColumnID| Column1 | value
--------|-----------|-----------
1 | ABC | 10
1 | ABC | 11
1 | ABC | 12
2 | PQR | 20
2 | PQR | 21
2 | PQR | 22
Thanks!
I use laravel 7.x and I used this as a workaround:->get()->pluck('id')->toArray();
it gives back an array of ids [50,2,3]
and this is the whole query I used:
$article_tags = DB::table('tags')
->join('taggables', function ($join) use ($id) {
$join->on('tags.id', '=', 'taggables.tag_id');
$join->where([
['taggable_id', '=', $id],
['taggable_type','=','article']
]);
})->select('tags.id')->get()->pluck('id')->toArray();
Note : Only if you are not using angular modules
For some reason this is not in the docs but I had to import the custom pipe in the component
import {UsersPipe} from './users-filter.pipe'
@Component({
...
pipes: [UsersPipe]
})
net stop <your service> && net start <your service>
No net restart
, unfortunately.
You can use import nbimporter
then import notebookName
the IDENT_OUTPUT did not do anything for me, and to give a complete answer that works with my jackson 2.2.3 jars:
public static void main(String[] args) throws IOException {
byte[] jsonBytes = Files.readAllBytes(Paths.get("C:\\data\\testfiles\\single-line.json"));
ObjectMapper objectMapper = new ObjectMapper();
Object json = objectMapper.readValue( jsonBytes, Object.class );
System.out.println( objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString( json ) );
}
Yep, just add parenthesis (calling the function). Make sure the function is in scope and actually returns something.
<ul class="ui-listview ui-radiobutton" ng-repeat="meter in meters">
<li class = "ui-divider">
{{ meter.DESCRIPTION }}
{{ htmlgeneration() }}
</li>
</ul>
Alternatively, just GROUP BY
the hour and day:
SELECT CAST(Startdate as DATE) as 'StartDate',
CAST(DATEPART(Hour, StartDate) as varchar) + ':00' as 'Hour',
COUNT(*) as 'Ct'
FROM #Events
GROUP BY CAST(Startdate as DATE), DATEPART(Hour, StartDate)
ORDER BY CAST(Startdate as DATE) ASC
output:
StartDate Hour Ct
2007-01-01 0:00 3
2007-01-02 5:00 2
2007-01-03 4:00 1
2007-01-07 3:00 1
@RequestParam
makes Spring to map request parameters from the GET/POST request to your method argument.
GET Request
http://testwebaddress.com/getInformation.do?city=Sydney&country=Australia
public String getCountryFactors(@RequestParam(value = "city") String city,
@RequestParam(value = "country") String country){ }
POST Request
@RequestBody
makes Spring to map entire request to a model class and from there you can retrieve or set values from its getter and setter methods. Check below.
http://testwebaddress.com/getInformation.do
You have JSON
data as such coming from the front end and hits your controller class
{
"city": "Sydney",
"country": "Australia"
}
Java
Code - backend (@RequestBody
)
public String getCountryFactors(@RequestBody Country countryFacts)
{
countryFacts.getCity();
countryFacts.getCountry();
}
public class Country {
private String city;
private String country;
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
}
Return a tuple:
func getTime() -> (Int, Int, Int) {
...
return ( hour, minute, second)
}
Then it's invoked as:
let (hour, minute, second) = getTime()
or:
let time = getTime()
println("hour: \(time.0)")
You're calling both wait
and notifyAll
without using a synchronized
block. In both cases the calling thread must own the lock on the monitor you call the method on.
From the docs for notify
(wait
and notifyAll
have similar documentation but refer to notify
for the fullest description):
This method should only be called by a thread that is the owner of this object's monitor. A thread becomes the owner of the object's monitor in one of three ways:
- By executing a synchronized instance method of that object.
- By executing the body of a synchronized statement that synchronizes on the object.
- For objects of type Class, by executing a synchronized static method of that class.
Only one thread at a time can own an object's monitor.
Only one thread will be able to actually exit wait
at a time after notifyAll
as they'll all have to acquire the same monitor again - but all will have been notified, so as soon as the first one then exits the synchronized block, the next will acquire the lock etc.
Short answer
The purpose of meshgrid
is to help remplace Python loops (slow interpreted code) by vectorized operations within C NumPy library.
Borrowed from this site.
x = np.arange(-4, 4, 0.25)
y = np.arange(-4, 4, 0.25)
X, Y = np.meshgrid(x, y)
R = np.sqrt(X**2 + Y**2)
Z = np.sin(R)
meshgrid
is used to create pairs of coordinates between -4 and +4 with .25 increments in each direction X and Y. Each pair is then used to find R, and Z from it. This way of preparing "a grid" of coordinates is frequently used in plotting 3D surfaces, or coloring 2D surfaces.
Details: Python for-loop vs NumPy vector operation
To take a more simple example, let's say we have two sequences of values,
a = [2,7,9,20]
b = [1,6,7,9] ?
and we want to perform an operation on each possible pair of values, one taken from the first list, one taken from the second list. We also want to store the result. For example, let's say we want to get the sum of the values for each possible pair.
Slow and laborious method
c = []
for i in range(len(b)):
row = []
for j in range(len(a)):
row.append (a[j] + b[i])
c.append (row)
print (c)
Result:
[[3, 8, 10, 21],
[8, 13, 15, 26],
[9, 14, 16, 27],
[11, 16, 18, 29]]
Python is interpreted, these loops are relatively slow to execute.
Fast and easy method
meshgrid
is intended to remove the loops from the code. It returns two arrays (i and j below) which can be combined to scan all the existing pairs like this:
i,j = np.meshgrid (a,b)
c = i + j
print (c)
Result:
[[ 3 8 10 21]
[ 8 13 15 26]
[ 9 14 16 27]
[11 16 18 29]]
Meshgrid under the hood
The two arrays prepared by meshgrid
are:
(array([[ 2, 7, 9, 20],
[ 2, 7, 9, 20],
[ 2, 7, 9, 20],
[ 2, 7, 9, 20]]),
array([[1, 1, 1, 1],
[6, 6, 6, 6],
[7, 7, 7, 7],
[9, 9, 9, 9]]))
These arrays are created by repeating the values provided. One contains the values in identical rows, the other contains the other values in identical columns. The number of rows and column is determined by the number of elements in the other sequence.
The two arrays created by meshgrid
are therefore shape compatible for a vector operation. Imagine x and y sequences in the code at the top of page having a different number of elements, X and Y resulting arrays will be shape compatible anyway, not requiring any broadcast.
Origin
numpy.meshgrid
comes from MATLAB, like many other NumPy functions. So you can also study the examples from MATLAB to see meshgrid
in use, the code for the 3D plotting looks the same in MATLAB.
That only works for numbers less than 1.
select to_char(12.34, '0D99') from dual;
-- Result: #####
This won't work.
You could do something like this but this results in leading whitespaces:
select to_char(12.34, '999990D99') from dual;
-- Result: ' 12,34'
Ultimately, you could add a TRIM to get rid of the whitespaces again but I wouldn't consider that a proper solution either...
select trim(to_char(12.34, '999990D99')) from dual;
-- Result: 12,34
Again, this will only work for numbers with 6 digits max.
Edit: I wanted to add this as a comment on DCookie's suggestion but I can't.
I got same problem when I got new laptop with Windows8/Kaspesky installed on it. I got problems eclipse: cannot open git-upload-pack. I also got problems with maven. I also got problem with Skype.
When I disabled Kaspersky everything started to work properly.
There is a lot more to coalesce than just a replacement for ISNULL. I completely agree that the official "documentation" of coalesce is vague and unhelpful. This article helps a lot. http://www.mssqltips.com/sqlservertip/1521/the-many-uses-of-coalesce-in-sql-server/
Maybe you can try the following :
var i = 0;
function AjaxSendForm(url, placeholder, form, append) {
var data = $(form).serialize();
append = (append === undefined ? false : true); // whatever, it will evaluate to true or false only
$.ajax({
type: 'POST',
url: url,
data: data,
beforeSend: function() {
// setting a timeout
$(placeholder).addClass('loading');
i++;
},
success: function(data) {
if (append) {
$(placeholder).append(data);
} else {
$(placeholder).html(data);
}
},
error: function(xhr) { // if error occured
alert("Error occured.please try again");
$(placeholder).append(xhr.statusText + xhr.responseText);
$(placeholder).removeClass('loading');
},
complete: function() {
i--;
if (i <= 0) {
$(placeholder).removeClass('loading');
}
},
dataType: 'html'
});
}
This way, if the beforeSend
statement is called before the complete
statement i
will be greater than 0 so it will not remove the class. Then only the last call will be able to remove it.
I cannot test it, let me know if it works or not.
#include<stdio.h>
#include<string.h>
main()
{
int i=0,n;
int j=0;
char str[]=" Nar ayan singh ";
char *ptr,*ptr1;
printf("sizeof str:%ld\n",strlen(str));
while(str[i]==' ')
{
memcpy (str,str+1,strlen(str)+1);
}
printf("sizeof str:%ld\n",strlen(str));
n=strlen(str);
while(str[n]==' ' || str[n]=='\0')
n--;
str[n+1]='\0';
printf("str:%s ",str);
printf("sizeof str:%ld\n",strlen(str));
}
If you use the Angular CLI to create your components, let's say CarComponent
, it attaches app
to the selector name (i.e app-car
) and this throws the above error when you reference the component in the parent view. Therefore you either have to change the selector name in the parent view to let's say <app-car></app-car>
or change the selector in the CarComponent
to selector: 'car'
Sass cannot perform arithmetic on values that cannot be converted from one unit to the next. Sass has no way of knowing exactly how wide "100%" is in terms of pixels or any other unit. That's something only the browser knows.
You need to use calc()
instead. Check browser compatibility on Can I use...
.foo {
height: calc(25% - 5px);
}
If your values are in variables, you may need to use interpolation turn them into strings (otherwise Sass just tries to perform arithmetic):
$a: 25%;
$b: 5px;
.foo {
width: calc(#{$a} - #{$b});
}
I stuck with my original code and also included a fade in 'back-to-top' link making use of this code and a bit from here too:
http://webdesignerwall.com/tutorials/animated-scroll-to-top
Works well :)
It's easy. If you have two or more running container, complete next steps:
docker network create myNetwork
docker network connect myNetwork web1
docker network connect myNetwork web2
Now you connect from web1 to web2 container or the other way round.
Use the internal network IP addresses which you can find by running:
docker network inspect myNetwork
Note that only internal IP addresses and ports are accessible to the containers connected by the network bridge.
So for example assuming that web1 container was started with: docker run -p 80:8888 web1
(meaning that its server is running on port 8888 internally), and inspecting myNetwork
shows that web1's IP is 172.0.0.2, you can connect from web2 to web1 using curl 172.0.0.2:8888
).
Try this
$('#checkbox1').click(function() {
if (!this.checked) {
var sure = confirm("Are you sure?");
this.checked = sure;
$('#textbox1').val(sure.toString());
}
});
Try this:
function reload(){_x000D_
var container = document.getElementById("yourDiv");_x000D_
var content = container.innerHTML;_x000D_
container.innerHTML= content; _x000D_
_x000D_
//this line is to watch the result in console , you can remove it later _x000D_
console.log("Refreshed"); _x000D_
}
_x000D_
<a href="javascript: reload()">Click to Reload</a>_x000D_
<div id="yourDiv">The content that you want to refresh/reload</div>
_x000D_
Hope it works. Let me know
This can be easily handled with pydantic, as it already has this functionality built-in.
Option 1: normal way
from pydantic import BaseModel
class testclass(BaseModel):
value1: str = "a"
value2: str = "b"
test = testclass()
>>> print(test.json(indent=4))
{
"value1": "a",
"value2": "b"
}
Option 2: using pydantic's dataclass
import json
from pydantic.dataclasses import dataclass
from pydantic.json import pydantic_encoder
@dataclass
class testclass:
value1: str = "a"
value2: str = "b"
test = testclass()
>>> print(json.dumps(test, indent=4, default=pydantic_encoder))
{
"value1": "a",
"value2": "b"
}
I would do something like:
filename = "mynumbers.txt"
mynumbers = []
with open(filename) as f:
for line in f:
mynumbers.append([int(n) for n in line.strip().split(',')])
for pair in mynumbers:
try:
x,y = pair[0],pair[1]
# Do Something with x and y
except IndexError:
print "A line in the file doesn't have enough entries."
The with open is recommended in http://docs.python.org/tutorial/inputoutput.html since it makes sure files are closed correctly even if an exception is raised during the processing.
In your Page_Load you will want to clear out the normal output and write your own, for example:
string json = "{\"name\":\"Joe\"}";
Response.Clear();
Response.ContentType = "application/json; charset=utf-8";
Response.Write(json);
Response.End();
To convert a C# object to JSON you can use a library such as Json.NET.
Instead of getting your .aspx page to output JSON though, consider using a Web Service (asmx) or WCF, both of which can output JSON.
It works fine for me: http://jsfiddle.net/qwertynl/htb9h/
My javascript:
var app = angular.module("myApp", [])
app.controller("MyCtrl", ['$scope', function($scope) {
$scope.telephone = []; // << remember to set this
}]);
Let's polyfill:
if(!AbortController){
class AbortController {
constructor() {
this.aborted = false;
this.signal = this.signal.bind(this);
}
signal(abortFn, scope) {
if (this.aborted) {
abortFn.apply(scope, { name: 'AbortError' });
this.aborted = false;
} else {
this.abortFn = abortFn.bind(scope);
}
}
abort() {
if (this.abortFn) {
this.abortFn({ reason: 'canceled' });
this.aborted = false;
} else {
this.aborted = true;
}
}
}
const originalFetch = window.fetch;
const customFetch = (url, options) => {
const { signal } = options || {};
return new Promise((resolve, reject) => {
if (signal) {
signal(reject, this);
}
originalFetch(url, options)
.then(resolve)
.catch(reject);
});
};
window.fetch = customFetch;
}
Please have in mind that the code is not tested! Let me know if you have tested it and something didn't work. It may give you warnings that you try to overwrite the 'fetch' function from the JavaScript official library.
You should just be able to use the savefig
method of sns_plot
directly.
sns_plot.savefig("output.png")
For clarity with your code if you did want to access the matplotlib figure that sns_plot
resides in then you can get it directly with
fig = sns_plot.fig
In this case there is no get_figure
method as your code assumes.
45 characters.
You might expect an address to be
0000:0000:0000:0000:0000:0000:0000:0000
8 * 4 + 7 = 39
8 groups of 4 digits with 7 :
between them.
But if you have an IPv4-mapped IPv6 address, the last two groups can be written in base 10 separated by .
, eg. [::ffff:192.168.100.228]
. Written out fully:
0000:0000:0000:0000:0000:ffff:192.168.100.228
(6 * 4 + 5) + 1 + (4 * 3 + 3) = 29 + 1 + 15 = 45
Note, this is an input/display convention - it's still a 128 bit address and for storage it would probably be best to standardise on the raw colon separated format, i.e. [0000:0000:0000:0000:0000:ffff:c0a8:64e4]
for the address above.
postgresql.conf
is located in PostgreSQL's data directory. The data directory is configured during the setup and the setting is saved as PGDATA
entry in c:\Program Files\PostgreSQL\<version>\pg_env.bat
, for example
@ECHO OFF
REM The script sets environment variables helpful for PostgreSQL
@SET PATH="C:\Program Files\PostgreSQL\<version>\bin";%PATH%
@SET PGDATA=D:\PostgreSQL\<version>\data
@SET PGDATABASE=postgres
@SET PGUSER=postgres
@SET PGPORT=5432
@SET PGLOCALEDIR=C:\Program Files\PostgreSQL\<version>\share\locale
Alternatively you can query your database with SHOW config_file;
if you are a superuser.
You can use a regular expression to delete white spaces , try that snippet:
Scanner scan = new Scanner(System.in);
System.out.println(scan.nextLine().replaceAll(" ", ""));
The Barack Obama app took 22 days to develop from first code to release. Three developers (although not all of them were full time). 10 people total. Figure 500-1000 man hours. Contracting rates are $100-150/hr. Figure $50000-$150000. Compare your app to Obama.app and scale accordingly.
Cursor c = scoreDb.query(Table_Name, score, null, null, null, null, Column+" DESC");
Try this
As of Telegram Desktop 1.3 you can format your messages and add links.
[Ctrl+K] = create link (https://my.website)
Other useful hotkeys are:
[Ctrl+B] = bold
[Ctrl+I] = italic
[Ctrl+Shift+M] = monospace
[Ctrl+Shift+N] = clear formatting
You can create a new branch based on old-name branch. Just like this, then delete the old branch, over!!!
You need to take out the $ signs before the row numbers in the formula....and the row number used in the formula should correspond to the first row of data, so if you are applying this to the ("applies to") range $B$2:$B$5 it must be this formula
=$B2>$C2
by using that "relative" version rather than your "absolute" one Excel (implicitly) adjusts the formula for each row in the range, as if you were copying the formula down
For those not getting the -ms-border-radius: or the border-radius: to work in IE 10,11 And it renders all square then follow these steps:
Long story short, EOF
marker(but a different literal can be used as well) is a heredoc format that allows you to provide your input as multiline.
A lot of confusion comes from how cat
actually works it seems.
You can use cat
with >>
or >
as follows:
$ cat >> temp.txt
line 1
line 2
While cat
can be used this way when writing manually into console, it's not convenient if I want to provide the input in a more declarative way so that it can be reused by tools and also to keep indentations, whitespaces, etc.
Heredoc allows to define your entire input as if you are not working with stdin
but typing in a separate text editor. This is what Wikipedia article means by:
it is a section of a source code file that is treated as if it were a separate file.
You can set a custom toolbar item color dynamically by creating a custom toolbar class:
package view;
import android.app.Activity;
import android.content.Context;
import android.graphics.ColorFilter;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffColorFilter;
import android.support.v7.internal.view.menu.ActionMenuItemView;
import android.support.v7.widget.ActionMenuView;
import android.support.v7.widget.Toolbar;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AutoCompleteTextView;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
public class CustomToolbar extends Toolbar{
public CustomToolbar(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
// TODO Auto-generated constructor stub
}
public CustomToolbar(Context context, AttributeSet attrs) {
super(context, attrs);
// TODO Auto-generated constructor stub
}
public CustomToolbar(Context context) {
super(context);
// TODO Auto-generated constructor stub
ctxt = context;
}
int itemColor;
Context ctxt;
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
Log.d("LL", "onLayout");
super.onLayout(changed, l, t, r, b);
colorizeToolbar(this, itemColor, (Activity) ctxt);
}
public void setItemColor(int color){
itemColor = color;
colorizeToolbar(this, itemColor, (Activity) ctxt);
}
/**
* Use this method to colorize toolbar icons to the desired target color
* @param toolbarView toolbar view being colored
* @param toolbarIconsColor the target color of toolbar icons
* @param activity reference to activity needed to register observers
*/
public static void colorizeToolbar(Toolbar toolbarView, int toolbarIconsColor, Activity activity) {
final PorterDuffColorFilter colorFilter
= new PorterDuffColorFilter(toolbarIconsColor, PorterDuff.Mode.SRC_IN);
for(int i = 0; i < toolbarView.getChildCount(); i++) {
final View v = toolbarView.getChildAt(i);
doColorizing(v, colorFilter, toolbarIconsColor);
}
//Step 3: Changing the color of title and subtitle.
toolbarView.setTitleTextColor(toolbarIconsColor);
toolbarView.setSubtitleTextColor(toolbarIconsColor);
}
public static void doColorizing(View v, final ColorFilter colorFilter, int toolbarIconsColor){
if(v instanceof ImageButton) {
((ImageButton)v).getDrawable().setAlpha(255);
((ImageButton)v).getDrawable().setColorFilter(colorFilter);
}
if(v instanceof ImageView) {
((ImageView)v).getDrawable().setAlpha(255);
((ImageView)v).getDrawable().setColorFilter(colorFilter);
}
if(v instanceof AutoCompleteTextView) {
((AutoCompleteTextView)v).setTextColor(toolbarIconsColor);
}
if(v instanceof TextView) {
((TextView)v).setTextColor(toolbarIconsColor);
}
if(v instanceof EditText) {
((EditText)v).setTextColor(toolbarIconsColor);
}
if (v instanceof ViewGroup){
for (int lli =0; lli< ((ViewGroup)v).getChildCount(); lli ++){
doColorizing(((ViewGroup)v).getChildAt(lli), colorFilter, toolbarIconsColor);
}
}
if(v instanceof ActionMenuView) {
for(int j = 0; j < ((ActionMenuView)v).getChildCount(); j++) {
//Step 2: Changing the color of any ActionMenuViews - icons that
//are not back button, nor text, nor overflow menu icon.
final View innerView = ((ActionMenuView)v).getChildAt(j);
if(innerView instanceof ActionMenuItemView) {
int drawablesCount = ((ActionMenuItemView)innerView).getCompoundDrawables().length;
for(int k = 0; k < drawablesCount; k++) {
if(((ActionMenuItemView)innerView).getCompoundDrawables()[k] != null) {
final int finalK = k;
//Important to set the color filter in seperate thread,
//by adding it to the message queue
//Won't work otherwise.
//Works fine for my case but needs more testing
((ActionMenuItemView) innerView).getCompoundDrawables()[finalK].setColorFilter(colorFilter);
// innerView.post(new Runnable() {
// @Override
// public void run() {
// ((ActionMenuItemView) innerView).getCompoundDrawables()[finalK].setColorFilter(colorFilter);
// }
// });
}
}
}
}
}
}
}
then refer to it in your layout file. Now you can set a custom color using
toolbar.setItemColor(Color.Red);
Sources:
I found the information to do this here: How to dynamicaly change Android Toolbar icons color
and then I edited it, improved upon it, and posted it here: GitHub:AndroidDynamicToolbarItemColor
I suggest using a utility as suggested by ThomasP, and then link that into your build process. An external file is still present to contain the text, but the file is not read at runtime. The workflow is then:
class TextBlock {...
followed by a static string which is auto-generated from the resource fileIn Python, "privacy" depends on "consenting adults'" levels of agreement - you can't force it (any more than you can in real life;-). A single leading underscore means you're not supposed to access it "from the outside" -- two leading underscores (w/o trailing underscores) carry the message even more forcefully... but, in the end, it still depends on social convention and consensus: Python's introspection is forceful enough that you can't handcuff every other programmer in the world to respect your wishes.
((Btw, though it's a closely held secret, much the same holds for C++: with most compilers, a simple #define private public
line before #include
ing your .h
file is all it takes for wily coders to make hash of your "privacy"...!-))
date must be insert with two apostrophes' As example if the date is 2018/10/20. It can insert from these query
Query -
insert into run(id,name,dob)values(&id,'&name','2018-10-20')
I think the best option in Terms of performance (or in any terms) is to Distinct using the The IEqualityComparer interface.
Although implementing each time a new comparer for each class is cumbersome and produces boilerplate code.
So here is an extension method which produces a new IEqualityComparer on the fly for any class using reflection.
Usage:
var filtered = taskList.DistinctBy(t => t.TaskExternalId).ToArray();
Extension Method Code
public static class LinqExtensions
{
public static IEnumerable<T> DistinctBy<T, TKey>(this IEnumerable<T> items, Func<T, TKey> property)
{
GeneralPropertyComparer<T, TKey> comparer = new GeneralPropertyComparer<T,TKey>(property);
return items.Distinct(comparer);
}
}
public class GeneralPropertyComparer<T,TKey> : IEqualityComparer<T>
{
private Func<T, TKey> expr { get; set; }
public GeneralPropertyComparer (Func<T, TKey> expr)
{
this.expr = expr;
}
public bool Equals(T left, T right)
{
var leftProp = expr.Invoke(left);
var rightProp = expr.Invoke(right);
if (leftProp == null && rightProp == null)
return true;
else if (leftProp == null ^ rightProp == null)
return false;
else
return leftProp.Equals(rightProp);
}
public int GetHashCode(T obj)
{
var prop = expr.Invoke(obj);
return (prop==null)? 0:prop.GetHashCode();
}
}
Ok, well, since you didn't show any code, I'll make a few assumptions here.
Based on the ORA-1461 error, it seems that you've specified a LONG datatype in a select statement? And you're trying to bind it to an output variable? Is that right? The error is pretty straight forward. You can only bind a LONG value for insert into LONG column.
Not sure what else to say. The error is fairly self-explanatory.
In general, it's a good idea to move away from LONG datatype to a CLOB. CLOBs are much better supported, and LONG datatypes really are only there for backward compatibility.
Here's a list of LONG datatype restrictions
Hope that helps.
You can do it without setlocal
, because of the setlocal
command the variable won't survive an endlocal
because it was created in setlocal
. In this way the variable will be defined the right way.
To do that use this code:
set var1=A
set var2=B
set AB=hi
call set newvar=%%%var1%%var2%%%
echo %newvar%
Note: You MUST use call
before you set the variable or it won't work.
If the input field just needs a static default value I usually do this with jQuery:
$('#input').focus().val('Default value');
This seems to work in all browsers.
As I mentioned in this post, here is a light-weighted library I created specially for links in UILabel FRHyperLabel.
To achieve an effect like this:
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque quis blandit eros, sit amet vehicula justo. Nam at urna neque. Maecenas ac sem eu sem porta dictum nec vel tellus.
use code:
//Step 1: Define a normal attributed string for non-link texts
NSString *string = @"Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque quis blandit eros, sit amet vehicula justo. Nam at urna neque. Maecenas ac sem eu sem porta dictum nec vel tellus.";
NSDictionary *attributes = @{NSFontAttributeName: [UIFont preferredFontForTextStyle:UIFontTextStyleHeadline]};
label.attributedText = [[NSAttributedString alloc]initWithString:string attributes:attributes];
//Step 2: Define a selection handler block
void(^handler)(FRHyperLabel *label, NSString *substring) = ^(FRHyperLabel *label, NSString *substring){
NSLog(@"Selected: %@", substring);
};
//Step 3: Add link substrings
[label setLinksForSubstrings:@[@"Lorem", @"Pellentesque", @"blandit", @"Maecenas"] withLinkHandler:handler];
For special character I normally use the Unicode definition, for the '&' for example: \u0026 if I am correct. Here is a nice reference page: http://jrgraphix.net/research/unicode_blocks.php?block=0
Improving on Reza's answer:
<html><head><style>
.splitter {
width: 100%;
height: 100px;
display: flex;
}
#separator {
cursor: col-resize;
background-color: #aaa;
background-image: url("data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='10' height='30'><path d='M2 0 v30 M5 0 v30 M8 0 v30' fill='none' stroke='black'/></svg>");
background-repeat: no-repeat;
background-position: center;
width: 10px;
height: 100%;
/* Prevent the browser's built-in drag from interfering */
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
}
#first {
background-color: #dde;
width: 20%;
height: 100%;
min-width: 10px;
}
#second {
background-color: #eee;
width: 80%;
height: 100%;
min-width: 10px;
}
</style></head><body>
<div class="splitter">
<div id="first"></div>
<div id="separator" ></div>
<div id="second" ></div>
</div>
<script>
// A function is used for dragging and moving
function dragElement(element, direction)
{
var md; // remember mouse down info
const first = document.getElementById("first");
const second = document.getElementById("second");
element.onmousedown = onMouseDown;
function onMouseDown(e)
{
//console.log("mouse down: " + e.clientX);
md = {e,
offsetLeft: element.offsetLeft,
offsetTop: element.offsetTop,
firstWidth: first.offsetWidth,
secondWidth: second.offsetWidth
};
document.onmousemove = onMouseMove;
document.onmouseup = () => {
//console.log("mouse up");
document.onmousemove = document.onmouseup = null;
}
}
function onMouseMove(e)
{
//console.log("mouse move: " + e.clientX);
var delta = {x: e.clientX - md.e.clientX,
y: e.clientY - md.e.clientY};
if (direction === "H" ) // Horizontal
{
// Prevent negative-sized elements
delta.x = Math.min(Math.max(delta.x, -md.firstWidth),
md.secondWidth);
element.style.left = md.offsetLeft + delta.x + "px";
first.style.width = (md.firstWidth + delta.x) + "px";
second.style.width = (md.secondWidth - delta.x) + "px";
}
}
}
dragElement( document.getElementById("separator"), "H" );
</script></body></html>
_x000D_
You need to detect the click from js side, your HTML remaining same. Note: this method is deprecated since v3.5.5 and removed in v4.
$("button").click(function() {
var $btn = $(this);
$btn.button('loading');
// simulating a timeout
setTimeout(function () {
$btn.button('reset');
}, 1000);
});
Also, don't forget to load jQuery and Bootstrap js (based on jQuery) file in your page.
Modify Remember like this
public class MyModel
{
public string Name { get; set; }
public bool? Remember { get; set; }
}
Use nullable bool in controller and fallback to false on null like this
[HttpPost]
public ActionResult MyAction(MyModel model)
{
model.Remember = model.Remember ?? false;
Console.WriteLine(model.Remember.ToString());
}
Use the following command:
sudo apt-get install python3-tk
The following commands do not work:
sudo apt-get install python3-tkinter
sudo apt-get install python3-Tkinter
pip3 install Tkinter
pip3 install tkinter
For those who get this (terribly unclear) error:
COPY failed: stat /var/lib/docker/tmp/docker-builderXXXXXXX/abc.txt: no such file or directory
There could be loads of reasons, including:
context
overwrites the context of the Dockerfile. Your COPY statements now need to navigate a path relative to what is defined in docker-compose.yml instead of relative to your Dockerfile.COPY abc.txt /app #This won't work
.dockerignore
or .gitignore
files (be wary of wildcards)Sometimes WORKDIR /abc
followed by COPY . xyz/
works where COPY /abc xyz/
fails, but it's a bit ugly.
You can use the IAsyncResult and Action class/interface to achieve this.
public void TimeoutExample()
{
IAsyncResult result;
Action action = () =>
{
// Your code here
};
result = action.BeginInvoke(null, null);
if (result.AsyncWaitHandle.WaitOne(10000))
Console.WriteLine("Method successful.");
else
Console.WriteLine("Method timed out.");
}
You can use nircmd
project here: http://www.nirsoft.net/utils/nircmd.html
Example code:
nircmd win move ititle "cmd.exe" 5 5 10 10
nircmd win setsize ititle "cmd.exe" 30 30 100 200
nircmd cmdwait 1000 win setsize ititle "cmd.exe" 30 30 1000 600
Chrome developer tools now have the ability to list WebSocket frames and also inspect the data if the frames are not binary.
Process:
If your WebSocket connection uses binary frames then you will probably still want to use Wireshark to debug the connection. Wireshark 1.8.0 added dissector and filtering support for WebSockets. An alternative may be found in this other answer.
Gets the time to wait while trying to establish a connection before terminating the attempt and generating an error.
adding
dialog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
and
"android.permission.SYSTEM_ALERT_WINDOW"/>
in manifest
It works for me now. After even close and open the application, gave me the error at that time.
pip install packageName -t pathOfDirectory
or
pip install packageName --target pathOfDirectorty
Here's a more portable version (just for fun, it is not necessary in your case):
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from subprocess import Popen, PIPE, STDOUT
try:
from subprocess import DEVNULL # py3k
except ImportError:
import os
DEVNULL = open(os.devnull, 'wb')
text = u"René Descartes"
p = Popen(['espeak', '-b', '1'], stdin=PIPE, stdout=DEVNULL, stderr=STDOUT)
p.communicate(text.encode('utf-8'))
assert p.returncode == 0 # use appropriate for your program error handling here
To be clearer, I make an example here,
class ClassA {
class func func1() -> String {
return "func1"
}
static func func2() -> String {
return "func2"
}
/* same as above
final class func func2() -> String {
return "func2"
}
*/
}
static func
is same as final class func
Because it is final
, we can not override it in subclass as below:
class ClassB : ClassA {
override class func func1() -> String {
return "func1 in ClassB"
}
// ERROR: Class method overrides a 'final` class method
override static func func2() -> String {
return "func2 in ClassB"
}
}
This query can do the thing for you.
DECLARE
@search_string VARCHAR(100),
@table_name SYSNAME,
@table_id INT,
@column_name SYSNAME,
@sql_string VARCHAR(2000)
SET @search_string = 'StringtoSearch'
DECLARE tables_cur CURSOR FOR SELECT ss.name +'.'+ so.name [name], object_id FROM sys.objects so INNER JOIN sys.schemas ss ON so.schema_id = ss.schema_id WHERE type = 'U'
OPEN tables_cur
FETCH NEXT FROM tables_cur INTO @table_name, @table_id
WHILE (@@FETCH_STATUS = 0)
BEGIN
DECLARE columns_cur CURSOR FOR SELECT name FROM sys.columns WHERE object_id = @table_id
AND system_type_id IN (167, 175, 231, 239, 99)
OPEN columns_cur
FETCH NEXT FROM columns_cur INTO @column_name
WHILE (@@FETCH_STATUS = 0)
BEGIN
SET @sql_string = 'IF EXISTS (SELECT * FROM ' + @table_name + ' WHERE [' + @column_name + ']
LIKE ''%' + @search_string + '%'') PRINT ''' + @table_name + ', ' + @column_name + ''''
EXECUTE(@sql_string)
FETCH NEXT FROM columns_cur INTO @column_name
END
CLOSE columns_cur
DEALLOCATE columns_cur
FETCH NEXT FROM tables_cur INTO @table_name, @table_id
END
CLOSE tables_cur
DEALLOCATE tables_cur
You need to use to_timestamp()
to convert your string to a proper timestamp
value:
to_timestamp('12-01-2012 21:24:00', 'dd-mm-yyyy hh24:mi:ss')
If your column is of type DATE
(which also supports seconds), you need to use to_date()
to_date('12-01-2012 21:24:00', 'dd-mm-yyyy hh24:mi:ss')
To get this into a where
condition use the following:
select *
from TableA
where startdate >= to_timestamp('12-01-2012 21:24:00', 'dd-mm-yyyy hh24:mi:ss')
and startdate <= to_timestamp('12-01-2012 21:25:33', 'dd-mm-yyyy hh24:mi:ss')
You never need to use to_timestamp()
on a column that is of type timestamp
.
This is how you do CURL with sessions
//initial request with login data
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'http://www.example.com/login.php');
curl_setopt($ch, CURLOPT_USERAGENT,'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/32.0.1700.107 Chrome/32.0.1700.107 Safari/537.36');
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, "username=XXXXX&password=XXXXX");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_COOKIESESSION, true);
curl_setopt($ch, CURLOPT_COOKIEJAR, 'cookie-name'); //could be empty, but cause problems on some hosts
curl_setopt($ch, CURLOPT_COOKIEFILE, '/var/www/ip4.x/file/tmp'); //could be empty, but cause problems on some hosts
$answer = curl_exec($ch);
if (curl_error($ch)) {
echo curl_error($ch);
}
//another request preserving the session
curl_setopt($ch, CURLOPT_URL, 'http://www.example.com/profile');
curl_setopt($ch, CURLOPT_POST, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, "");
$answer = curl_exec($ch);
if (curl_error($ch)) {
echo curl_error($ch);
}
I've seen this on ImpressPages
There are defaults in the theme that Android uses if you don't specifiy a text color. It may be different colors in various Android UIs (e.g. HTC Sense, Samsung TouchWiz, etc). Android has a _dark
and _light
theme, so the defaults are different for these (but nearly black in both of them in vanilla android). It is however good practice to define your primary text color yourself for to provide a consistent style throughout the devices.
In code:
getResources().getColor(android.R.color.primary_text_dark);
getResources().getColor(android.R.color.primary_text_light);
In xml:
android:color="@android:color/primary_text_dark"
android:color="@android:color/primary_text_light"
As reference in vanilla Android the dark theme text color is #060001
and the in the light theme it's #060003
since API v1. See the android style class here
$(".list-toggle").click(function() {
$(this).hasAttr('colspan') ?
$(this).removeAttr('colspan') : $(this).attr('colspan', 6);
});
The solution is pretty simple.
<table id="TASK_LIST_GRID" class="table table-striped table-bordered table-hover dataTable no-footer" width="100%" role="grid" aria-describedby="TASK_LIST_GRID_info">_x000D_
<thead>_x000D_
<tr role="row">_x000D_
<th class="sorting" tabindex="0" aria-controls="TASK_LIST_GRID" rowspan="1" colspan="1">Solution</th>_x000D_
<th class="sorting" tabindex="0" aria-controls="TASK_LIST_GRID" rowspan="1" colspan="1">Status</th>_x000D_
<th class="sorting" tabindex="0" aria-controls="TASK_LIST_GRID" rowspan="1" colspan="1">Category</th>_x000D_
<th class="sorting" tabindex="0" aria-controls="TASK_LIST_GRID" rowspan="1" colspan="1">Type</th>_x000D_
<th class="sorting" tabindex="0" aria-controls="TASK_LIST_GRID" rowspan="1" colspan="1">Due Date</th>_x000D_
<th class="sorting" tabindex="0" aria-controls="TASK_LIST_GRID" rowspan="1" colspan="1">Create Date</th>_x000D_
<th class="sorting" tabindex="0" aria-controls="TASK_LIST_GRID" rowspan="1" colspan="1">Owner</th>_x000D_
<th class="sorting" tabindex="0" aria-controls="TASK_LIST_GRID" rowspan="1" colspan="1">Comments</th>_x000D_
<th class="sorting" tabindex="0" aria-controls="TASK_LIST_GRID" rowspan="1" colspan="1">Mnemonic</th>_x000D_
<th class="sorting" tabindex="0" aria-controls="TASK_LIST_GRID" rowspan="1" colspan="1">Domain</th>_x000D_
<th class="sorting" tabindex="0" aria-controls="TASK_LIST_GRID" rowspan="1" colspan="1">Approve</th>_x000D_
<th class="sorting" tabindex="0" aria-controls="TASK_LIST_GRID" rowspan="1" colspan="1">Dismiss</th>_x000D_
</tr>_x000D_
</thead>_x000D_
<tbody></tbody>_x000D_
</table>
_x000D_
TASKLISTGRID = $("#TASK_LIST_GRID").DataTable({_x000D_
data : response,_x000D_
columns : columns.AdoptionTaskInfo.columns,_x000D_
paging: true_x000D_
});_x000D_
_x000D_
//Note: columns : columns.AdoptionTaskInfo.columns has at least a column not definded in the <thead>
_x000D_
Note: columns : columns.AdoptionTaskInfo.columns has at least a column not defined in the table head
Use the Stringify.Library nuget package
//Default delimiter is ,
var split = new StringConverter().ConvertTo<List<string>>(names);
//You can also have your custom delimiter for e.g. ;
var split = new StringConverter().ConvertTo<List<string>>(names, new ConverterOptions { Delimiter = ';' });
This is a nice safe example...
function escapeHtml(str) {
if (typeof(str) == "string"){
try{
var newStr = "";
var nextCode = 0;
for (var i = 0;i < str.length;i++){
nextCode = str.charCodeAt(i);
if (nextCode > 0 && nextCode < 128){
newStr += "&#"+nextCode+";";
}
else{
newStr += "?";
}
}
return newStr;
}
catch(err){
}
}
else{
return str;
}
}
Have you tried like:
[HttpGet("Summary")]
public HttpResponseMessage Summary(MyVm vm)
{
return null;
}
[HttpGet("FullDetails")]
public HttpResponseMessage FullDetails()
{
return null;
}
You will need to drop and re-create the primary key like this:
alter table my_table drop constraint my_pk;
alter table my_table add constraint my_pk primary key (city_id, buildtime, time);
However, if there are other tables with foreign keys that reference this primary key, then you will need to drop those first, do the above, and then re-create the foreign keys with the new column list.
An alternative syntax to drop the existing primary key (e.g. if you don't know the constraint name):
alter table my_table drop primary key;
I created an online tool to do this. Simply paste any dependency in pom file format, and the dependency tree for that artifact is generated, based on the central maven repository.
For a start the first select has 6 columns and the second has 4 columns. Perhaps make both have the same number of columns (adding nulls?).
Add in the generated migration after creating the column the following (example)
add_index :photographers, :email, :unique => true
Ok, I couldn't resist replying to this. Let me first say I don't think it's a good idea to simulate this in C as it really is a foreign concept to C.
We can use abuse the preprocessor and local stack variables to give use a limited version of C++ try/throw/catch.
Version 1 (local scope throws)
#include <stdbool.h>
#define try bool __HadError=false;
#define catch(x) ExitJmp:if(__HadError)
#define throw(x) __HadError=true;goto ExitJmp;
Version 1 is a local throw only (can't leave the function's scope). It does rely on C99's ability to declare variables in code (it should work in C89 if the try is first thing in the function).
This function just makes a local var so it knows if there was an error and uses a goto to jump to the catch block.
For example:
#include <stdio.h>
#include <stdbool.h>
#define try bool __HadError=false;
#define catch(x) ExitJmp:if(__HadError)
#define throw(x) __HadError=true;goto ExitJmp;
int main(void)
{
try
{
printf("One\n");
throw();
printf("Two\n");
}
catch(...)
{
printf("Error\n");
}
return 0;
}
This works out to something like:
int main(void)
{
bool HadError=false;
{
printf("One\n");
HadError=true;
goto ExitJmp;
printf("Two\n");
}
ExitJmp:
if(HadError)
{
printf("Error\n");
}
return 0;
}
Version 2 (scope jumping)
#include <stdbool.h>
#include <setjmp.h>
jmp_buf *g__ActiveBuf;
#define try jmp_buf __LocalJmpBuff;jmp_buf *__OldActiveBuf=g__ActiveBuf;bool __WasThrown=false;g__ActiveBuf=&__LocalJmpBuff;if(setjmp(__LocalJmpBuff)){__WasThrown=true;}else
#define catch(x) g__ActiveBuf=__OldActiveBuf;if(__WasThrown)
#define throw(x) longjmp(*g__ActiveBuf,1);
Version 2 is a lot more complex but basically works the same way. It uses a long jump out of the current function to the try block. The try block then uses an if/else to skip the code block to the catch block which check the local variable to see if it should catch.
The example expanded again:
jmp_buf *g_ActiveBuf;
int main(void)
{
jmp_buf LocalJmpBuff;
jmp_buf *OldActiveBuf=g_ActiveBuf;
bool WasThrown=false;
g_ActiveBuf=&LocalJmpBuff;
if(setjmp(LocalJmpBuff))
{
WasThrown=true;
}
else
{
printf("One\n");
longjmp(*g_ActiveBuf,1);
printf("Two\n");
}
g_ActiveBuf=OldActiveBuf;
if(WasThrown)
{
printf("Error\n");
}
return 0;
}
This uses a global pointer so the longjmp() knows what try was last run.
We are using abusing the stack so child functions can also have a try/catch block.
Using this code has a number of down sides (but is a fun mental exercise):
You can use two enums. One for the database and the other for readability.
You just need to make sure they stay in sync, which seems like a small cost. You don't have to set the values, just set the positions the same, but setting the values makes it very clear the two enums are related and prevents errors from rearranging the enum members. And a comment lets the maintenance crew know these are related and must be kept in sync.
// keep in sync with GroupTypes
public enum GroupTypeCodes
{
OEM,
CMB
}
// keep in sync with GroupTypesCodes
public enum GroupTypes
{
TheGroup = GroupTypeCodes.OEM,
TheOtherGroup = GroupTypeCodes.CMB
}
To use it you just convert to the code first:
GroupTypes myGroupType = GroupTypes.TheGroup;
string valueToSaveIntoDatabase = ((GroupTypeCodes)myGroupType).ToString();
Then if you want to make it even more convenient you can add an extension function that only works for this type of enum:
public static string ToString(this GroupTypes source)
{
return ((GroupTypeCodes)source).ToString();
}
and you can then just do:
GroupTypes myGroupType = GroupTypes.TheGroup;
string valueToSaveIntoDatabase = myGroupType.ToString();
The easiest way is to turn the int into a string and take each character of the string as an element of your list:
>>> n = 43365644
>>> digits = [int(x) for x in str(n)]
>>> digits
[4, 3, 3, 6, 5, 6, 4, 4]
>>> lst.extend(digits) # use the extends method if you want to add the list to another
It involves a casting operation, but it's readable and acceptable if you don't need extreme performance.
To reiterate a prior solution and to stress the pure CSS implementation here is my answer.
A Pure CSS solution is needed in cases where you are sourcing content from another site, and thus you have no control over the HTML that is delivered. In my case I am trying to remove branding of licensed source content so that the licencee does not have to advertise for the company they are buying the content from. Therefore, I'm removing their logo while keeping everything else. I should note that this is within my client's contract to do so.
{ /* image size is 204x30 */
width:0;
height:0;
padding-left:102px;
padding-right:102px;
padding-top:15px;
padding-bottom:15px;
background-image:url(http://sthstest/Style%20Library/StThomas/images/rhn_nav_logo2.gif);
}
Open the source tab in 'Developer Tools', click on a line number in a script that is running, this will create a breakpoint and the debugger will break there.
Here is my solution. Worked with script, which was ran by third party program with no WScript declared and no import allowed.
Function MySleep(milliseconds)
set WScriptShell = CreateObject("WScript.Shell")
WScriptShell.Run "Sleep -m " & milliseconds, 0, true
end Function
Update
Looks like Microsoft removed Sleep.exe from win 8, so this doesn't work in win 8 unless you put Sleep.exe in folder defined in %path%.
There's a much simpler way to convert your XmlDocument to a string; use the OuterXml property. The OuterXml property returns a string version of the xml.
public string GetXMLAsString(XmlDocument myxml)
{
return myxml.OuterXml;
}
Use the password_verify() function
if (password_vertify($inputpassword, $row['password'])) {
print "Logged in";
else {
print "Password Incorrect";
}
Try Like this.
For Inserting into DB
$db = mysqli_connect("localhost","root","","DbName"); //keep your db name
$image = addslashes(file_get_contents($_FILES['images']['tmp_name']));
//you keep your column name setting for insertion. I keep image type Blob.
$query = "INSERT INTO products (id,image) VALUES('','$image')";
$qry = mysqli_query($db, $query);
For Accessing image From Blob
$db = mysqli_connect("localhost","root","","DbName"); //keep your db name
$sql = "SELECT * FROM products WHERE id = $id";
$sth = $db->query($sql);
$result=mysqli_fetch_array($sth);
echo '<img src="data:image/jpeg;base64,'.base64_encode( $result['image'] ).'"/>';
Hope It will help you.
Thanks.
Pointers can be used like any other iterators:
int x[3] = {1, 2, 3};
std::vector<int> v(x, x + 3);
test(v)
I have noticed that your success function has the parameter "html", and you are trying to add "data" to your elements html()
... Change it so these both match:
$.ajax({
type:"POST",
url: "ajax.php",
data:"id="+id ,
success: function(data){
$("#response").html(data);
}
});
Use this
<system.web>
<identity impersonate="true"
userName="User Name"
password="Password" />
`enter code here`</system.web>
-tony-
If you get net::ERR_CONTENT_DECODING_FAILED in the console then you are using gzip in your .htaccess file but gzip encoding is Off.
Enable zlib.output_compression=On
in php.ini
and restart Apache
You must cast your integers as string when trying to concatenate them into a varchar.
i.e.
SELECT @ActualWeightDIMS = CAST(@Actual_Dims_Lenght AS varchar(10))
+ 'x' +
CAST(@Actual_Dims_Width as varchar(10))
+ 'x' + CAST(@Actual_Dims_Height as varchar(10));
In SQL Server 2008, you can use the STR
function:
SELECT @ActualWeightDIMS = STR(@Actual_Dims_Lenght)
+ 'x' + STR(@Actual_Dims_Width)
+ 'x' + STR(@Actual_Dims_Height);
This is my understanding of what the relations are between the various "urllibs":
In the Python 2 standard library there exist two HTTP libraries side-by-side. Despite the similar name, they are unrelated: they have a different design and a different implementation.
The Python 3 standard library has a new urllib, that is a merged/refactored/rewritten version of those two packages.
urllib3 is a third-party package. Despite the name, it is unrelated to the standard library packages, and there is no intention to include it in the standard library in the future.
Finally, requests internally uses urllib3, but it aims for an easier-to-use API.
Regarding this part:
When I convert it to UTF-8 without bom and close file, the file is again ANSI when I reopen.
The easiest solution is to avoid the problem entirely by properly configuring Notepad++.
Try Settings
-> Preferences
-> New document
-> Encoding
-> choose UTF-8
without BOM, and check Apply to opened ANSI files
.
That way all the opened ANSI files will be treated as UTF-8 without BOM.
For explanation what's going on, read the comments below this answer.
To fully learn about Unicode and UTF-8, read this excellent article from Joel Spolsky.
Assert.That(myTestDelegate, Throws.ArgumentException
.With.Property("Message").EqualTo("your argument is invalid."));
In python, this concatenates with blank lines between files (the ,
suppresses adding an extra trailing blank line):
print '\n'.join(open(f).read() for f in filenames),
Here is the ugly python one-liner that can be called from the shell and prints the output to a file:
python -c "from sys import argv; print '\n'.join(open(f).read() for f in argv[1:])," File*.txt > finalfile.txt
If you're only checking if it's a number, is_numeric()
is much much better here. It's more readable and a bit quicker than regex.
The issue with your regex here is that it won't allow decimal values, so essentially you've just written is_int()
in regex. Regular expressions should only be used when there is a non-standard data format in your input; PHP has plenty of built in validation functions, even an email validator without regex.
I tried killall -9 node
command in terminal
then again i run my project using npm start
and it's working fine
Just add to a variable encode('utf-8')
agent_contact.encode('utf-8')
use Jackson (https://github.com/FasterXML/jackson) from http://json.org/
HashMap<String,Object> result =
new ObjectMapper().readValue(<JSON_OBJECT>, HashMap.class);
Sorry, I solved my problem with the code above:
$("#captureImage").live("change", function() {
if($("#captureImage:checked").val() !== undefined) {
navigator.device.capture.captureImage(function(mediaFiles) {
console.log("works");
}, function(exception) {
$("#captureImage").removeAttr('checked').checkboxradio('refresh');
_callback.error(exception);
}, {});
}
});
overrides:
- files: *-tests.js
rules:
no-param-reassign: 0
You can also set a specific env for a folder, like this :
overrides:
- files: test/*-tests.js
env:
mocha: true
This configuration will fix error message about describe
and it
not defined, only for your test folder:
/myproject/test/init-tests.js
6:1 error 'describe' is not defined no-undef
9:3 error 'it' is not defined no-undef
Like others have said, there are 2 important pieces of information:
this
pointer when making a static function call and this
pointer points to the structure where the virtual table, or thunk, are used to look up which runtime method to call.A static function is determined at compile time.
I showed this code example in C++ static members in class; it shows that you can call a static method given a null pointer:
struct Foo
{
static int boo() { return 2; }
};
int _tmain(int argc, _TCHAR* argv[])
{
Foo* pFoo = NULL;
int b = pFoo->boo(); // b will now have the value 2
return 0;
}
One possible solution is using nine patch image like this http://developer.android.com/guide/topics/graphics/2d-graphics.html#nine-patch
OR
I have done this in the following way. This is my main layout in which round_corner.xml and drop_shadow.xml used as background resource. round_corner_two is same like round_corner.xml only the color attribute is different. copy the round_corner.xml,drop_shadow.xml and round_conere_two.xml into drawable folder.
<RelativeLayout
android:id="@+id/facebook_id"
android:layout_width="250dp"
android:layout_height="52dp"
android:layout_centerHorizontal="true"
android:layout_marginTop="28dp"
android:background="@drawable/round_corner" >
<LinearLayout
android:id="@+id/shadow_id"
android:layout_width="match_parent"
android:layout_height="48dp"
android:layout_margin="1dp"
android:background="@drawable/drop_shadow" >
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center"
android:layout_marginBottom="2dp"
android:background="@drawable/round_corner_two"
android:gravity="center"
android:text="@string/fb_butn_text"
android:textColor="@color/white" >
</TextView>
</LinearLayout>
</RelativeLayout>
round_corner.xml:
<?xml version="1.0" encoding="utf-8"?>
<shape
xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<!-- view background color -->
<solid
android:color="#ffffff" >
</solid>
<!-- view border color and width -->
<stroke
android:width="0dp"
android:color="#3b5998" >
</stroke>
<!-- If you want to add some padding -->
<padding
android:left="1dp"
android:top="1dp"
android:right="1dp"
android:bottom="1dp" >
</padding>
<!-- Here is the corner radius -->
<corners
android:radius="10dp" >
</corners>
</shape>
drop_shadow.xml
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item >
<shape
android:shape="rectangle">
<solid android:color="@android:color/darker_gray" />
<corners android:radius="12dp"/>
</shape>
</item>
<item android:right="1dp" android:left="1dp" android:bottom="5dp">
<shape
android:shape="rectangle">
<solid android:color="@android:color/white"/>
<corners android:radius="5dp"/>
</shape>
</item>
</layer-list>
You need only to write:
GRANT DBA TO NewDBA;
Because this already makes the user a DB Administrator
Don't know how I got to this question, but even if it's many years since this has been asked, I would like to add a quick and simple method I follow and it has never let me down:
var num = response_from_a_function_or_something();
var fixedNum = parseFloat(num).toFixed( 2 );
As guruz mentioned, the JIT has several lovely graph/tree layouts, including quite appealing RGraph and HyperTree visualizations.
Also, I've just put up a super simple SVG-based implementation at github (no dependencies, ~125 LOC) that should work well enough for small graphs displayed in modern browsers.
Here is one that we have saved off to findcol.sql so we can run it easily from within SQLPlus
set verify off
clear break
accept colnam prompt 'Enter Column Name (or part of): '
set wrap off
select distinct table_name,
column_name,
data_type || ' (' ||
decode(data_type,'LONG',null,'LONG RAW',null,
'BLOB',null,'CLOB',null,'NUMBER',
decode(data_precision,null,to_char(data_length),
data_precision||','||data_scale
), data_length
) || ')' data_type
from all_tab_columns
where column_name like ('%' || upper('&colnam') || '%');
set verify on
you can select a sibling element using jQuery
<script type="text/javascript">
$(document).ready(function(){
$("selector").siblings().addClass("classname");
});
</script>
You can use a data trigger (with a view model) on the button to enable a wait cursor.
<Button x:Name="NextButton"
Content="Go"
Command="{Binding GoCommand }">
<Button.Style>
<Style TargetType="{x:Type Button}">
<Setter Property="Cursor" Value="Arrow"/>
<Style.Triggers>
<DataTrigger Binding="{Binding Path=IsWorking}" Value="True">
<Setter Property="Cursor" Value="Wait"/>
</DataTrigger>
</Style.Triggers>
</Style>
</Button.Style>
</Button>
Here is the code from the view-model:
public class MainViewModel : ViewModelBase
{
// most code removed for this example
public MainViewModel()
{
GoCommand = new DelegateCommand<object>(OnGoCommand, CanGoCommand);
}
// flag used by data binding trigger
private bool _isWorking = false;
public bool IsWorking
{
get { return _isWorking; }
set
{
_isWorking = value;
OnPropertyChanged("IsWorking");
}
}
// button click event gets processed here
public ICommand GoCommand { get; private set; }
private void OnGoCommand(object obj)
{
if ( _selectedCustomer != null )
{
// wait cursor ON
IsWorking = true;
_ds = OrdersManager.LoadToDataSet(_selectedCustomer.ID);
OnPropertyChanged("GridData");
// wait cursor off
IsWorking = false;
}
}
}
Using the C# language constructs, you cannot explicitly call the base function from outside the scope of A
or B
. If you really need to do that, then there is a flaw in your design - i.e. that function shouldn't be virtual to begin with, or part of the base function should be extracted to a separate non-virtual function.
You can from inside B.X however call A.X
class B : A
{
override void X() {
base.X();
Console.WriteLine("y");
}
}
But that's something else.
As Sasha Truf points out in this answer, you can do it through IL. You can probably also accomplish it through reflection, as mhand points out in the comments.
I'm guessing your code failed BEFORE import sys, so it can't find it when you handle the exception.
Also, you should indent the your code whithin the try
block.
try:
import sys
# .. other safe imports
try:
import numpy as np
# other unsafe imports
except ImportError:
print "Error: missing one of the libraries (numpy, pyfits, scipy, matplotlib)"
sys.exit()
In order to delete all images, use the given command
docker rmi $(docker images -q)
In order to delete all containers, use the given command
docker rm $(docker ps -a -q)
Warning: This will destroy all your images and containers. It will not be possible to restore them!
This solution is provided by Techoverflow.net.
make sure your suite.xml should not have .java extension
ex :
<test name="Test C1">
<classes>
<class name="com.taxi.suiteC.TestCase_C1" ></class>
</classes>
</test>
$mail = new PHPMailer(); // create a new object
$mail->IsSMTP(); // enable SMTP
$mail->SMTPDebug = 1; // debugging: 1 = errors and messages, 2 = messages only
$mail->SMTPAuth = true; // authentication enabled
$mail->SMTPSecure = 'ssl'; // secure transfer enabled REQUIRED for Gmail
$mail->Host = "smtp.gmail.com";
$mail->Port = 465; // or 587
$mail->IsHTML(true);
$mail->Username = "[email protected]";
$mail->Password = "password";
$mail->SetFrom("[email protected]");
$mail->Subject = "Test";
$mail->Body = "hello";
$mail->AddAddress("[email protected]");
if(!$mail->Send()) {
echo "Mailer Error: " . $mail->ErrorInfo;
} else {
echo "Message has been sent";
}
This code above has been tested and worked for me.
It could be that you needed $mail->SMTPSecure = 'ssl';
Also make sure you don't have two step verification switched on for that account as that can cause problems also.
UPDATED
You could try changing $mail->SMTP to:
$mail->SMTPSecure = 'tls';
It's worth noting that some SMTP servers block connections.
Some SMTP servers don't support SSL
(or TLS
) connections.
I see that you are looking for an implementation of the problem more than solving that error. Here you have a possible solution:
from itertools import chain
def involved(courses, person):
courses_info = chain.from_iterable(x.values() for x in courses.values())
return filter(lambda x: x['teacher'] == person, courses_info)
print involved(courses, 'Dave')
The first thing I do is getting the list of the courses and then filter by teacher's name.
I just had to figure this out for a client presentation and found a work around to having the GIF play a few times by making a fake loop.
Hope this helps.
Creating a tableview using tableViewController .
import UIKit
class TableViewController: UITableViewController
{
let tableViewModel = TableViewModel()
var product: [String] = []
var price: [String] = []
override func viewDidLoad()
{
super.viewDidLoad()
self.tableView.contentInset = UIEdgeInsetsMake( 20, 20 , 0, 0)
let priceProductDetails = tableViewModel.dataProvider()
for (key, value) in priceProductDetails
{
product.append(key)
price.append(value)
}
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
return product.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
let cell = UITableViewCell(style: .Value1, reuseIdentifier: "UITableViewCell")
cell.textLabel?.text = product[indexPath.row]
cell.detailTextLabel?.text = price[indexPath.row]
return cell
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath)
{
print("You tapped cell number \(indexPath.row).")
}
}
The HTTPS certificate verification security measure isn't something to be discarded light-heartedly. The Man-in-the-middle attack that it prevents safeguards you from a third party e.g. sipping a virus in or tampering with or stealing your data.
Even if you only intend to do that in a test environment, you can easily forget to undo it when moving elsewhere.
Instead, read the relevant section on the provided link and do as it says. The way specific for requests
(which bundles with its own copy of urllib3
), as per CA Certificates — Advanced Usage — Requests 2.8.1 documentation:
requests
ships with its own certificate bundle (but it can only be updated together with the module)requests
v2.4.0
) the certifi
package instead if it's installedcertifi
as per how do I update root certificates of certifi? . E.g. if you replace its bundle with just your test certificate, you will immediately see it if you forget to undo that when moving to production.Finally, with today's government-backed global hacking operations like Tailored Access Operations and the Great Firewall of China that target network infrastructure, falling under a MITM attack is more probable than you think.
You can find those maven properties in the super pom.
You find the jar here:
${M2_HOME}/lib/maven-model-builder-3.0.3.jar
Open the jar with 7-zip or some other archiver (or use the jar tool).
Navigate to
org/apache/maven/model
There you'll find the pom-4.0.0.xml
.
It contains all those "short cuts":
<project>
...
<build>
<directory>${project.basedir}/target</directory>
<outputDirectory>${project.build.directory}/classes</outputDirectory>
<finalName>${project.artifactId}-${project.version}</finalName>
<testOutputDirectory>${project.build.directory}/test-classes</testOutputDirectory>
<sourceDirectory>${project.basedir}/src/main/java</sourceDirectory>
<scriptSourceDirectory>src/main/scripts</scriptSourceDirectory>
<testSourceDirectory>${project.basedir}/src/test/java</testSourceDirectory>
<resources>
<resource>
<directory>${project.basedir}/src/main/resources</directory>
</resource>
</resources>
<testResources>
<testResource>
<directory>${project.basedir}/src/test/resources</directory>
</testResource>
</testResources>
...
</build>
...
</project>
After some lobbying I am adding a link to the pom-4.0.0.xml
. This allows you to see the properties without opening up the local jar file.
Yes. Java doubles will hold their precision better than your given epsilon of 0.00001.
Any rounding error that occurs due to the storage of floating point values will occur smaller than 0.00001. I regularly use 1E-6
or 0.000001 for a double epsilon in Java with no trouble.
On a related note, I like the format of epsilon = 1E-5;
because I feel it is more readable (1E-5 in Java = 1 x 10^-5). 1E-6 is easy to distinguish from 1E-5 when reading code whereas 0.00001 and 0.000001 look so similar when glancing at code I think they are the same value.
If you have a complex form with multiple files and other inputs here is a solution that plays nice with ngModel
.
It consists of a file input component that wraps a simple file input and implements the ControlValueAccessor
interface to make it consumable by ngModel
. The component exposes the FileList
object to ngModel
.
This solution is based on this article.
The component is used like this:
<file-input name="file" inputId="file" [(ngModel)]="user.photo"></file-input>
<label for="file"> Select file </label>
Here's the component code:
import { Component, Input, forwardRef } from '@angular/core';
import { NG_VALUE_ACCESSOR, ControlValueAccessor } from '@angular/forms';
const noop = () => {
};
export const CUSTOM_INPUT_CONTROL_VALUE_ACCESSOR: any = {
provide: NG_VALUE_ACCESSOR,
useExisting: forwardRef(() => FileInputComponent),
multi: true
};
@Component({
selector: 'file-input',
templateUrl: './file-input.component.html',
providers: [CUSTOM_INPUT_CONTROL_VALUE_ACCESSOR]
})
export class FileInputComponent {
@Input()
public name:string;
@Input()
public inputId:string;
private innerValue:any;
constructor() { }
get value(): FileList {
return this.innerValue;
};
private onTouchedCallback: () => void = noop;
private onChangeCallback: (_: FileList) => void = noop;
set value(v: FileList) {
if (v !== this.innerValue) {
this.innerValue = v;
this.onChangeCallback(v);
}
}
onBlur() {
this.onTouchedCallback();
}
writeValue(value: FileList) {
if (value !== this.innerValue) {
this.innerValue = value;
}
}
registerOnChange(fn: any) {
this.onChangeCallback = fn;
}
registerOnTouched(fn: any) {
this.onTouchedCallback = fn;
}
changeFile(event) {
this.value = event.target.files;
}
}
And here's the component template:
<input type="file" name="{{ name }}" id="{{ inputId }}" multiple="multiple" (change)="changeFile($event)"/>
From the official Swift programming guide:
Global variables are variables that are defined outside of any function, method, closure, or type context. Global constants and variables are always computed lazily.
You can define it in any file and can access it in current module
anywhere.
So you can define it somewhere in the file outside of any scope. There is no need for static
and all global variables are computed lazily.
var yourVariable = "someString"
You can access this from anywhere in the current module.
However you should avoid this as Global variables are not good for application state and mainly reason of bugs.
As shown in this answer, in Swift you can encapsulate them in struct
and can access anywhere.
You can define static variables or constant in Swift also. Encapsulate in struct
struct MyVariables {
static var yourVariable = "someString"
}
You can use this variable in any class or anywhere
let string = MyVariables.yourVariable
println("Global variable:\(string)")
//Changing value of it
MyVariables.yourVariable = "anotherString"
I don't think phpMyAdmin lets you do that, but I'd like to hear I'm wrong.
On the other hand you can enable query logging in MySQL: The General Query Log
... more range, using a generator function.
function range(s, e, str){
// create generator that handles numbers & strings.
function *gen(s, e, str){
while(s <= e){
yield (!str) ? s : str[s]
s++
}
}
if (typeof s === 'string' && !str)
str = 'abcdefghijklmnopqrstuvwxyz'
const from = (!str) ? s : str.indexOf(s)
const to = (!str) ? e : str.indexOf(e)
// use the generator and return.
return [...gen(from, to, str)]
}
// usage ...
console.log(range('l', 'w'))
//=> [ 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w' ]
console.log(range(7, 12))
//=> [ 7, 8, 9, 10, 11, 12 ]
// first 'o' to first 't' of passed in string.
console.log(range('o', 't', "ssshhhooooouuut!!!!"))
// => [ 'o', 'o', 'o', 'o', 'o', 'u', 'u', 'u', 't' ]
// only lowercase args allowed here, but ...
console.log(range('m', 'v').map(v=>v.toUpperCase()))
//=> [ 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V' ]
// => and decreasing range ...
console.log(range('m', 'v').map(v=>v.toUpperCase()).reverse())
// => ... and with a step
console.log(range('m', 'v')
.map(v=>v.toUpperCase())
.reverse()
.reduce((acc, c, i) => (i % 2) ? acc.concat(c) : acc, []))
// ... etc, etc.
Hope this is useful.
Delete
operation available on Arrays. We can symbolically delete an element by setting it to some specific value, e.g. -1, 0, etc. depending on our requirementsInsert
for arrays is basically Set
as mentioned in the beginningMake sure nodejs in the PATH is in front of anything that uses node.
It is a class that extends another class.
example taken from https://www.java-tips.org/java-se-tips-100019/24-java-lang/784-what-is-a-java-subclass.html, Cat is a sub class of Animal :-)
public class Animal {
public static void hide() {
System.out.println("The hide method in Animal.");
}
public void override() {
System.out.println("The override method in Animal.");
}
}
public class Cat extends Animal {
public static void hide() {
System.out.println("The hide method in Cat.");
}
public void override() {
System.out.println("The override method in Cat.");
}
public static void main(String[] args) {
Cat myCat = new Cat();
Animal myAnimal = (Animal)myCat;
myAnimal.hide();
myAnimal.override();
}
}
If your environment is JavaScript, use markdown-it along with the plugin markdown-it-attrs:
const md = require('markdown-it')();
const attrs = require('markdown-it-attrs');
md.use(attrs);
const src = 'paragraph {.className #id and=attributes}';
// render
let res = md.render(src);
console.log(res);
Output
<p class="className" id="id" and="attributes">paragraph</p>
Note: Be aware of the security aspect when allowing attributes in your markdown!
Disclaimer, I'm the author of markdown-it-attrs.
There is an object serialization module, with the serialize function you can serialize any object.
Add following code in info.plist file
<key>NSPhotoLibraryUsageDescription</key>
<string>My description about why I need this capability</string>
Padding is a way to add kind of a margin inside the Div.
Just Use
div { padding-left: 20px; }
And to mantain the size, you would have to -20px from the original width of the Div.
See http://ruby-doc.org/core/classes/Range.html#M000695 for the full API.
Basically you use the step()
method. For example:
(10..100).step(10) do |n|
# n = 10
# n = 20
# n = 30
# ...
end
Joining fails if the DataFrames have some column names in common. The simplest way around it is to include an lsuffix
or rsuffix
keyword like so:
restaurant_review_frame.join(restaurant_ids_dataframe, on='business_id', how='left', lsuffix="_review")
This way, the columns have distinct names. The documentation addresses this very problem.
Or, you could get around this by simply deleting the offending columns before you join. If, for example, the stars in restaurant_ids_dataframe
are redundant to the stars in restaurant_review_frame
, you could del restaurant_ids_dataframe['stars']
.
For radioButton use
radio1.setChecked(true);
It does not make sense to have just one RadioButton. If you have more of them you need to uncheck others through
radio2.setChecked(false); ...
If your setting is just on/off use CheckBox.
If you parse the JSON with eval
, you're allowing the string being parsed to contain absolutely anything, so instead of just being a set of data, you could find yourself executing function calls, or whatever.
Also, JSON's parse
accepts an aditional parameter, reviver, that lets you specify how to deal with certain values, such as datetimes (more info and example in the inline documentation here)
As you already mentioned, this is straightforward to do in Python 2.6 or newer:
enumerate(range(2000, 2005), 1)
Python 2.5 and older do not support the start
parameter so instead you could create two range objects and zip them:
r = xrange(2000, 2005)
r2 = xrange(1, len(r) + 1)
h = zip(r2, r)
print h
Result:
[(1, 2000), (2, 2001), (3, 2002), (4, 2003), (5, 2004)]
If you want to create a generator instead of a list then you can use izip instead.
if you did a git add and you haven't pushed anything yet, you just have to do this to unstage it from your commit.
git reset HEAD <file>
Floating it will reorganise the flow but position: absolute is the only way to completely remove it from the flow of the document.
As stated before none of the perm fixes work anymore. You need to change the perms accordingly AND put the following in your wp-config.php
:
define('FS_METHOD', 'direct');
Making your queryable lists to .ToList() and it should work fine.
ephemeral is just another name of root volume when you launch Instance from AMI backed from Amazon EC2 instance store
So Everything will be stored on ephemeral.
if you have launched your instance from AMI backed by EBS volume then your instance does not have ephemeral.
=IF(X2>=85,0.559,IF(X2>=80,0.327,IF(X2>=75,0.255,-1)))
Explanation:
=IF(X2>=85, 'If the value is in the highest bracket
0.559, 'Use the appropriate number
IF(X2>=80, 'Otherwise, if the number is in the next highest bracket
0.327, 'Use the appropriate number
IF(X2>=75, 'Otherwise, if the number is in the next highest bracket
0.255, 'Use the appropriate number
-1 'Otherwise, we're not in any of the ranges (Error)
)
)
)
I'd suggest reading through the Firebase documentation. Specifically, see the Saving Data portion of the Firebase JavaScript Web Guide.
From the guide:
Getting the Unique ID Generated by push()
Calling
push()
will return a reference to the new data path, which you can use to get the value of its ID or set data to it. The following code will result in the same data as the above example, but now we'll have access to the unique push ID that was generated
// Generate a reference to a new location and add some data using push() var newPostRef = postsRef.push({ author: "gracehop", title: "Announcing COBOL, a New Programming Language" }); // Get the unique ID generated by push() by accessing its key var postID = newPostRef.key;
Source: https://firebase.google.com/docs/database/admin/save-data#section-ways-to-save
key
. These keys look like -JiGh_31GA20JabpZBfa
, so not numeric.From the guide:
In JavaScript, the pattern of calling
push()
and then immediately callingset()
is so common that we let you combine them by just passing the data to be set directly topush()
as follows. Both of the following write operations will result in the same data being saved to Firebase:
// These two methods are equivalent: postsRef.push().set({ author: "gracehop", title: "Announcing COBOL, a New Programming Language" }); postsRef.push({ author: "gracehop", title: "Announcing COBOL, a New Programming Language" });
Source: https://firebase.google.com/docs/database/admin/save-data#getting-the-unique-key-generated-by-push
Why not just have five separate images of a star (empty, quarter-full, half-full, three-quarter-full and full) then just inject the images into your DOM depending on the truncated or rouded value of rating multiplied by 4 (to get a whole numner for the quarters)?
For example, 4.8618164 multiplied by 4 and rounded is 19 which would be four and three quarter stars.
Alternatively (if you're lazy like me), just have one image selected from 21 (0 stars through 5 stars in one-quarter increments) and select the single image based on the aforementioned value. Then it's just one calculation followed by an image change in the DOM (rather than trying to change five different images).
Used to this
input[type="radio"]{
vertical-align:top;
}
p{
font-size:10px;line-height: 18px;
}
Have you tried QCoreApplication::applicationDirPath()
qDebug() << "App path : " << qApp->applicationDirPath();
After experiencing issues with sites breaking on Edge when using High Contrast Mode, I came across the following work by Jeff Clayton:
https://browserstrangeness.github.io/css_hacks.html
It's a crazy, weird media query, but those are easier to use in Sass:
@media screen and (min-width:0\0) and (min-resolution:+72dpi), \0screen\,screen\9 {
.selector { rule: value };
}
This targets IE versions expect for IE8.
Or you can use:
@media screen\0 {
.selector { rule: value };
}
Which targets IE8-11, but also triggers FireFox 1.x (which for my use case, doesn't matter).
Right now I'm testing with print support, and this seems to be working okay:
@media all\0 {
.selector { rule: value };
}
One way you can do it, is to get the slaves list from the frame that needs to be cleared and destroy or "hide" them according to your needs. To get a clear frame you can do it like this:
from tkinter import *
root = Tk()
def clear():
list = root.grid_slaves()
for l in list:
l.destroy()
Label(root,text='Hello World!').grid(row=0)
Button(root,text='Clear',command=clear).grid(row=1)
root.mainloop()
You should call grid_slaves()
, pack_slaves()
or slaves()
depending on the method you used to add the widget to the frame.
If you are using Asp.Net MVC, then take a look at:
public static RouteValueDictionary AnonymousObjectToHtmlAttributes(object htmlAttributes);
which is a static public method on the System.Web.Mvc.HtmlHelper class.
You can use a TreeMap data structure
. TreeMap
is implemented as a red black tree, which is a self-balancing binary search tree.
You can use lambda
functions in findAll
as explained in documentation. So that in your case to search for td
tag with only valign = "top"
use following:
td_tag_list = soup.findAll(
lambda tag:tag.name == "td" and
len(tag.attrs) == 1 and
tag["valign"] == "top")
I know this is an old question but I thought I would provide an example using the srcdoc
attribute as this is now widely supported and this is question is viewed often.
Using the srcdoc
attribute, you can provide inline HTML to embed. It overrides the src
attribute if supported. The browser will fall back to the src
attribute if unsupported.
I would also recommend using the sandbox
attribute to apply extra restrictions to the content in the frame. This is especially important if the HTML is not your own.
const iframe = document.createElement('iframe');_x000D_
const html = '<body>Foo</body>';_x000D_
iframe.srcdoc = html;_x000D_
iframe.sandbox = '';_x000D_
document.body.appendChild(iframe);
_x000D_
If you need to support older browsers, you can check for srcdoc
support and fallback to one of the other methods from other answers.
function setIframeHTML(iframe, html) {_x000D_
if (typeof iframe.srcdoc !== 'undefined') {_x000D_
iframe.srcdoc = html;_x000D_
} else {_x000D_
iframe.sandbox = 'allow-same-origin';_x000D_
iframe.contentWindow.document.open();_x000D_
iframe.contentWindow.document.write(html);_x000D_
iframe.contentWindow.document.close();_x000D_
}_x000D_
}_x000D_
_x000D_
var iframe = document.createElement('iframe');_x000D_
iframe.sandbox = '';_x000D_
var html = '<body>Foo</body>';_x000D_
_x000D_
document.body.appendChild(iframe);_x000D_
setIframeHTML(iframe, html);
_x000D_
public static object GetPropValue(object src, string propName)
{
return src.GetType().GetProperty(propName).GetValue(src, null);
}
Of course, you will want to add validation and whatnot, but that is the gist of it.
def my_func(mandatory_arg, optional_arg=100):
print(mandatory_arg, optional_arg)
http://docs.python.org/2/tutorial/controlflow.html#default-argument-values
I find this more readable than using **kwargs
.
To determine if an argument was passed at all, I use a custom utility object as the default value:
MISSING = object()
def func(arg=MISSING):
if arg is MISSING:
...
You can use stristr()
or strpos()
. Both return false if nothing is found.
This should do the trick:
$($.parseJSON(data.msg)).map(function () {
return $('<option>').val(this.value).text(this.label);
}).appendTo('#combobox');
Here's the distinction between ajax
and getJSON
(from the jQuery documentation):
[getJSON] is a shorthand Ajax function, which is equivalent to:
$.ajax({ url: url, dataType: 'json', data: data, success: callback });
EDIT: To be clear, part of the problem was that the server's response was returning a json object that looked like this:
{
"msg": '[{"value":"1","label":"xyz"}, {"value":"2","label":"abc"}]'
}
...So that msg
property needed to be parsed manually using $.parseJSON()
.
Pseudo code, something like:
CASE
When CHARINDEX('lactulose', dbo.Table.Column) > 0 Then 'BP Medication'
ELSE ''
END AS 'Medication Type'
This does not care where the keyword is found in the list and avoids depending on formatting of spaces and commas.
SELECT contendernum,totals, RANK() OVER (ORDER BY totals ASC) AS xRank FROM
(
SELECT ContenderNum ,SUM(Criteria1+Criteria2+Criteria3+Criteria4) AS totals
FROM dbo.Cat1GroupImpersonation
GROUP BY ContenderNum
) AS a
You can't.
As a workaround you can use a // @ts-nocheck
comment at the top of a file to disable type-checking for that file: https://devblogs.microsoft.com/typescript/announcing-typescript-3-7-beta/
So to disable checking for a block (function, class, etc.), you can move it into its own file, then use the comment/flag above. (This isn't as flexible as block-based disabling of course, but it's the best option available at the moment.)
you can set it in .bashrc
PATH=$PATH:/opt/ActiveTcl-8.5/bin;export PATH;
If you're talking about XML-files (ISO-8859-1), the XML-declaration inside them specifies the encoding: <?xml version="1.0" encoding="ISO-8859-1" ?>
So, you can use regular expressions (e.g. with perl
) to check every file for such specification.
More information can be found here: How to Determine Text File Encoding.
I faced a similar issue. The solution that worked for me 1) uninstall python 2.7 2) delete python27 folder 3) reinstall the latest python
You can also use python's collections.Chainmap which was introduced in python 3.3.
from collections import Chainmap
c = Chainmap(a, b)
c['a'] # returns 1
This has a few possible advantages, depending on your use-case. They are explained in more detail here, but I'll give a brief overview:
This mainly makes it useful for things like configuration dictionaries.
Step 1: Go to
http://localhost/security/xamppsecurity.php
Step 2: Set/Modify your password.
Step 3: Open C:\xampp\phpMyAdmin\config.inc.php using a editor.
Step 4: Check the following lines:
$cfg['Servers'][$i]['user'] = 'root';
$cfg['Servers'][$i]['password'] = 'your_password';
// your_password = the password that you have set in Step 2.
Step 5: Make sure the following line is set to TRUE: $cfg['Servers'][$i]['AllowNoPassword'] = true;
Step 6: Save the file, Restart MySQL from XAMPP Control Panel
Step 7: Login into phpmyadmin with root & your password.
Note: If again the same error comes, check the security page:
http://localhost/security/index.php
It will say:
The MySQL admin user root has no longer no password SECURE
PhpMyAdmin password login is enabled. SECURE
Then Restart your system, the problem will be solved.
If using IIS:
If using IIS Express:
Open 'Add/Remove Programs' from the old control panel and run a repair on IIS Express Or you might go Control Panel ->> Programs ->> Programs and Features ->> Turn Windows features on or off ->> Internet Information Services and check the checkbox as shown in the picture below:
Surprised no one mentioned Illustrator's Save As > Format dropdown > .svg option.
Outputs an .svg file that contains the path (and the rest of the svg definition) within an .svg (xml) file.
The path itself is within <path d>
.
OPTIONS request are by no means an AngularJS bug, this is how Cross-Origin Resource Sharing standard mandates browsers to behave. Please refer to this document: https://developer.mozilla.org/en-US/docs/HTTP_access_control, where in the "Overview" section it says:
The Cross-Origin Resource Sharing standard works by adding new HTTP headers that allow servers to describe the set of origins that are permitted to read that information using a web browser. Additionally, for HTTP request methods that can cause side-effects on user data (in particular; for HTTP methods other than GET, or for POST usage with certain MIME types). The specification mandates that browsers "preflight" the request, soliciting supported methods from the server with an HTTP OPTIONS request header, and then, upon "approval" from the server, sending the actual request with the actual HTTP request method. Servers can also notify clients whether "credentials" (including Cookies and HTTP Authentication data) should be sent with requests.
It is very hard to provide a generic solution that would work for all the WWW servers as setup will vary depending on the server itself and HTTP verbs that you intend to support. I would encourage you to get over this excellent article (http://www.html5rocks.com/en/tutorials/cors/) that has much more details on the exact headers that needs to be sent by a server.
You're returning the address of a local variable allocated on the stack. When your function returns, the storage for all local variables (such as wc
) is deallocated and is subject to being immediately overwritten by something else.
To fix this, you can pass the size of the buffer to GetWC
, but then you've got pretty much the same interface as mbstowcs
itself. Or, you could allocate a new buffer inside GetWC
and return a pointer to that, leaving it up to the caller to deallocate the buffer.