What is the underlying logic you want to implement? If, for instance, you want to test for the existence of a record to determine to insert or update then a better choice would be to use MERGE instead.
If you expect the record to exist most of the time, this is probably the most efficient way of doing things (although the CASE WHEN EXISTS solution is likely to be just as efficient):
begin
select null into dummy
from sales
where sales_type = 'Accessories'
and rownum = 1;
-- do things here when record exists
....
exception
when no_data_found then
-- do things here when record doesn't exists
.....
end;
You only need the ROWNUM line if SALES_TYPE is not unique. There's no point in doing a count when all you want to know is whether at least one record exists.
This might be useful for someone else: Using this sample html
<div class="ParentDiv">
<label for="label">labelName</label>
<input type="button" value="elementToSelect">
</div>
<div class="DontSelect">
<label for="animal">pig</label>
<input type="button" value="elementToSelect">
</div>
If for example, I want to select an element in the same section (e.g div) as a label, you can use this
//label[contains(., 'labelName')]/parent::*//input[@value='elementToSelect']
This just means, look for a label (it could anything like a
, h2
) called labelName
. Navigate to the parent of that label (i.e. div class="ParentDiv"
). Search within the descendants of that parent to find any child element with the value of elementToSelect
. With this, it will not select the second elementToSelect
with DontSelect
div as parent.
The trick is that you can reduce search areas for an element by navigating to the parent first and then searching descendant of that parent for the element you need.
Other Syntax like following-sibling::h2
can also be used in some cases. This means the sibling following element h2
. This will work for elements at the same level, having the same parent.
Random.new.rand(a..b)
Where a
is your lowest value and b
is your highest value.
It might be the JavaScript check for some valid condition.
Two things you can perform a/c to your requirements:
String barcode="0000000047166";
WebElement strLocator = driver.findElement(By.xpath("//*[@id='div-barcode']"));
strLocator.sendKeys(barcode);
When you put <form>
tag inside you ngApp, AngularJS automatically adds form controller (actually there is a directive, called form
that add nessesary behaviour). The value of the name attribute will be bound in your scope; so something like <form name="yourformname">...</form>
will satisfy:
A form is an instance of FormController. The form instance can optionally be published into the scope using the name attribute.
So to check form validity, you can check value of $scope.yourformname.$valid
property of scope.
More information you can get at Developer's Guide section about forms.
Change color values in the array
val gradientDrawable = GradientDrawable(
GradientDrawable.Orientation.TOP_BOTTOM,
intArrayOf(Color.parseColor("#008000"),
Color.parseColor("#ADFF2F"))
);
gradientDrawable.cornerRadius = 0f;
//Set Gradient
linearLayout.setBackground(gradientDrawable);
Result
You need some JS to achieve this by simply adding alert('Your message')
within your PHP code.
See example below
<?php
//my other php code here
function function_alert() {
// Display the alert box; note the Js tags within echo, it performs the magic
echo "<script>alert('Your message Here');</script>";
}
?>
when you visit your browser using the route supposed to triger your function_alert
, you will see the alert box with your message displayed on your screen.
Read more at https://www.geeksforgeeks.org/how-to-pop-an-alert-message-box-using-php/
As this is one of the first hits in the search engines, and none of the above seems to work for MongoDB 3.x, here is one regex search that does work:
db.users.find( { 'name' : { '$regex' : yourvalue, '$options' : 'i' } } )
No need to create and extra index or alike.
Everyone else's method doesn't account for whitespaces. Obviously nobody really considers a whitespace a special character.
Use this method to detect special characters not including whitespaces:
import re
def detect_special_characer(pass_string):
regex= re.compile('[@_!#$%^&*()<>?/\|}{~:]')
if(regex.search(pass_string) == None):
res = False
else:
res = True
return(res)
You can do the check at first and then use the switch as you like.
For example:
string str = "parameter"; // test1..test2..test3....
if (!message.Contains(str)) return ;
Then
switch(str)
{
case "test1" : {} break;
case "test2" : {} break;
default : {} break;
}
The above solution is good in some scenarios but there is another scenario where this happens when you are unit testing and you try to "Debug Selected Tests" from the Test Explorer when you solution is not set to Debug.
In this case you need to change your solution from Release or whatever it is set to to Debug in this case. If this is the problem then changing "ContextSwitchDeadlock" won't really help you.
I missed this myself because the error message was so nasty I didn't check the obvious thing which was the Debug setting!
HTTP HEAD requests must be treated slightly differently because response.getEntity() is null. Instead, you must capture the HttpContext passed into HttpClient.execute() and retrieve the connection parameter to close it (in HttpComponents 4.1.X anyway).
HttpRequest httpRqst = new HttpHead( uri );
HttpContext httpContext = httpFactory.createContext();
HttpResponse httpResp = httpClient.execute( httpRqst, httpContext );
...
// Close when finished
HttpEntity entity = httpResp.getEntity();
if( null != entity )
// Handles standard 'GET' case
EntityUtils.consume( entity );
else {
ConnectionReleaseTrigger conn =
(ConnectionReleaseTrigger) httpContext.getAttribute( ExecutionContext.HTTP_CONNECTION );
// Handles 'HEAD' where entity is not returned
if( null != conn )
conn.releaseConnection();
}
HttpComponents 4.2.X added a releaseConnection() to HttpRequestBase to make this easier.
Second Largest in O(n/2)
public class SecMaxNum {
// second Largest number with O(n/2)
/**
* @author Rohan Kamat
* @Date Feb 04, 2016
*/
public static void main(String[] args) {
int[] input = { 1, 5, 10, 11, 11, 4, 2, 8, 1, 8, 9, 8 };
int large = 0, second = 0;
for (int i = 0; i < input.length - 1; i = i + 2) {
// System.out.println(i);
int fist = input[i];
int sec = input[i + 1];
if (sec >= fist) {
int temp = fist;
fist = sec;
sec = temp;
}
if (fist >= second) {
if (fist >= large) {
large = fist;
} else {
second = fist;
}
}
if (sec >= second) {
if (sec >= large) {
large = sec;
} else {
second = sec;
}
}
}
}
}
Okay this code does exactly what you need:
HTML:
<div class="class1">nothing happens hear.</div>
<div class="class1 class2">This element will receive yout code.</div>
<div class="class1">nothing happens hear.</div>
JS:
function getElementMultipleClasses() {
var x = document.getElementsByClassName("class1 class2");
x[0].innerHTML = "This is the element you want";
}
getElementMultipleClasses();
Hope it helps! ;)
Try:
which( !is.na(p), arr.ind=TRUE)
Which I think is just as informative and probably more useful than the output you specified, But if you really wanted the list version, then this could be used:
> apply(p, 1, function(x) which(!is.na(x)) )
[[1]]
[1] 2 3
[[2]]
[1] 4 7
[[3]]
integer(0)
[[4]]
[1] 5
[[5]]
integer(0)
Or even with smushing together with paste:
lapply(apply(p, 1, function(x) which(!is.na(x)) ) , paste, collapse=", ")
The output from which
function the suggested method delivers the row and column of non-zero (TRUE) locations of logical tests:
> which( !is.na(p), arr.ind=TRUE)
row col
[1,] 1 2
[2,] 1 3
[3,] 2 4
[4,] 4 5
[5,] 2 7
Without the arr.ind
parameter set to non-default TRUE, you only get the "vector location" determined using the column major ordering the R has as its convention. R-matrices are just "folded vectors".
> which( !is.na(p) )
[1] 6 11 17 24 32
I like this way:
set list=a;^
b;^
c;^
d;
for %%a in (%list%) do (
echo %%a
echo/
)
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_with_the_button);
final Animation myAnim = AnimationUtils.loadAnimation(this, R.anim.milkshake);
Button myButton = (Button) findViewById(R.id.new_game_btn);
myButton.setAnimation(myAnim);
}
For onClick of the Button
myButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
v.startAnimation(myAnim);
}
});
Create the anim folder in res directory
Right click on, res -> New -> Directory
Name the new Directory anim
create a new xml file name it milkshake
milkshake.xml
<?xml version="1.0" encoding="utf-8"?>
<rotate xmlns:android="http://schemas.android.com/apk/res/android"
android:duration="100"
android:fromDegrees="-5"
android:pivotX="50%"
android:pivotY="50%"
android:repeatCount="10"
android:repeatMode="reverse"
android:toDegrees="5" />
I used the Dahnark's code but I also need to change the ToolBar background:
if (dark_ui) {
this.setTheme(R.style.Theme_Dark);
if (Build.VERSION.SDK_INT >= 21) {
getWindow().setNavigationBarColor(getResources().getColor(R.color.Theme_Dark_primary));
getWindow().setStatusBarColor(getResources().getColor(R.color.Theme_Dark_primary_dark));
}
} else {
this.setTheme(R.style.Theme_Light);
}
setContentView(R.layout.activity_main);
toolbar = (Toolbar) findViewById(R.id.app_bar);
if(dark_ui) {
toolbar.setBackgroundColor(getResources().getColor(R.color.Theme_Dark_primary));
}
Yes. Empty or incomplete headers or response body typically caused by broken connections or server side crash can cause 502 errors if accessed via a gateway or proxy.
For more information about the network errors
This error can also happen if the variable you are comparing has hidden characters that are not numbers/digits.
For example, if you are retrieving an integer from a third-party script, you must ensure that the returned string does not contain hidden characters, like "\n"
or "\r"
.
For example:
#!/bin/bash
# Simulate an invalid number string returned
# from a script, which is "1234\n"
a='1234
'
if [ "$a" -gt 1233 ] ; then
echo "number is bigger"
else
echo "number is smaller"
fi
This will result in a script error : integer expression expected
because $a
contains a non-digit newline character "\n"
. You have to remove this character using the instructions here: How to remove carriage return from a string in Bash
So use something like this:
#!/bin/bash
# Simulate an invalid number string returned
# from a script, which is "1234\n"
a='1234
'
# Remove all new line, carriage return, tab characters
# from the string, to allow integer comparison
a="${a//[$'\t\r\n ']}"
if [ "$a" -gt 1233 ] ; then
echo "number is bigger"
else
echo "number is smaller"
fi
You can also use set -xv
to debug your bash script and reveal these hidden characters. See https://www.linuxquestions.org/questions/linux-newbie-8/bash-script-error-integer-expression-expected-934465/
You can try the following snippet using jQuery:
$(table).find('tbody').append("<tr><td>aaaa</td></tr>");
For the Platform Independent Users or Windows users, what you can do is:
import runtime:
import (
"runtime"
"strings"
)
and then trim the string like this:
if runtime.GOOS == "windows" {
input = strings.TrimRight(input, "\r\n")
} else {
input = strings.TrimRight(input, "\n")
}
now you can compare it like that:
if strings.Compare(input, "a") == 0 {
//....yourCode
}
This is a better approach when you're making use of STDIN on multiple platforms.
This happens because on windows lines end with "\r\n"
which is known as CRLF, but on UNIX lines end with "\n"
which is known as LF and that's why we trim "\n"
on unix based operating systems while we trim "\r\n"
on windows.
I also had same issue .I build it trough this way.I used struts 2 framework.
<script type="text/javascript">
$(document).ready(function () {
var year = (new Date).getFullYear();
$( "#effectiveDateId" ).datepicker({dateFormat: "mm/dd/yy", maxDate:
0});
});
</script>
<s:textfield name="effectiveDate" cssClass="input-large"
key="label.warrantRateMappingToPropertyTypeForm.effectiveDate"
id="effectiveDateId" required="true"/>
This worked for me.
Set max_allowed_packet to the same (or more) than what it was when you dumped it with mysqldump. If you can't do that, make the dump again with a smaller value.
That is, assuming you dumped it with mysqldump. If you used some other tool, you're on your own.
This is round robin DNS. This is a quite simple solution for load balancing. Usually DNS servers rotate/shuffle the DNS records for each incoming DNS request. Unfortunately it's not a real solution for fail-over. If one of the servers fail, some visitors will still be directed to this failed server.
Edit: as of Bootstrap 3.1 .col-xs-offset-*
does exist, see bootstrap :: grid options
.col-xs-offset-*
doesn't exist.
Offset and column ordering are only for small and more. (ONLY .col-sm-offset-*
, .col-md-offset-*
and .col-lg-offset-*
)
See the official documentation : bootstrap :: grid options
The reason you might not be getting any results is because you might not be having the J2EE environment setup in your Eclipse IDE. Follow these steps to solve the problem.
Hope this helps.
Here is what you want to put in the project's Post-build event command line:
copy /Y "$(TargetDir)$(ProjectName).dll" "$(SolutionDir)lib\$(ProjectName).dll"
EDIT: Or if your target name is different than the Project Name.
copy /Y "$(TargetDir)$(TargetName).dll" "$(SolutionDir)lib\$(TargetName).dll"
Try swapspace http://pqxx.org/development/swapspace/
Most distros have it packaged.
On EC2 you might want to change "swappath" to /mnt or high-iops disk.
An unsigned application cannot be installed. When we run directly from eclipse, that apk is signed with debugger key and can be found in bin\ folder of the project. You can use that for test purpose distribution also.
Using only strlen from string.h
sorry for my English
char * str_replace(char * text,char * rep, char * repw){//text -> to replace in it | rep -> replace | repw -> replace with
int replen = strlen(rep),repwlen = strlen(repw),count;//some constant variables
for(int i=0;i<strlen(text);i++){//search for the first character from rep in text
if(text[i] == rep[0]){//if it found it
count = 1;//start searching from the next character to avoid repetition
for(int j=1;j<replen;j++){
if(text[i+j] == rep[j]){//see if the next character in text is the same as the next in the rep if not break
count++;
}else{
break;
}
}
if(count == replen){//if count equals to the lenght of the rep then we found the word that we want to replace in the text
if(replen < repwlen){
for(int l = strlen(text);l>i;l--){//cuz repwlen greater than replen we need to shift characters to the right to make space for the replacement to fit
text[l+repwlen-replen] = text[l];//shift by repwlen-replen
}
}
if(replen > repwlen){
for(int l=i+replen-repwlen;l<strlen(text);l++){//cuz replen greater than repwlen we need to shift the characters to the left
text[l-(replen-repwlen)] = text[l];//shift by replen-repwlen
}
text[strlen(text)-(replen-repwlen)] = '\0';//get rid of the last unwanted characters
}
for(int l=0;l<repwlen;l++){//replace rep with repwlen
text[i+l] = repw[l];
}
if(replen != repwlen){
i+=repwlen-1;//pass to the next character | try text "y" ,rep "y",repw "yy" without this line to understand
}
}
}
}
return text;
}
if you want strlen code to avoid calling string.h
int strlen(char * string){//use this code to avoid calling string.h
int lenght = 0;
while(string[lenght] != '\0'){
lenght++;
}
return lenght;
}
Have you tried http://www.dpriver.com/pp/sqlformat.htm?
This is what I use, and it works for me:
//variables
String subject = "Whatever subject you want";
String body = "Whatever text you want to put in the body";
String intentType = "text/html";
String mailToParse = "mailto:";
//start Intent
Intent variableName = new Intent(Intent.ACTION_SENDTO);
variableName.setType(intentType);
variableName.setData(Uri.parse(mailToParse));
variableName.putExtra(Intent.EXTRA_SUBJECT, subject);
variableName.putExtra(Intent.EXTRA_TEXT, body);
startActivity(variableName);
This will also let the user choose their preferred email app. The only thing this does not allow you to do is to set the recipient's email address.
DATE: It is used for values with a date part but no time part. MySQL retrieves and displays DATE values in YYYY-MM-DD format. The supported range is 1000-01-01
to 9999-12-31
.
DATETIME: It is used for values that contain both date and time parts. MySQL retrieves and displays DATETIME values in YYYY-MM-DD HH:MM:SS format. The supported range is 1000-01-01 00:00:00
to 9999-12-31 23:59:59
.
TIMESTAMP: It is also used for values that contain both date and time parts, and includes the time zone. TIMESTAMP has a range of 1970-01-01 00:00:01
UTC to 2038-01-19 03:14:07
UTC.
TIME: Its values are in HH:MM:SS format (or HHH:MM:SS format for large hours values). TIME values may range from -838:59:59
to 838:59:59
. The hours part may be so large because the TIME type can be used not only to represent a time of day (which must be less than 24 hours), but also elapsed time or a time interval between two events (which may be much greater than 24 hours, or even negative).
Hmm... well, the simple way that comes to mind is to convert it to a dict
d = dict(thelist)
and access d[53]
.
EDIT: Oops, misread your question the first time. It sounds like you actually want to get the index where a given number is stored. In that case, try
dict((t[0], i) for i, t in enumerate(thelist))
instead of a plain old dict
conversion. Then d[53]
would be 2.
sudo nano /etc/apache2/httpd.conf
ServerName
in nano editor <Ctrl + W>
ServerName localhost
sudo /usr/sbin/apachectl restart
sudo diskutil unmount force PATH
Works every time :)
Notice the force
tag
Open up your git bash and type
echo $HOME
This shall be the same folder as you get when you open your command window (cmd) and type
echo %USERPROFILE%
And – of course – the .ssh
folder shall be present on THAT directory.
Use decode
:
print(curses.version.decode())
# 2.2
Javascript String objects have a split function, doesn't really need to be jQuery specific
var str = "nice.test"
var strs = str.split(".")
strs would be
["nice", "test"]
I'd be tempted to use JSON in your example though. The php could return the JSON which could easily be parsed
success: function(data) {
var items = JSON.parse(data)
}
In this case a[4]
is the 5th
integer in the array a
, ap
is a pointer to integer, so you are assigning an integer to a pointer and that's the warning.
So ap
now holds 45
and when you try to de-reference it (by doing *ap
) you are trying to access a memory at address 45, which is an invalid address, so your program crashes.
You should do ap = &(a[4]);
or ap = a + 4;
In c
array names decays to pointer, so a
points to the 1st element of the array.
In this way, a
is equivalent to &(a[0])
.
Some of the basic data structures in programming languages such as C and C++ are stacks and queues.
The stack data structure follows the "First In Last Out" policy (FILO) where the first element inserted or "pushed" into a stack is the last element that is removed or "popped" from the stack.
Similarly, a queue data structure follows a "First In First Out" policy (as in the case of a normal queue when we stand in line at the counter), where the first element is pushed into the queue or "Enqueued" and the same element when it has to be removed from the queue is "Dequeued".
This is quite similar to push and pop in a stack, but the terms enqueue and dequeue avoid confusion as to whether the data structure in use is a stack or a queue.
Class coders has a simple program to demonstrate the enqueue and dequeue process. You could check it out for reference.
http://classcoders.blogspot.in/2012/01/enque-and-deque-in-c.html
In options object you have used "=" sign to assign value to port but we have to use ":" to assign values to properties in object when using object literal to create an object i.e."{}" ,these curly brackets. Even when you use function expression or create an object inside object you have to use ":" sign. for e.g.:
var rishabh = {
class:"final year",
roll:123,
percent: function(marks1, marks2, marks3){
total = marks1 + marks2 + marks3;
this.percentage = total/3 }
};
john.percent(85,89,95);
console.log(rishabh.percentage);
here we have to use commas "," after each property. but you can use another style to create and initialize an object.
var john = new Object():
john.father = "raja"; //1st way to assign using dot operator
john["mother"] = "rani";// 2nd way to assign using brackets and key must be string
This is the full text of the blog post linked below:
If you've tried installing a package with pip recently, you may have encountered this error:
Could not fetch URL https://pypi.python.org/simple/Django/: There was a problem confirming the ssl certificate: <urlopen error [Errno 1] _ssl.c:504: error:0D0890A1:asn1 encoding routines:ASN1_verify:unknown message digest algorithm>
Will skip URL https://pypi.python.org/simple/Django/ when looking for download links for Django==1.5.1 (from -r requirements.txt (line 1))
Could not fetch URL https://pypi.python.org/simple/: There was a problem confirming the ssl certificate: <urlopen error [Errno 1] _ssl.c:504: error:0D0890A1:asn1 encoding routines:ASN1_verify:unknown message digest algorithm>
Will skip URL https://pypi.python.org/simple/ when looking for download links for Django==1.5.1 (from -r requirements.txt (line 1))
Cannot fetch index base URL https://pypi.python.org/simple/
Could not fetch URL https://pypi.python.org/simple/Django/1.5.1: There was a problem confirming the ssl certificate: <urlopen error [Errno 1] _ssl.c:504: error:0D0890A1:asn1 encoding routines:ASN1_verify:unknown message digest algorithm>
Will skip URL https://pypi.python.org/simple/Django/1.5.1 when looking for download links for Django==1.5.1 (from -r requirements.txt (line 1))
Could not fetch URL https://pypi.python.org/simple/Django/: There was a problem confirming the ssl certificate: <urlopen error [Errno 1] _ssl.c:504: error:0D0890A1:asn1 encoding routines:ASN1_verify:unknown message digest algorithm>
Will skip URL https://pypi.python.org/simple/Django/ when looking for download links for Django==1.5.1 (from -r requirements.txt (line 1))
Could not find any downloads that satisfy the requirement Django==1.5.1 (from -r requirements.txt (line 1))
No distributions at all found for Django==1.5.1 (from -r requirements.txt (line 1))
Storing complete log in /Users/paul/.pip/pip.log
This seems to be an issue with an old version of OpenSSL being incompatible with pip 1.3.1. If you're using a non-stock Python distribution (notably EPD 7.3), you're very likely to have a setup that isn't going to work with pip 1.3.1 without a shitload of work.
The easy workaround for now, is to install pip 1.2.1, which does not require SSL:
curl -O https://pypi.python.org/packages/source/p/pip/pip-1.2.1.tar.gz
tar xvfz pip-1.2.1.tar.gz
cd pip-1.2.1
python setup.py install
If you are using EPD, and you're not using it for a class where things might break, you may want to consider installing the new incarnation: Enthought Canopy. I know they were aware of the issues caused by the previous version of OpenSSL, and would imagine they are using a new version now that should play nicely with pip 1.3.1.
Convert the text view to an image, and the scale the image within the boundaries.
Here's an example on how to convert a view to an Image: Converting a view to Bitmap without displaying it in Android?
The problem is, your text will not be selectable, but it should do the trick. I haven't tried it, so I'm not sure how it would look (because of the scaling).
An auto-updated column is automatically updated to the current timestamp when the value of any other column in the row is changed from its current value. An auto-updated column remains unchanged if all other columns are set to their current values.
To explain it let's imagine you have only one row:
-------------------------------
| price | updated_at |
-------------------------------
| 2 | 2018-02-26 16:16:17 |
-------------------------------
Now, if you run the following update column:
update my_table
set price = 2
it will not change the value of updated_at, since price value wasn't actually changed (it was already 2).
But if you have another row with price value other than 2, then the updated_at value of that row (with price <> 3) will be updated to CURRENT_TIMESTAMP.
This works in Python 2.x.
For Python 3 look in the docs:
import urllib.request
with urllib.request.urlopen("http://www.python.org") as url:
s = url.read()
# I'm guessing this would output the html source code ?
print(s)
An effective savior for this kind of situation is Time Machine (OS X) or a similar time-based backup system. It's saved me a couple of times because I can go back and restore just that one file.
Change hidden field value with checkbox toggle like below...
HTML:
<input type='hidden' value='Unchecked' id="deleteAll" name='anyName'>
<input type="checkbox" onclick="toggle(this)"/> Delete All
Script:
function toggle(obj) {`var $input = $(obj);
if ($input.prop('checked')) {
$('#deleteAll').attr( 'value','Checked');
} else {
$('#deleteAll').attr( 'value','Unchecked');
}
}
From your statement, it seems like you merely want to write:
if (10 >= hh && hh < 18) {
...
}
This is trivial if you are given the hours already. But surely you are asking something else?
matches
method performs matching of full line, i.e. it is equivalent to find()
with '^abc$'. So, just use Pattern.compile("[a-zA-Z]").matcher(str).find()
instead. Then fix your regex. As @user unknown mentioned your regex actually matches only one character. You probably should say [a-zA-Z]+
You have to put a space between {}
and \;
So the command will be like:
find /home/me/download/ -type f -name "*.rm" -exec ffmpeg -i {} -sameq {}.mp3 && rm {} \;
The lxml library includes a very convenient syntax for XML generation, called the E-factory. Here's how I'd make the example you give:
#!/usr/bin/python
import lxml.etree
import lxml.builder
E = lxml.builder.ElementMaker()
ROOT = E.root
DOC = E.doc
FIELD1 = E.field1
FIELD2 = E.field2
the_doc = ROOT(
DOC(
FIELD1('some value1', name='blah'),
FIELD2('some value2', name='asdfasd'),
)
)
print lxml.etree.tostring(the_doc, pretty_print=True)
Output:
<root>
<doc>
<field1 name="blah">some value1</field1>
<field2 name="asdfasd">some value2</field2>
</doc>
</root>
It also supports adding to an already-made node, e.g. after the above you could say
the_doc.append(FIELD2('another value again', name='hithere'))
<div class="img-rounded">
will give you rounded corners.
Click on settings in top tool bar;
Click on debugger;
In tree, highlight "gdb/cdb debugger" by clicking it
Click "create configuration"
Click default configuration, a dialogue will appear to the right for "executable path" with a button to the right.
Click on that button and it will bring up the file that codeblocks is installed in. Just keep clicking until you create the path to the gdb.exe (it sort of finds itself).
Idisposable is implement whenever you want a deterministic (confirmed) garbage collection.
class Users : IDisposable
{
~Users()
{
Dispose(false);
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
// This method will remove current object from garbage collector's queue
// and stop calling finilize method twice
}
public void Dispose(bool disposer)
{
if (disposer)
{
// dispose the managed objects
}
// dispose the unmanaged objects
}
}
When creating and using the Users class use "using" block to avoid explicitly calling dispose method:
using (Users _user = new Users())
{
// do user related work
}
end of the using block created Users object will be disposed by implicit invoke of dispose method.
This answer has been resolved for a while and all the available options are already out there. However in this answer I'll attempt to shed a bit more light on these options to help you understand when to use what.
This post will go through the following topics:
merge
, join
, concat
There are a few options, some simpler than others depending on the use case.
DataFrame.merge
withleft_index
andright_index
(orleft_on
andright_on
using named indexes)DataFrame.join
(joins on index)pd.concat
(joins on index)
PROS | CONS | |
---|---|---|
merge |
• supports inner/left/right/full |
• can only join two frames at a time |
join |
• supports inner/left (default)/right/full |
• only supports index-index joins |
concat |
• specializes in joining multiple DataFrames at a time |
• only supports inner/full (default) joins |
Typically, an inner join on index would look like this:
left.merge(right, left_index=True, right_index=True)
Other types of joins (left, right, outer) follow similar syntax (and can be controlled using how=...
).
Notable Alternatives
DataFrame.join
defaults to a left outer join on the index.
left.join(right, how='inner',)
If you happen to get ValueError: columns overlap but no suffix specified
, you will need to specify lsuffix
and rsuffix=
arguments to resolve this. Since the column names are same, a differentiating suffix is required.
pd.concat
joins on the index and can join two or more DataFrames at once. It does a full outer join by default.
pd.concat([left, right], axis=1, sort=False)
For more information on concat
, see this post.
To perform an inner join using index of left, column of right, you will use DataFrame.merge
a combination of left_index=True
and right_on=...
.
left.merge(right, left_index=True, right_on='key')
Other joins follow a similar structure. Note that only merge
can perform index to column joins. You can join on multiple levels/columns, provided the number of index levels on the left equals the number of columns on the right.
join
and concat
are not capable of mixed merges. You will need to set the index as a pre-step using DataFrame.set_index
.
This post is an abridged version of my work in Pandas Merging 101. Please follow this link for more examples and other topics on merging.
Do it this way (make necessary changes in code)..
SqlConnection con = new SqlConnection(GetConnectionString());
con.Open();
SqlCommand cmd = new SqlCommand("CheckUser", con);
cmd.CommandType = CommandType.StoredProcedure;
SqlParameter p1 = new SqlParameter("username", username.Text);
SqlParameter p2 = new SqlParameter("password", password.Text);
cmd.Parameters.Add(p1);
cmd.Parameters.Add(p2);
SqlDataReader rd = cmd.ExecuteReader();
if(rd.HasRows)
{
//do the things
}
else
{
lblinfo.Text = "abc";
}
For only horizontal lines
ax = plt.axes()
ax.yaxis.grid() # horizontal lines
This worked
Date's compareTo() you're using will work for ascending order.
To do descending, just reverse the value of compareTo() coming out. You can use a single Comparator class that takes in a flag/enum in the constructor that identifies the sort order
public int compare(MyObject lhs, MyObject rhs) {
if(SortDirection.Ascending == m_sortDirection) {
return lhs.MyDateTime.compareTo(rhs.MyDateTime);
}
return rhs.MyDateTime.compareTo(lhs.MyDateTime);
}
You need to call Collections.sort() to actually sort the list.
As a side note, I'm not sure why you're defining your map inside your for loop. I'm not exactly sure what your code is trying to do, but I assume you want to populate the indexed values from your for loop in to the map.
This calculator does not have any modulo function. However there is quite simple way how to compute modulo using display mode ab/c
(instead of traditional d/c
).
How to switch display mode to ab/c
:
ab/c
(number 1).Now do your calculation (in comp mode), like 50 / 3
and you will see 16 2/3
, thus, mod is 2
. Or try 54 / 7
which is 7 5/7
(mod is 5
).
If you don't see any fraction then the mod is 0
like 50 / 5 = 10
(mod is 0
).
The remainder fraction is shown in reduced form, so 60 / 8
will result in 7 1/2
. Remainder is 1/2
which is 4/8
so mod is 4
.
EDIT: As @lawal correctly pointed out, this method is a little bit tricky for negative numbers because the sign of the result would be negative.
For example -121 / 26 = -4 17/26
, thus, mod is -17
which is +9
in mod 26. Alternatively you can add the modulo base to the computation for negative numbers: -121 / 26 + 26 = 21 9/26
(mod is 9
).
EDIT2: As @simpatico pointed out, this method will not work for numbers that are out of calculator's precision. If you want to compute say 200^5 mod 391
then some tricks from algebra are needed. For example, using rule
(A * B) mod C = ((A mod C) * B) mod C
we can write:
200^5 mod 391 = (200^3 * 200^2) mod 391 = ((200^3 mod 391) * 200^2) mod 391 = 98
If you are using EF6 (Entity Framework 6+), this has changed for database calls to SQL.
See: http://msdn.microsoft.com/en-us/data/dn456843.aspx
use context.Database.BeginTransaction.
using (var context = new BloggingContext()) { using (var dbContextTransaction = context.Database.BeginTransaction()) { try { context.Database.ExecuteSqlCommand( @"UPDATE Blogs SET Rating = 5" + " WHERE Name LIKE '%Entity Framework%'" ); var query = context.Posts.Where(p => p.Blog.Rating >= 5); foreach (var post in query) { post.Title += "[Cool Blog]"; } context.SaveChanges(); dbContextTransaction.Commit(); } catch (Exception) { dbContextTransaction.Rollback(); //Required according to MSDN article throw; //Not in MSDN article, but recommended so the exception still bubbles up } } }
My basic ~/.vimrc with comment:
set number " show line number
set tabstop=2 " set display width of tab; 1 tab = x space with
set expandtab " transform tab to x space (x is tabstop)
set autoindent " auto indent; new line with number of space at the beginning same as previous
set shiftwidth=2 " number of space append to lines when type >>
Use the 'EntireColumn' property, that's what it is there for. C# snippet, but should give you a good indication of how to do this:
string rangeQuery = "A1:A1";
Range range = workSheet.get_Range(rangeQuery, Type.Missing);
range = range.EntireColumn;
Essentially, it's the way Microsoft introduces its C++ extensions so that they won't conflict with future extensions of standard C++. With __declspec, you can attribute a function or class; the exact meaning varies depending on the nature of __declspec. __declspec(naked), for example, suppresses prolog/epilog generation (for interrupt handlers, embeddable code, etc), __declspec(thread) makes a variable thread-local, and so on.
The full list of __declspec attributes is available on MSDN, and varies by compiler version and platform.
If you want to access the property without creating an intermediate variable, use the {}
notation:
$something = $object->{'something'};
That also allows you to build the property name in a loop for example:
for ($i = 0; $i < 5; $i++) {
$something = $object->{'something' . $i};
// ...
}
You should use the HasValue
property:
SomeProperty.HasValue
For example:
if (SomeProperty.HasValue)
{
// Do Something
}
else
{
// Do Something Else
}
FYI
public Nullable<System.Guid> SomeProperty { get; set; }
is equivalent to:
public System.Guid? SomeProperty { get; set; }
The MSDN Reference: http://msdn.microsoft.com/en-us/library/sksw8094.aspx
Ruby has eleven methods to find elements in an array.
The preferred one is include?
or, for repeated access, creat a Set and then call include?
or member?
.
Here are all of them:
array.include?(element) # preferred method
array.member?(element)
array.to_set.include?(element)
array.to_set.member?(element)
array.index(element) > 0
array.find_index(element) > 0
array.index { |each| each == element } > 0
array.find_index { |each| each == element } > 0
array.any? { |each| each == element }
array.find { |each| each == element } != nil
array.detect { |each| each == element } != nil
They all return a true
ish value if the element is present.
include?
is the preferred method. It uses a C-language for
loop internally that breaks when an element matches the internal rb_equal_opt/rb_equal
functions. It cannot get much more efficient unless you create a Set for repeated membership checks.
VALUE
rb_ary_includes(VALUE ary, VALUE item)
{
long i;
VALUE e;
for (i=0; i<RARRAY_LEN(ary); i++) {
e = RARRAY_AREF(ary, i);
switch (rb_equal_opt(e, item)) {
case Qundef:
if (rb_equal(e, item)) return Qtrue;
break;
case Qtrue:
return Qtrue;
}
}
return Qfalse;
}
member?
is not redefined in the Array
class and uses an unoptimized implementation from the Enumerable
module that literally enumerates through all elements:
static VALUE
member_i(RB_BLOCK_CALL_FUNC_ARGLIST(iter, args))
{
struct MEMO *memo = MEMO_CAST(args);
if (rb_equal(rb_enum_values_pack(argc, argv), memo->v1)) {
MEMO_V2_SET(memo, Qtrue);
rb_iter_break();
}
return Qnil;
}
static VALUE
enum_member(VALUE obj, VALUE val)
{
struct MEMO *memo = MEMO_NEW(val, Qfalse, 0);
rb_block_call(obj, id_each, 0, 0, member_i, (VALUE)memo);
return memo->v2;
}
Translated to Ruby code this does about the following:
def member?(value)
memo = [value, false, 0]
each_with_object(memo) do |each, memo|
if each == memo[0]
memo[1] = true
break
end
memo[1]
end
Both include?
and member?
have O(n) time complexity since the both search the array for the first occurrence of the expected value.
We can use a Set to get O(1) access time at the cost of having to create a Hash representation of the array first. If you repeatedly check membership on the same array this initial investment can pay off quickly. Set
is not implemented in C but as plain Ruby class, still the O(1) access time of the underlying @hash
makes this worthwhile.
Here is the implementation of the Set class:
module Enumerable
def to_set(klass = Set, *args, &block)
klass.new(self, *args, &block)
end
end
class Set
def initialize(enum = nil, &block) # :yields: o
@hash ||= Hash.new
enum.nil? and return
if block
do_with_enum(enum) { |o| add(block[o]) }
else
merge(enum)
end
end
def merge(enum)
if enum.instance_of?(self.class)
@hash.update(enum.instance_variable_get(:@hash))
else
do_with_enum(enum) { |o| add(o) }
end
self
end
def add(o)
@hash[o] = true
self
end
def include?(o)
@hash.include?(o)
end
alias member? include?
...
end
As you can see the Set class just creates an internal @hash
instance, maps all objects to true
and then checks membership using Hash#include?
which is implemented with O(1) access time in the Hash class.
I won't discuss the other seven methods as they are all less efficient.
There are actually even more methods with O(n) complexity beyond the 11 listed above, but I decided to not list them since they scan the entire array rather than breaking at the first match.
Don't use these:
# bad examples
array.grep(element).any?
array.select { |each| each == element }.size > 0
...
In the Manifest, you can set the screenOrientation to landscape. It would look something like this in the XML:
<activity android:name="MyActivity"
android:screenOrientation="landscape"
android:configChanges="keyboardHidden|orientation|screenSize">
...
</activity>
Where MyActivity
is the one you want to stay in landscape.
The android:configChanges=...
line prevents onResume()
, onPause()
from being called when the screen is rotated. Without this line, the rotation will stay as you requested but the calls will still be made.
Note: keyboardHidden
and orientation
are required for < Android 3.2 (API level 13), and all three options are required 3.2 or above, not just orientation
.
++x is called preincrement while x++ is called postincrement.
int x = 5, y = 5;
System.out.println(++x); // outputs 6
System.out.println(x); // outputs 6
System.out.println(y++); // outputs 5
System.out.println(y); // outputs 6
Another option is use Oracle SQL Developer. Two steps as below:
(1) First of all, you need to connect SQL Developer to your PostgreSQL database.
(2) Then you can generate an entity-relationship (ER) diagram using SQL Developer
ALL_SOURCE describes the text source of the stored objects accessible to the current user.
Here is one of the solution
select * from ALL_SOURCE where text like '%some string%';
As suggested in "PostgreSQL database default location on Linux", under Linux you can find out using the following command:
ps aux | grep postgres | grep -- -D
it is a very old thread, I know but this might help too if somebody gets here once they search for a solution.
Basically I used the document.currentScript to get the element from where my code is running and I filter using the name of the variable I am looking for. I did it extending currentScript with a method called "get", so we will be able to fetch the value inside that script by using:
document.currentScript.get('get_variable_name');
In this way we can use standard URI to retrieve the variables without adding special attributes.
This is the final code
document.currentScript.get = function(variable) {
if(variable=(new RegExp('[?&]'+encodeURIComponent(variable)+'=([^&]*)')).exec(this.src))
return decodeURIComponent(variable[1]);
};
I was forgetting about IE :) It could not be that easier... Well I did not mention that document.currentScript is a HTML5 property. It has not been included for different versions of IE (I tested until IE11, and it was not there yet). For IE compatibility, I added this portion to the code:
document.currentScript = document.currentScript || (function() {
var scripts = document.getElementsByTagName('script');
return scripts[scripts.length - 1];
})();
What we are doing here is to define some alternative code for IE, which returns the current script object, which is required in the solution to extract parameters from the src property. This is not the perfect solution for IE since there are some limitations; If the script is loaded asynchronously. Newer browsers should include ".currentScript" property.
I hope it helps.
SELECT `product`.*, `customer1`.`name1`, `customer2`.`name2`
FROM `product`
LEFT JOIN `customer1` ON `product`.`cid` = `customer1`.`cid`
LEFT JOIN `customer2` ON `product`.`cid` = `customer2`.`cid`
The way for loop is processed is as follows
1 First, initialization is performed (i=0)
2 the check is performed (i < n)
3 the code in the loop is executed.
4 the value is incremented
5 Repeat steps 2 - 4
This is the reason why, there is no difference between i++ and ++i in the for loop which has been used.
Store it in a cookie that only lasts for the current browsing session
There's a static method values()
which is documented, but not where you'd expect it: http://docs.oracle.com/javase/tutorial/java/javaOO/enum.html
enum MyEnum {
FIRST, SECOND, THIRD;
private static MyEnum[] allValues = values();
public static MyEnum fromOrdinal(int n) {return allValues[n];}
}
In principle, you can use just values()[i]
, but there are rumors that values()
will create a copy of the array each time it is invoked.
You probably have changes on github that you never merged. Try git pull
to fetch and merge the changes, then you should be able to push. Sorry if I misunderstood your question.
This code will list out all the form variables that are being sent in a POST. This way you can see if you have the proper names of the post values.
string[] keys = Request.Form.AllKeys;
for (int i= 0; i < keys.Length; i++)
{
Response.Write(keys[i] + ": " + Request.Form[keys[i]] + "<br>");
}
I realize this is an old question, but I like this solution enough to share it.
% cat > numbers.txt
1
2
3
4
5
^D
% cat numbers.txt | perl -lpe '$c+=$_}{$_=$c'
15
If there is interest, I'll explain how it works.
You just have to reset the values you don't want to their defaults. No need to get into a mess by using !important
.
#zoomTarget .slikezamenjanje img {
max-height: auto;
padding-right: 0px;
}
I think the key datum you are missing is that CSS comes with default values. If you want to override a value, set it back to its default, which you can look up.
For example, all CSS height
and width
attributes default to auto
.
Draco,
You can do it like this:
$("#datePickerId").datepicker(
{ dateFormat: 'DD, d MM yy',
minDate: new Date(2009, 10 - 1, 25), // it will set minDate from 25 October 2009
showOn: 'button',
buttonImage: '../../images/calendar.gif',
buttonImageOnly: true,
hideIfNoPrevNext: true
}
);
remember to write -1 after month (ex. for june is -> 6 -1)
The error was that you cannot use this
in the grep, but you must use a reference to the element. This works:
function findPurpose(purposeName){
return $.grep(purposeObjects, function(n, i){
return n.purpose == purposeName;
});
};
findPurpose("daily");
returns:
[Object { purpose="daily"}]
Using Java 8:
private static Comparator<String> nullSafeStringComparator = Comparator
.nullsFirst(String::compareToIgnoreCase);
private static Comparator<Metadata> metadataComparator = Comparator
.comparing(Metadata::getName, nullSafeStringComparator)
.thenComparing(Metadata::getValue, nullSafeStringComparator);
public int compareTo(Metadata that) {
return metadataComparator.compare(this, that);
}
You can do it this way:
=IF(E9>21,"Text 1",IF(AND(E9>=5,E9<=21),"Test 2","Text 3"))
Note I assume you meant >=
and <=
here since your description skipped the values 5
and 21
, but you can adjust these inequalities as needed.
Or you can do it this way:
=IF(E9>21,"Text 1",IF(E9<5,"Text 3","Text 2"))
I ran into this problem when SQL Server 2014 standard was installed on a server where SQL Server Express was also installed. I had opened SSMS from a desktop shortcut, not realizing right away that it was SSMS for SQL Server Express, not for 2014. SSMS for Express returned the error, but SQL Server 2014 did not.
Use LinkedHashMap and use this function.
private LinkedHashMap<Integer, String> map = new LinkedHashMap<Integer, String>();
Define like this and.
private Entry getEntry(int id){
Iterator iterator = map.entrySet().iterator();
int n = 0;
while(iterator.hasNext()){
Entry entry = (Entry) iterator.next();
if(n == id){
return entry;
}
n ++;
}
return null;
}
The function can return the selected entry.
I applied CSS styling to an anchored HREF attribute fully emulating the push button behaviors I needed (hover, active, background-color, etc., etc.). HTML markup is much simpler a-n-d eliminates the get/post complexity associated with using a form-based approach.
<a class="GYM" href="http://www.spufalcons.com/index.aspx?tab=gymnastics&path=gym">Gymnastics</a>
It seems you need to run ssh-agent
before using it:
eval `ssh-agent -s`
That question was answered in this topic: Could not open a connection to your authentication agent
One solution is to wrap it in a subquery
SELECT *
FROM
(
SELECT COUNT(column1),column1 FROM table GROUP BY column1
UNION ALL
SELECT COUNT(column2),column2 FROM table GROUP BY column2
UNION ALL
SELECT COUNT(column3),column3 FROM table GROUP BY column3
) s
Change the button to
<button id="search">Search</button>
and add the following script
var url = '@Url.Action("DisplaySearchResults", "Search")';
$('#search').click(function() {
var keyWord = $('#Keyword').val();
$('#searchResults').load(url, { searchText: keyWord });
})
and modify the controller method to accept the search text
public ActionResult DisplaySearchResults(string searchText)
{
var model = // build list based on parameter searchText
return PartialView("SearchResults", model);
}
The jQuery .load
method calls your controller method, passing the value of the search text and updates the contents of the <div>
with the partial view.
Side note: The use of a <form>
tag and @Html.ValidationSummary()
and @Html.ValidationMessageFor()
are probably not necessary here. Your never returning the Index
view so ValidationSummary
makes no sense and I assume you want a null
search text to return all results, and in any case you do not have any validation attributes for property Keyword
so there is nothing to validate.
Edit
Based on OP's comments that SearchCriterionModel
will contain multiple properties with validation attributes, then the approach would be to include a submit button and handle the forms .submit()
event
<input type="submit" value="Search" />
var url = '@Url.Action("DisplaySearchResults", "Search")';
$('form').submit(function() {
if (!$(this).valid()) {
return false; // prevent the ajax call if validation errors
}
var form = $(this).serialize();
$('#searchResults').load(url, form);
return false; // prevent the default submit action
})
and the controller method would be
public ActionResult DisplaySearchResults(SearchCriterionModel criteria)
{
var model = // build list based on the properties of criteria
return PartialView("SearchResults", model);
}
Another way of using recursion:
def updateDict(dict1,dict2):
keys1 = list(dict1.keys())
keys2= list(dict2.keys())
keys2 = [x for x in keys2 if x in keys1]
for x in keys2:
if (x in keys1) & (type(dict1[x]) is dict) & (type(dict2[x]) is dict):
updateDict(dict1[x],dict2[x])
else:
dict1.update({x:dict2[x]})
return(dict1)
rails -d mysql ProjectName
i had the same problem, i added the following lines in build.gradle
allprojects {
repositories {
jcenter()
maven { url "https://jitpack.io" }
maven {
url 'http://dl.bintray.com/dev-fingerlinks/maven'
}
mavenCentral()
}
}
If you're using application.properties in spring boot app, then just put the below line into application.properties and it should work:
spring.datasource.url: jdbc:mysql://google/?cloudSqlInstance=&socketFactory=com.google.cloud.sql.mysql.SocketFactory&user=****&password=****
you can first reverse array and then add elem to array then reverse back it.
const arr = [2,3,4,5,6];
const arr2 = 1;
arr.reverse();
//[6,5,4,3,2]
arr.push(arr2);
console.log(arr.reverse()); // [1,2,3,4,5,6]
good lock
ali alizadeh.
If p is a variable that contains a Promise, then p.then(empty);
should dismiss the promise when it eventually completes or if it is already complete (yes, I know this isn't the original question, but it is my question). "empty" is function empty() {}
. I'm just a beginner and probably wrong, but these other answers seem too complicated. Promises are supposed to be simple.
Way to unlock the user :
$ sqlplus /nolog
SQL > conn sys as sysdba
SQL > ALTER USER USER_NAME ACCOUNT UNLOCK;
and open new terminal
SQL > sqlplus / as sysdba
connected
SQL > conn username/password //which username u gave before unlock
password:password
password:password
You can write bash in your package.json:
# package.json
{
"name": ...,
"version": ...,
"scripts": {
"build": "NODE_ENV=production npm run webpack && cp -v <this> <that> && echo ok",
...
}
}
The error occurred because the code is not for the default compiler used there. Paste this code in effective POM before the root element ends, after declaring dependencies, to change the compiler used. Adjust version as you need.
<dependencies>
...
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.5.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
It seems that you have invalid JSON. In that case, that's totally dependent on the data the server sends you which you have not shown. I would suggest running the response through a JSON validator.
Using <table> is not a bad choice. Of course it is bit old fashioned.
But still not obsolete. But if you prefer you can use "Boostrap". There you have options for panels and enhanced forms.
This is the sample code for your requirement. Used minimal styles to simplify.
<!DOCTYPE html>
<html>
<head>
<title>Simple Login Form</title>
</head>
<style>
table{
border-style: solid;
position: absolute;
top: 40%;
left : 40%;
padding:10px;
}
</style>
<body>
<form method="post" action="login.php">
<table>
<tr bgcolor="black">
<th colspan="3"><font color="white">Enter login details</th>
</tr>
<tr height="20"></tr>
<tr>
<td>User Name</td>
<td>:</td>
<td>
<input type="text" name="username"/>
</td>
</tr>
<tr>
<td>Password</td>
<td>:</td>
<td>
<input type="password" name="password"/>
</td>
</tr>
<tr height="10"></tr>
<tr>
<td></td>
<td></td>
<td align="center"><input type="submit" value="Submit"></td>
</tr>
</table>
</form>
</body>
</html>
As mentioned by joanq MariaDB now seems to support CHECK constraints among other goodies:
"Support for CHECK CONSTRAINT (MDEV-7563)."
https://mariadb.com/kb/en/mariadb/mariadb-1021-release-notes/
I had this issue and solved it using the chomp function described above:
def chomp(s):
return s[:-1] if s.endswith('\n') else s
def trim_newlines(slist):
for i in range(len(slist)):
slist[i] = chomp(slist[i])
return slist
.....
names = theFile.readlines()
names = trim_newlines(names)
....
I was getting similar errors and eventually found just that cleaning the build folder resolved my issue.
mvn clean install
A less verbose approach:
int number = [dict[@"integer"] intValue];
Everybody that using: var myVar = 'token', is probably the worst idea. I can print it dirrectly in the console. You need to encrypt on the client side, then decrypt on server side.
You can call the super class's constructor like this
class A(object):
def __init__(self, number):
print "parent", number
class B(A):
def __init__(self):
super(B, self).__init__(5)
b = B()
NOTE:
This will work only when the parent class inherits object
If you open the Event Log viewer before the event source is created, for example while installing a service, you'll get that error message. You don't need to restart the OS: you simply have to close and open the event viewer.
NOTE: I don't provide a custom messages file. The creation of the event source uses the default configuration, as shown on Matt's answer.
I believe if you're willing to apply the approach to every possible orientation and to negative versions, a good start to image recognition (with good reliability) is to use eigenfaces: http://en.wikipedia.org/wiki/Eigenface
Another idea would be to transform both images into vectors of their components. A good way to do this is to create a vector that operates in x*y dimensions (x being the width of your image and y being the height), with the value for each dimension applying to the (x,y) pixel value. Then run a variant of K-Nearest Neighbours with two categories: match and no match. If it's sufficiently close to the original image it will fit in the match category, if not then it won't.
K Nearest Neighbours(KNN) can be found here, there are other good explanations of it on the web too: http://en.wikipedia.org/wiki/K-nearest_neighbor_algorithm
The benefits of KNN is that the more variants you're comparing to the original image, the more accurate the algorithm becomes. The downside is you need a catalogue of images to train the system first.
<!DOCTYPE html>
<html>
<head>
<style>
div {
padding: 20px;
resize: both;
overflow: auto;
}
img{
height: 100%;
width: 100%;
object-fit: contain;
}
</style>
</head>
<body>
<h1>The resize Property</h1>
<div>
<p>Let the user resize both the height and the width of this 1234567891011 div
element.
</p>
<p>To resize: Click and drag the bottom right corner of this div element.</p>
<img src="images/scenery.jpg" alt="Italian ">
</div>
<p><b>Note:</b> Internet Explorer does not support the resize property.</p>
</body>
</html>
You can use the dynamic object ViewBag
to pass data from Controllers to Views.
Add the following to your controller:
ViewBag.MyList = myList;
Then you can acces it from your view:
@ViewBag.MyList
// e.g.
@foreach (var item in ViewBag.MyList) { ... }
You can achieve this with the display
property:
html, body {
height:100%;
margin:0;
padding:0;
}
#section1 {
width:100%; /*full width*/
min-height:90%;
text-align:center;
display:table; /*acts like a table*/
}
h1{
margin:0;
padding:0;
vertical-align:middle; /*middle centred*/
display:table-cell; /*acts like a table cell*/
}
I can attest to the fact that -webkit-transform: translate3d(0, 0, 0);
will mess with the new position: -webkit-sticky;
property. With a left drawer navigation pattern that I was working on, the hardware acceleration I wanted with the transform property was messing with the fixed positioning of my top nav bar. I turned off the transform and the positioning worked fine.
Luckily, I seem to have had hardware acceleration on already, because I had -webkit-font-smoothing: antialiased
on the html element. I was testing this behavior in iOS7 and Android.
This saved my day. The simplest approach to get the path from URI.
//kotlin
myuri = data.data
val realPath = myuri.path
Log.d(TAG, "path: $realPath")
Returns path :
path: /storage/emulated/0/Download/CutOFF - Escuro (Original Mix).mp3
To take 6footunder's comment and turn it into an answer, HttpContent
is abstract so you need to use one of the derived classes:
The answer is Yes, but you should consider the following 3 points.
No two main method parameter should be the same
Eg.
public static void main(int i)
public static void main(int i, int j)
public static void main(double j)
public static void main(String[] args)
Java’s actual main method is the one with (String[] args)
, So the Actual execution starts from public static void main(String[] args), so the main method with (String[] args)
is must in a class unless if it is not a child class.
In order for other main methods to execute you need to call them from inside the (String[] args)
main method.
Here is a detailed video about the same: https://www.youtube.com/watch?v=Qlhslsluhg4&feature=youtu.be
Your specific case can simply be corrected to be working:
<script type="text/javascript">
var myButton = document.getElementById("myButton");
var myMessage = "it's working";
myButton.onclick = function() { alert(myMessage); };
</script>
This example will work because the anonymous function created and assigned as a handler to element will have access to variables defined in the context where it was created.
For the record, a handler (that you assign through setting onxxx property) expects single argument to take that is event object being passed by the DOM, and you cannot force passing other argument in there
While technically correct, the other answers would benefit from an explanation of Angular's URL-to-route matching. I don't think you can fully (pardon the pun) understand what pathMatch: full
does if you don't know how the router works in the first place.
Let's first define a few basic things. We'll use this URL as an example: /users/james/articles?from=134#section
.
It may be obvious but let's first point out that query parameters (?from=134
) and fragments (#section
) do not play any role in path matching. Only the base url (/users/james/articles
) matters.
Angular splits URLs into segments. The segments of /users/james/articles
are, of course, users
, james
and articles
.
The router configuration is a tree structure with a single root node. Each Route
object is a node, which may have children
nodes, which may in turn have other children
or be leaf nodes.
The goal of the router is to find a router configuration branch, starting at the root node, which would match exactly all (!!!) segments of the URL. This is crucial! If Angular does not find a route configuration branch which could match the whole URL - no more and no less - it will not render anything.
E.g. if your target URL is /a/b/c
but the router is only able to match either /a/b
or /a/b/c/d
, then there is no match and the application will not render anything.
Finally, routes with redirectTo
behave slightly differently than regular routes, and it seems to me that they would be the only place where anyone would really ever want to use pathMatch: full
. But we will get to this later.
prefix
) path matchingThe reasoning behind the name prefix
is that such a route configuration will check if the configured path
is a prefix of the remaining URL segments. However, the router is only able to match full segments, which makes this naming slightly confusing.
Anyway, let's say this is our root-level router configuration:
const routes: Routes = [
{
path: 'products',
children: [
{
path: ':productID',
component: ProductComponent,
},
],
},
{
path: ':other',
children: [
{
path: 'tricks',
component: TricksComponent,
},
],
},
{
path: 'user',
component: UsersonComponent,
},
{
path: 'users',
children: [
{
path: 'permissions',
component: UsersPermissionsComponent,
},
{
path: ':userID',
children: [
{
path: 'comments',
component: UserCommentsComponent,
},
{
path: 'articles',
component: UserArticlesComponent,
},
],
},
],
},
];
Note that every single Route
object here uses the default matching strategy, which is prefix
. This strategy means that the router iterates over the whole configuration tree and tries to match it against the target URL segment by segment until the URL is fully matched. Here's how it would be done for this example:
users
.'products' !== 'users'
, so skip that branch. Note that we are using an equality check rather than a .startsWith()
or .includes()
- only full segment matches count!:other
matches any value, so it's a match. However, the target URL is not yet fully matched (we still need to match james
and articles
), thus the router looks for children.:other
is tricks
, which is !== 'james'
, hence not a match.'user' !== 'users
, skip branch.'users' === 'users
- the segment matches. However, this is not a full match yet, thus we need to look for children (same as in step 3).'permissions' !== 'james'
, skip it.:userID
matches anything, thus we have a match for the james
segment. However this is still not a full match, thus we need to look for a child which would match articles
.
:userID
has a child route articles
, which gives us a full match! Thus the application renders UserArticlesComponent
.full
) matchingImagine now that the users
route configuration object looked like this:
{
path: 'users',
component: UsersComponent,
pathMatch: 'full',
children: [
{
path: 'permissions',
component: UsersPermissionsComponent,
},
{
path: ':userID',
component: UserComponent,
children: [
{
path: 'comments',
component: UserCommentsComponent,
},
{
path: 'articles',
component: UserArticlesComponent,
},
],
},
],
}
Note the usage of pathMatch: full
. If this were the case, steps 1-5 would be the same, however step 6 would be different:
'users' !== 'users/james/articles
- the segment does not match because the path configuration users
with pathMatch: full
does not match the full URL, which is users/james/articles
.What if we had this instead:
{
path: 'users/:userID',
component: UsersComponent,
pathMatch: 'full',
children: [
{
path: 'comments',
component: UserCommentsComponent,
},
{
path: 'articles',
component: UserArticlesComponent,
},
],
}
users/:userID
with pathMatch: full
matches only users/james
thus it's a no-match once again, and the application renders nothing.
Let's consider this:
{
path: 'users',
children: [
{
path: 'permissions',
component: UsersPermissionsComponent,
},
{
path: ':userID',
component: UserComponent,
pathMatch: 'full',
children: [
{
path: 'comments',
component: UserCommentsComponent,
},
{
path: 'articles',
component: UserArticlesComponent,
},
],
},
],
}
In this case:
'users' === 'users
- the segment matches, but james/articles
still remains unmatched. Let's look for children.'permissions' !== 'james'
- skip.:userID'
can only match a single segment, which would be james
. However, it's a pathMatch: full
route, and it must match james/articles
(the whole remaining URL). It's not able to do that and thus it's not a match (so we skip this branch)!As you may have noticed, a pathMatch: full
configuration is basically saying this:
Ignore my children and only match me. If I am not able to match all of the remaining URL segments myself, then move on.
Any Route
which has defined a redirectTo
will be matched against the target URL according to the same principles. The only difference here is that the redirect is applied as soon as a segment matches. This means that if a redirecting route is using the default prefix
strategy, a partial match is enough to cause a redirect. Here's a good example:
const routes: Routes = [
{
path: 'not-found',
component: NotFoundComponent,
},
{
path: 'users',
redirectTo: 'not-found',
},
{
path: 'users/:userID',
children: [
{
path: 'comments',
component: UserCommentsComponent,
},
{
path: 'articles',
component: UserArticlesComponent,
},
],
},
];
For our initial URL (/users/james/articles
), here's what would happen:
'not-found' !== 'users'
- skip it.'users' === 'users'
- we have a match.redirectTo: 'not-found'
, which is applied immediately.not-found
.not-found
right away. The application renders NotFoundComponent
.Now consider what would happen if the users
route also had pathMatch: full
:
const routes: Routes = [
{
path: 'not-found',
component: NotFoundComponent,
},
{
path: 'users',
pathMatch: 'full',
redirectTo: 'not-found',
},
{
path: 'users/:userID',
children: [
{
path: 'comments',
component: UserCommentsComponent,
},
{
path: 'articles',
component: UserArticlesComponent,
},
],
},
];
'not-found' !== 'users'
- skip it.users
would match the first segment of the URL, but the route configuration requires a full
match, thus skip it.'users/:userID'
matches users/james
. articles
is still not matched but this route has children.articles
in the children. The whole URL is now matched and the application renders UserArticlesComponent
.path: ''
)The empty path is a bit of a special case because it can match any segment without "consuming" it (so it's children would have to match that segment again). Consider this example:
const routes: Routes = [
{
path: '',
children: [
{
path: 'users',
component: BadUsersComponent,
}
]
},
{
path: 'users',
component: GoodUsersComponent,
},
];
Let's say we are trying to access /users
:
path: ''
will always match, thus the route matches. However, the whole URL has not been matched - we still need to match users
!users
, which matches the remaining (and only!) segment and we have a full match. The application renders BadUsersComponent
.The OP used this router configuration:
const routes: Routes = [
{
path: 'welcome',
component: WelcomeComponent,
},
{
path: '',
redirectTo: 'welcome',
pathMatch: 'full',
},
{
path: '**',
redirectTo: 'welcome',
pathMatch: 'full',
},
];
If we are navigating to the root URL (/
), here's how the router would resolve that:
welcome
does not match an empty segment, so skip it.path: ''
matches the empty segment. It has a pathMatch: 'full'
, which is also satisfied as we have matched the whole URL (it had a single empty segment).welcome
happens and the application renders WelcomeComponent
.pathMatch: 'full'
?Actually, one would expect the whole thing to behave exactly the same. However, Angular explicitly prevents such a configuration ({ path: '', redirectTo: 'welcome' }
) because if you put this Route
above welcome
, it would theoretically create an endless loop of redirects. So Angular just throws an error, which is why the application would not work at all! (https://angular.io/api/router/Route#pathMatch)
Actually, this does not make too much sense to me because Angular also has implemented a protection against such endless redirects - it only runs a single redirect per routing level! This would stop all further redirects (as you'll see in the example below).
path: '**'
?path: '**'
will match absolutely anything (af/frewf/321532152/fsa
is a match) with or without a pathMatch: 'full'
.
Also, since it matches everything, the root path is also included, which makes { path: '', redirectTo: 'welcome' }
completely redundant in this setup.
Funnily enough, it is perfectly fine to have this configuration:
const routes: Routes = [
{
path: '**',
redirectTo: 'welcome'
},
{
path: 'welcome',
component: WelcomeComponent,
},
];
If we navigate to /welcome
, path: '**'
will be a match and a redirect to welcome will happen. Theoretically this should kick off an endless loop of redirects but Angular stops that immediately (because of the protection I mentioned earlier) and the whole thing works just fine.
There is PEP 8, as other answers show, but PEP 8 is only the styleguide for the standard library, and it's only taken as gospel therein. One of the most frequent deviations of PEP 8 for other pieces of code is the variable naming, specifically for methods. There is no single predominate style, although considering the volume of code that uses mixedCase, if one were to make a strict census one would probably end up with a version of PEP 8 with mixedCase. There is little other deviation from PEP 8 that is quite as common.
I started with johncarls solution, but needed to adjust it to get exactly what I needed. Mainly, I needed it to rotate clockwise when the angle increased. I also needed 0 degrees to point NORTH. His solution got me close, but I decided to post my solution as well in case it helps anyone else.
I've added some additional comments to help explain my understanding of the function in case you need to make simple modifications.
/**
* Calculates the angle from centerPt to targetPt in degrees.
* The return should range from [0,360), rotating CLOCKWISE,
* 0 and 360 degrees represents NORTH,
* 90 degrees represents EAST, etc...
*
* Assumes all points are in the same coordinate space. If they are not,
* you will need to call SwingUtilities.convertPointToScreen or equivalent
* on all arguments before passing them to this function.
*
* @param centerPt Point we are rotating around.
* @param targetPt Point we want to calcuate the angle to.
* @return angle in degrees. This is the angle from centerPt to targetPt.
*/
public static double calcRotationAngleInDegrees(Point centerPt, Point targetPt)
{
// calculate the angle theta from the deltaY and deltaX values
// (atan2 returns radians values from [-PI,PI])
// 0 currently points EAST.
// NOTE: By preserving Y and X param order to atan2, we are expecting
// a CLOCKWISE angle direction.
double theta = Math.atan2(targetPt.y - centerPt.y, targetPt.x - centerPt.x);
// rotate the theta angle clockwise by 90 degrees
// (this makes 0 point NORTH)
// NOTE: adding to an angle rotates it clockwise.
// subtracting would rotate it counter-clockwise
theta += Math.PI/2.0;
// convert from radians to degrees
// this will give you an angle from [0->270],[-180,0]
double angle = Math.toDegrees(theta);
// convert to positive range [0-360)
// since we want to prevent negative angles, adjust them now.
// we can assume that atan2 will not return a negative value
// greater than one partial rotation
if (angle < 0) {
angle += 360;
}
return angle;
}
This is of course subjective, but I think it strongly improves on two points:
condition
holds.In order to assign a variable safely you have to use the SET-SELECT statement:
SET @PrimaryContactKey = (SELECT c.PrimaryCntctKey
FROM tarcustomer c, tarinvoice i
WHERE i.custkey = c.custkey
AND i.invckey = @tmp_key)
Make sure you have both a starting and an ending parenthesis!
The reason the SET-SELECT version is the safest way to set a variable is twofold.
1. The SELECT returns several posts
What happens if the following select results in several posts?
SELECT @PrimaryContactKey = c.PrimaryCntctKey
FROM tarcustomer c, tarinvoice i
WHERE i.custkey = c.custkey
AND i.invckey = @tmp_key
@PrimaryContactKey
will be assigned the value from the last post in the result.
In fact @PrimaryContactKey
will be assigned one value per post in the result, so it will consequently contain the value of the last post the SELECT-command was processing.
Which post is "last" is determined by any clustered indexes or, if no clustered index is used or the primary key is clustered, the "last" post will be the most recently added post. This behavior could, in a worst case scenario, be altered every time the indexing of the table is changed.
With a SET-SELECT statement your variable will be set to null
.
2. The SELECT returns no posts
What happens, when using the second version of the code, if your select does not return a result at all?
In a contrary to what you may believe the value of the variable will not be null - it will retain it's previous value!
This is because, as stated above, SQL will assign a value to the variable once per post - meaning it won't do anything with the variable if the result contains no posts. So, the variable will still have the value it had before you ran the statement.
With the SET-SELECT statement the value will be null
.
For those of you, who doesn't like this monstrous new AClass[] { ... }
syntax, here's some sugar:
public AClass[] c(AClass... arr) { return arr; }
Use this little function as you like:
AClass[] array;
...
array = c(object1, object2);
I think the proper way to use **kwargs
in Python when it comes to default values is to use the dictionary method setdefault
, as given below:
class ExampleClass:
def __init__(self, **kwargs):
kwargs.setdefault('val', value1)
kwargs.setdefault('val2', value2)
In this way, if a user passes 'val' or 'val2' in the keyword args
, they will be used; otherwise, the default values that have been set will be used.
Something like this should work.
ssh [email protected] 'find -type f -name "*.pdf" -exec cp {} ./pdfsfolder \;'
Try this simpler one,
cp /home/ankur/folder/file{1,2} /home/ankur/dest
If you want to copy all the 10 files then run this command,
cp ~/Desktop/{xyz,file{1,2},next,files,which,are,not,similer} foo-bar
I got the same error because I had accidentally used <div>
instead of <canvas>
as the element on which I attempt to call getContext
.
There isn't a single answer to this question as there are too many variables, but SHA2 is not yet really cracked (see: Lifetimes of cryptographic hash functions) so it is still a good algorithm to use to store passwords in. The use of salt is good because it prevents attack from dictionary attacks or rainbow tables. Importance of a salt is that it should be unique for each password. You can use a format like [128-bit salt][512-bit password hash] when storing the hashed passwords.
The only viable way to attack is to actually calculate hashes for different possibilities of password and eventually find the right one by matching the hashes.
To give an idea about how many hashes can be done in a second, I think Bitcoin is a decent example. Bitcoin uses SHA256 and to cut it short, the more hashes you generate, the more bitcoins you get (which you can trade for real money) and as such people are motivated to use GPUs for this purpose. You can see in the hardware overview that an average graphic card that costs only $150 can calculate more than 200 million hashes/s. The longer and more complex your password is, the longer time it will take. Calculating at 200M/s, to try all possibilities for an 8 character alphanumberic (capital, lower, numbers) will take around 300 hours. The real time will most likely less if the password is something eligible or a common english word.
As such with anything security you need to look at in context. What is the attacker's motivation? What is the kind of application? Having a hash with random salt for each gives pretty good protection against cases where something like thousands of passwords are compromised.
One thing you can do is also add additional brute force protection by slowing down the hashing procedure. As you only hash passwords once, and the attacker has to do it many times, this works in your favor. The typical way to do is to take a value, hash it, take the output, hash it again and so forth for a fixed amount of iterations. You can try something like 1,000 or 10,000 iterations for example. This will make it that many times times slower for the attacker to find each password.
Don't forget to return
the mapped array , like:
lapsList() {
return this.state.laps.map((data) => {
return (
<View><Text>{data.time}</Text></View>
)
})
}
Reference for the map()
method: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map
Postgres allows the use of any existing database on the server as a template when creating a new database. I'm not sure whether pgAdmin gives you the option on the create database dialog but you should be able to execute the following in a query window if it doesn't:
CREATE DATABASE newdb WITH TEMPLATE originaldb OWNER dbuser;
Still, you may get:
ERROR: source database "originaldb" is being accessed by other users
To disconnect all other users from the database, you can use this query:
SELECT pg_terminate_backend(pg_stat_activity.pid) FROM pg_stat_activity
WHERE pg_stat_activity.datname = 'originaldb' AND pid <> pg_backend_pid();
This is the solution in Kotlin
val editText: EditText = findViewById(R.id.main_et_name)
editText.setText("This is a text.")
<div id="demo"></div>
<input type="submit" name="submit" id="submit" value="Submit" onClick="return empty()">
<script type="text/javascript">
function empty()
{
var x;
x = document.getElementById("feedbackpost").value;
if (x == "")
{
var demo = document.getElementById("demo");
demo.innerHTML =document.write='<h1>Hello member</h1>';
return false;
};
}
</script>
In Xcode 5.1
Enable Done Button
Hide Keyboard when Done is pressed
Add this method to your ViewController
-(BOOL)textFieldShouldReturn:(UITextField *)textField
{
[textField resignFirstResponder];
return YES;
}
After close examining, not 300k lines but there are around 3-4 CSS properties that you need to override:
.navbar-collapse.collapse {
display: block!important;
}
.navbar-nav>li, .navbar-nav {
float: left !important;
}
.navbar-nav.navbar-right:last-child {
margin-right: -15px !important;
}
.navbar-right {
float: right!important;
}
And with this your menu won't collapse.
EXPLANATION
The four CSS properties do the respective:
The default .collapse
property in bootstrap hides the right-side of the menu for tablets(landscape) and phones and instead a toggle button is displayed to hide/show it. Thus this property overrides the default and persistently shows those elements.
For the right-side menu to appear on the same line along with the left-side, we need the left-side to be floating left.
This property is present by default in bootstrap but not on tablet(portrait) to phone resolution. You can skip this one, it's likely to not affect your overall navbar.
This keeps the right-side menu to the right while the inner elements (li
) will follow the property 2. So we have left-side float left and right-side float right which brings them into one line.
Using File.separator made Ubuntu generate files with "\" on it's name instead of directories. Maybe I am being lazy with how I am making files(and directories) and could have avoided it, regardless, use "/" every time to avoid files with "\" on it's name
I think you are right, it's just not possible with pure CSS as far as I know (not cross-browser I mean).
Edit:
Ok I didn't like my answer very much so I puzzled a little. I might have found an interesting idea which could help out.. maybe it IS possible after all (although not the prettiest thing ever):
Edit: Tested and working in Chrome, FF and IE 8&9. . It doesn't work in IE7.
html:
<div id="img_wrap">
<img id="original_img" src="http://upload.wikimedia.org/wikipedia/en/8/81/Mdna-standard-edition-cover.jpg"/>
<div id="rescaled_img_wrap">
<img id="rescaled_img" src="http://upload.wikimedia.org/wikipedia/en/8/81/Mdna-standard-edition-cover.jpg"/>
</div>
</div>
css:
#img_wrap {
display: inline-block;
position:relative;
}
#rescaled_img_wrap {
width: 50%;
}
#original_img {
display: none;
}
#rescaled_img {
width: 100%;
height: 100%;
}
Put this code in a file called p.php
:
<?php
class yoyo{
function salt(){
}
function pepper(){
salt();
}
}
$y = new yoyo();
$y->pepper();
?>
Run it like this:
php p.php
We get error:
PHP Fatal error: Call to undefined function salt() in
/home/el/foo/p.php on line 6
Solution: use $this->salt();
instead of salt();
So do it like this instead:
<?php
class yoyo{
function salt(){
}
function pepper(){
$this->salt();
}
}
$y = new yoyo();
$y->pepper();
?>
If someone could post a link to why $this has to be used before PHP functions within classes, yeah, that would be great.
I found an easy way to do it: delete and replace
describe('Test case', () => {
const { open } = window;
beforeAll(() => {
// Delete the existing
delete window.open;
// Replace with the custom value
window.open = jest.fn();
// Works for `location` too, eg:
// window.location = { origin: 'http://localhost:3100' };
});
afterAll(() => {
// Restore original
window.open = open;
});
it('correct url is called', () => {
statementService.openStatementsReport(111);
expect(window.open).toBeCalled(); // Happy happy, joy joy
});
});
Check for a directory 'apps/autocomplete/.svn'. Move it somewhere safe (in case you need to restore it because this did not work) and see if that fixes the problem.
A quick note: Assume.assumeTrue(condition)
ignores rest of the steps but passes the test.
To fail the test, use org.junit.Assert.fail()
inside the conditional statement. Works same like Assume.assumeTrue()
but fails the test.
The function Correlate of numpy works with 2 1D arrays that you want to correlate and returns one correlation value.
First of all, you're missing a quote at the beginning but this is probably a copy/paste error.
In Python 3.x, the end=' '
part will place a space after the displayed string instead of a newline. To do the same thing in Python 2.x, you'd put a comma at the end:
print "Building internam Index for %d tile(s) ..." % len(inputTiles),
For clarity in this topic, a few points really should be made:
Sharpening images is an ill-posed problem. In other words, blurring is a lossy operation, and going back from it is in general not possible.
To sharpen single images, you need to somehow add constraints (assumptions) on what kind of image it is you want, and how it has become blurred. This is the area of natural image statistics. Approaches to do sharpening hold these statistics explicitly or implicitly in their algorithms (deep learning being the most implicitly coded ones). The common approach of up-weighting some of the levels of a DOG or Laplacian pyramid decomposition, which is the generalization of Brian Burns answer, assumes that a Gaussian blurring corrupted the image, and how the weighting is done is connected to assumptions on what was in the image to begin with.
Other sources of information can render the problem sharpening well-posed. Common such sources of information is video of a moving object, or multi-view setting. Sharpening in that setting is usually called super-resolution (which is a very bad name for it, but it has stuck in academic circles). There has been super-resolution methods in OpenCV since a long time.... although they usually dont work that well for real problems last I checked them out. I expect deep learning has produced some wonderful results here as well. Maybe someone will post in remarks on whats worthwhile out there.
str.replace(str.find(str2),str2.length(),str3);
Where
str
is the base stringstr2
is the sub string to findstr3
is the replacement substringI read & tried All Fixes But Not one worked. At last i Found that the Wamp Server Logo Is Green But Need to Be "PUT ONLINE".
So simple & a Quick Fix After Checking Your PHPMyAdmin.Cofg
& HttPD.cofg
Just Click on PUT ONLINE
For PyCharm 4
File >> Settings >> Editor >> Code Style: Right margin (columns)
suggestion: Take a look at other options in that tab, they're very helpful
I know it's kinda too late to reply to this post but since I don't see any clear answer i'd do it anyway...
you might wanna check out the MANIFEST.MF
in META-INF
on your eclipse.
then you might need to add the path of your class files like..
Class-Path: WEB-INF/classes
File.Create(string)
returns an instance of the FileStream
class. You can call the Stream.Close()
method on this object in order to close it and release resources that it's using:
var myFile = File.Create(myPath);
myFile.Close();
However, since FileStream
implements IDisposable
, you can take advantage of the using
statement (generally the preferred way of handling a situation like this). This will ensure that the stream is closed and disposed of properly when you're done with it:
using (var myFile = File.Create(myPath))
{
// interact with myFile here, it will be disposed automatically
}
If you read the docs.
$('#mydialog').dialog('isOpen')
This method returns a Boolean (true or false), not a jQuery object.
1320917972 is Unix timestamp using number of seconds since 00:00:00 UTC on January 1, 1970. You can use TimeUnit
class for unit conversion - from System.currentTimeMillis()
to seconds.
String timeStamp = String.valueOf(TimeUnit.MILLISECONDS.toSeconds(System.currentTimeMillis()));
You can also export the database and then use a program like notepad++ to replace words and then inmport aigain.
Think about protected internal
as applying two access modifier (protected
, and internal
) on the same field, property or method.
In the real world, imagine we are issuing privilege for people to visit museum:
- Everyone inside the city are allowed to visit museum (internal).
- Everyone outside of the city that their parents live here are allowed to visit museum (protected).
And we can put them together in these way:
Everyone inside the city (internal) and everyone outside of city that their parents live here (protected) are allowed to visit the museum (protected internal).
Programming world:
internal: The field is available everywhere in the assembly (project). It is like saying it is public
in its project scope (but can not being accessed outside of project scope even by those classes outside of assembly which inherit from that class). Every instance of that type can see it in that assembly (project scope).
protected: simply means that all derived classes can see it (inside or outside of assembly). For example derived classes can see the field or method inside its methods and constructors using: base.NameOfProtectedInternal
.
So, putting these two access modifier together (protected internal
), you have something that can being public inside the project, and can be seen by those which have inherited from that class inside their scope.
They can be written in the
internal protected
, and does not change the meaning, but it is convenient to write itprotected internal
.
TimeSpan span = end-start;
double totalMinutes = span.TotalMinutes;
I have another solution. I just want to test if executing a PowerShell script succeeds, because perhaps somebody might change the policy. As the argument, I just specify the path of the script to be executed.
ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.FileName = @"powershell.exe";
startInfo.Arguments = @"& 'c:\Scripts\test.ps1'";
startInfo.RedirectStandardOutput = true;
startInfo.RedirectStandardError = true;
startInfo.UseShellExecute = false;
startInfo.CreateNoWindow = true;
Process process = new Process();
process.StartInfo = startInfo;
process.Start();
string output = process.StandardOutput.ReadToEnd();
Assert.IsTrue(output.Contains("StringToBeVerifiedInAUnitTest"));
string errors = process.StandardError.ReadToEnd();
Assert.IsTrue(string.IsNullOrEmpty(errors));
With the contents of the script being:
$someVariable = "StringToBeVerifiedInAUnitTest"
$someVariable
This problem appears when we are using any third party solution, without using the handlers for the cleanup activitiy. For me this was happening for EhCache. We were using EhCache in our project for caching. And often we used to see following error in the logs
SEVERE: The web application [/products] appears to have started a thread named [products_default_cache_configuration] but has failed to stop it. This is very likely to create a memory leak.
Aug 07, 2017 11:08:36 AM org.apache.catalina.loader.WebappClassLoader clearReferencesThreads
SEVERE: The web application [/products] appears to have started a thread named [Statistics Thread-products_default_cache_configuration-1] but has failed to stop it. This is very likely to create a memory leak.
And we often noticed tomcat failing for OutOfMemory error during development where we used to do backend changes and deploy the application multiple times for reflecting our changes.
This is the fix we did
<listener>
<listener-class>
net.sf.ehcache.constructs.web.ShutdownListener
</listener-class>
</listener>
So point I am trying to make is check the documentation of the third party libraries which you are using. They should be providing some mechanisms to clean up the threads during shutdown. Which you need to use in your application. No need to re-invent the wheel unless its not provided by them. The worst case is to provide your own implementation.
Reference for EHCache Shutdown http://www.ehcache.org/documentation/2.8/operations/shutdown.html
Try:
select concat(first_name,last_name) as "Name" from test.student
or, better:
select concat(first_name," ",last_name) as "Name" from test.student
Java Escape Sequences:
\u{0000-FFFF} /* Unicode [Basic Multilingual Plane only, see below] hex value
does not handle unicode values higher than 0xFFFF (65535),
the high surrogate has to be separate: \uD852\uDF62
Four hex characters only (no variable width) */
\b /* \u0008: backspace (BS) */
\t /* \u0009: horizontal tab (HT) */
\n /* \u000a: linefeed (LF) */
\f /* \u000c: form feed (FF) */
\r /* \u000d: carriage return (CR) */
\" /* \u0022: double quote (") */
\' /* \u0027: single quote (') */
\\ /* \u005c: backslash (\) */
\{0-377} /* \u0000 to \u00ff: from octal value
1 to 3 octal digits (variable width) */
The Basic Multilingual Plane is the unicode values from 0x0000 - 0xFFFF (0 - 65535). Additional planes can only be specified in Java by multiple characters: the egyptian heiroglyph A054 (laying down dude) is U+1303F
/ 𓀿
and would have to be broken into "\uD80C\uDC3F"
(UTF-16) for Java strings. Some other languages support higher planes with "\U0001303F"
.
You can use continue
if condition:
continue
else:
#do something
This will remove the folders and files and leave the folder behind.
pushd "%pathtofolder%" && (rd /s /q "%pathtofolder%" 2>nul & popd)
Open application if it is exist, or open Play Store application for install it:
private void open() {
openApplication(getActivity(), "com.app.package.here");
}
public void openApplication(Context context, String packageN) {
Intent i = context.getPackageManager().getLaunchIntentForPackage(packageN);
if (i != null) {
i.addCategory(Intent.CATEGORY_LAUNCHER);
context.startActivity(i);
} else {
try {
context.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=" + packageN)));
}
catch (android.content.ActivityNotFoundException anfe) {
context.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("http://play.google.com/store/apps/details?id=" + packageN)));
}
}
}
Hope this helps
View view="some view instance";
view.setDrawingCacheEnabled(true);
Bitmap bitmap=view.getDrawingCache();
view.setDrawingCacheEnabled(false);
Update
getDrawingCache()
method is deprecated in API level 28. So look for other alternative for API level > 28.
def valid = pointAddress.findAll { a ->
validPointTypes.any { a.contains(it) }
}
Should do it
first, it's easy to convert a Date to an Instant
Instant timestamp = new Date().toInstant();
Then, you can convert the Instant to any date api in jdk 8 using ofInstant() method:
LocalDateTime date = LocalDateTime.ofInstant(timestamp, ZoneId.systemDefault());
Currently (Swift 2.1) you can check it using 3 ways:
Using '?' answered by @Sulthan
And using as?
operator:
if let delegateMe = self.delegate as? YourCustomViewController
{
delegateMe.onSuccess()
}
Basically it depends on what you are trying to achieve:
If you have no code using it now, I'd suggest continuing that. If your codebase uses it, continue that.
The biggest thing about coding style is consistency. If you have nothing to be consistent with, then the language vendor's recommendations are likely a good place to start.
Make simple:
@GetMapping("/health")
public ResponseEntity<String> healthCheck() {
LOG.info("REST request health check");
return new ResponseEntity<>("{\"status\" : \"UP\"}", HttpStatus.OK);
}
Rails 4:
If you want to use both not equal and equal, you can use:
user_id = 4
group_id = 27
GroupUser.where(group_id: group_id).where.not(user_id: user_id)
If you want to use a variety of operators (ie. >
, <
), at some point you may want to switch notations to the following:
GroupUser.where("group_id > ? AND user_id != ?", group_id, user_id)
Here is maybe a more elegant and flexible solution with 'resolve' configuration property and 'promises' enabling eventual data loading on routing and routing rules depending on data.
You specify a function in 'resolve' in routing config and in the function load and check data, do all redirects. If you need to load data, you return a promise, if you need to do redirect - reject promise before that. All details can be found on $routerProvider and $q documentation pages.
'use strict';
var app = angular.module('app', [])
.config(['$routeProvider', function($routeProvider) {
$routeProvider
.when('/', {
templateUrl: "login.html",
controller: LoginController
})
.when('/private', {
templateUrl: "private.html",
controller: PrivateController,
resolve: {
factory: checkRouting
}
})
.when('/private/anotherpage', {
templateUrl:"another-private.html",
controller: AnotherPriveController,
resolve: {
factory: checkRouting
}
})
.otherwise({ redirectTo: '/' });
}]);
var checkRouting= function ($q, $rootScope, $location) {
if ($rootScope.userProfile) {
return true;
} else {
var deferred = $q.defer();
$http.post("/loadUserProfile", { userToken: "blah" })
.success(function (response) {
$rootScope.userProfile = response.userProfile;
deferred.resolve(true);
})
.error(function () {
deferred.reject();
$location.path("/");
});
return deferred.promise;
}
};
For russian-speaking folks there is a post on habr "??????? ????????? ???????? ? AngularJS."
Use a JOIN
in the DELETE
statement.
DELETE p, pa
FROM pets p
JOIN pets_activities pa ON pa.id = p.pet_id
WHERE p.order > :order
AND p.pet_id = :pet_id
Alternatively you can use...
DELETE pa
FROM pets_activities pa
JOIN pets p ON pa.id = p.pet_id
WHERE p.order > :order
AND p.pet_id = :pet_id
...to delete only from pets_activities
See this.
For single table deletes, yet with referential integrity, there are other ways of doing with EXISTS
, NOT EXISTS
, IN
, NOT IN
and etc. But the one above where you specify from which tables to delete with an alias before the FROM
clause can get you out of a few pretty tight spots more easily. I tend to reach out to an EXISTS
in 99% of the cases and then there is the 1% where this MySQL syntax takes the day.
Something like this that i answer in another question
public class Snippet {
public static void main(String[] args) {
int [][]lst = new int[10][10];
for (int[] arr : lst) {
System.out.println(Arrays.toString(arr));
}
}
}
thanks to @usertatha with some modification
function isUUID ( uuid ) {
let s = "" + uuid;
s = s.match('^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$');
if (s === null) {
return false;
}
return true;
}
You can use the JavaScript String concat() Method,
var str1 = "Hello ";
var str2 = "world!";
var res = str1.concat(str2); //will return "Hello world!"
Its syntax is:
string.concat(string1, string2, ..., stringX)
You can use the CSS3 Linear Gradient property along with your background-image like this:
#landing-wrapper {
display:table;
width:100%;
background: linear-gradient( rgba(0, 0, 0, 0.5), rgba(0, 0, 0, 0.5) ), url('landingpagepic.jpg');
background-position:center top;
height:350px;
}
Here's a demo:
#landing-wrapper {_x000D_
display: table;_x000D_
width: 100%;_x000D_
background: linear-gradient(rgba(0, 0, 0, 0.5), rgba(0, 0, 0, 0.5)), url('http://placehold.it/350x150');_x000D_
background-position: center top;_x000D_
height: 350px;_x000D_
color: white;_x000D_
}
_x000D_
<div id="landing-wrapper">Lorem ipsum dolor ismet.</div>
_x000D_
Yes you can start with the Wikipedia article explaining the Big O notation, which in a nutshell is a way of describing the "efficiency" (upper bound of complexity) of different type of algorithms. Or you can look at an earlier answer where this is explained in simple english
As you have found out there is no such thing as a single "local IP address". Here's how to find out the local address that can be sent out to a specific host.
Use sys.getsizeof() if you DON'T want to include sizes of linked (nested) objects.
However, if you want to count sub-objects nested in lists, dicts, sets, tuples - and usually THIS is what you're looking for - use the recursive deep sizeof() function as shown below:
import sys
def sizeof(obj):
size = sys.getsizeof(obj)
if isinstance(obj, dict): return size + sum(map(sizeof, obj.keys())) + sum(map(sizeof, obj.values()))
if isinstance(obj, (list, tuple, set, frozenset)): return size + sum(map(sizeof, obj))
return size
You can also find this function in the nifty toolbox, together with many other useful one-liners:
If response is in json and not a string then
alert(response.id);
or
alert(response['id']);
otherwise
var response = JSON.parse('{"id":"2231f87c-a62c-4c2c-8f5d-b76d11942301"}');
response.id ; //# => 2231f87c-a62c-4c2c-8f5d-b76d11942301
The original post was asking how to center the collapsed navbar. To center elements on the normal navbar, try this:
.navbar-nav {
float:none;
margin:0 auto;
display: block;
text-align: center;
}
.navbar-nav > li {
display: inline-block;
float:none;
}
I am on Eclipse Neon, and after following the above steps, it still didnt work. import lombok.Data; was not being recognized.
After about an hour of looking around, i switched the version to 1.16.14 and it worked.
Now my thought is, whether the 1 hour spent will be a good investment for long term :-)
Programming to Interfaces is awesome, it promotes loose coupling. As @lassevk mentioned, Inversion of Control is a great use of this.
In addition, look into SOLID principals. here is a video series
It goes through a hard coded (strongly coupled example) then looks at interfaces, finally progressing to a IoC/DI tool (NInject)
You can't use a function to insert data into a base table. Functions return data. This is listed as the very first limitation in the documentation:
User-defined functions cannot be used to perform actions that modify the database state.
"Modify the database state" includes changing any data in the database (though a table variable is an obvious exception the OP wouldn't have cared about 3 years ago - this table variable only lives for the duration of the function call and does not affect the underlying tables in any way).
You should be using a stored procedure, not a function.
the query() method can do that very intuitively. Express your condition in a string to be evaluated like the following example :
df = df.query("columnNameA <= @x or columnNameB == @y")
with x and y are declared variables which you can refer to with @
UIImage* image3 = [UIImage imageNamed:@"back_button.png"];
CGRect frameimg = CGRectMake(15,5, 25,25);
UIButton *someButton = [[UIButton alloc] initWithFrame:frameimg];
[someButton setBackgroundImage:image3 forState:UIControlStateNormal];
[someButton addTarget:self action:@selector(Back_btn:)
forControlEvents:UIControlEventTouchUpInside];
[someButton setShowsTouchWhenHighlighted:YES];
UIBarButtonItem *mailbutton =[[UIBarButtonItem alloc] initWithCustomView:someButton];
self.navigationItem.leftBarButtonItem =mailbutton;
[someButton release];
///// called event
-(IBAction)Back_btn:(id)sender
{
//Your code here
}
SWIFT:
var image3 = UIImage(named: "back_button.png")
var frameimg = CGRect(x: 15, y: 5, width: 25, height: 25)
var someButton = UIButton(frame: frameimg)
someButton.setBackgroundImage(image3, for: .normal)
someButton.addTarget(self, action: Selector("Back_btn:"), for: .touchUpInside)
someButton.showsTouchWhenHighlighted = true
var mailbutton = UIBarButtonItem(customView: someButton)
navigationItem?.leftBarButtonItem = mailbutton
func back_btn(_ sender: Any) {
//Your code here
}
You can use this regex to get the yyyy-MM-dd format:
((?:19|20)\\d\\d)-(0?[1-9]|1[012])-([12][0-9]|3[01]|0?[1-9])
You can find example for date validation: How to validate date with regular expression.
You can use android:background="#DC143C"
, or any other RGB values for your color. I have no problem using it this way, as stated here
Since no context was given to this question and you are a relatively new user, I want to make sure that you are aware that you can have a list of lists. It's not the same as array of list and you asked specifically for that, but nevertheless:
List<List<int>> myList = new List<List<int>>();
you can initialize them through collection initializers like so:
List<List<int>> myList = new List<List<int>>(){{1,2,3},{4,5,6},{7,8,9}};
Actually if you are waiting for response from a server it should be done programatically. You may create a progress dialog and dismiss it, but then again that is not "the android way".
Currently the recommended method is to use a DialogFragment :
public class MySpinnerDialog extends DialogFragment {
public MySpinnerDialog() {
// use empty constructors. If something is needed use onCreate's
}
@Override
public Dialog onCreateDialog(final Bundle savedInstanceState) {
_dialog = new ProgressDialog(getActivity());
this.setStyle(STYLE_NO_TITLE, getTheme()); // You can use styles or inflate a view
_dialog.setMessage("Spinning.."); // set your messages if not inflated from XML
_dialog.setCancelable(false);
return _dialog;
}
}
Then in your activity you set your Fragment manager and show the dialog once the wait for the server started:
FragmentManager fm = getSupportFragmentManager();
MySpinnerDialog myInstance = new MySpinnerDialog();
}
myInstance.show(fm, "some_tag");
Once your server has responded complete you will dismiss it:
myInstance.dismiss()
Remember that the progressdialog is a spinner or a progressbar depending on the attributes, read more on the api guide
Here you go:
<html>_x000D_
<head>_x000D_
<title>Cols</title>_x000D_
<style>_x000D_
#left {_x000D_
width: 200px;_x000D_
float: left;_x000D_
}_x000D_
#right {_x000D_
margin-left: 200px;_x000D_
/* Change this to whatever the width of your left column is*/_x000D_
}_x000D_
.clear {_x000D_
clear: both;_x000D_
}_x000D_
</style>_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
<div id="container">_x000D_
<div id="left">_x000D_
Hello_x000D_
</div>_x000D_
<div id="right">_x000D_
<div style="background-color: red; height: 10px;">Hello</div>_x000D_
</div>_x000D_
<div class="clear"></div>_x000D_
</div>_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
See it in action here: http://jsfiddle.net/FVLMX/
If by "going crazy" you mean that each window keeps stealing focus from the other, TopMost will not solve the problem.
Instead, try:
CalledForm.Owner = CallerForm;
CalledForm.Show();
This will show the 'child' form without it stealing focus. The child form will also stay on top of its parent even if the parent is activated or focused. This code only works easily if you've created an instance of the child form from within the owner form. Otherwise, you might have to set the owner using the API.
The scanner can also use delimiters other than whitespace.
Easy example from Scanner API:
String input = "1 fish 2 fish red fish blue fish";
// \\s* means 0 or more repetitions of any whitespace character
// fish is the pattern to find
Scanner s = new Scanner(input).useDelimiter("\\s*fish\\s*");
System.out.println(s.nextInt()); // prints: 1
System.out.println(s.nextInt()); // prints: 2
System.out.println(s.next()); // prints: red
System.out.println(s.next()); // prints: blue
// don't forget to close the scanner!!
s.close();
The point is to understand the regular expressions (regex
) inside the Scanner::useDelimiter
. Find an useDelimiter
tutorial here.
To start with regular expressions here you can find a nice tutorial.
abc… Letters
123… Digits
\d Any Digit
\D Any Non-digit character
. Any Character
\. Period
[abc] Only a, b, or c
[^abc] Not a, b, nor c
[a-z] Characters a to z
[0-9] Numbers 0 to 9
\w Any Alphanumeric character
\W Any Non-alphanumeric character
{m} m Repetitions
{m,n} m to n Repetitions
* Zero or more repetitions
+ One or more repetitions
? Optional character
\s Any Whitespace
\S Any Non-whitespace character
^…$ Starts and ends
(…) Capture Group
(a(bc)) Capture Sub-group
(.*) Capture all
(ab|cd) Matches ab or cd
function NewClass() {
var self = this;
BaseClass.call(self); // Set base class
var baseModify = self.modify; // Get base function
self.modify = function () {
// Override code here
baseModify();
};
}
Hello I had this problem on mac, and what I did was
installed globally and prefix with global path
sudo npm install grunt -g --prefix=/usr/local
now
$ which grunt
should out put
/usr/local/bin/grunt
Cheers