NOLOCK is often exploited as a magic way to speed up database reads, but I try to avoid using it whever possible.
The result set can contain rows that have not yet been committed, that are often later rolled back.
An error or Result set can be empty, be missing rows or display the same row multiple times.
This is because other transactions are moving data at the same time you're reading it.
READ COMMITTED adds an additional issue where data is corrupted within a single column where multiple users change the same cell simultaneously.
Expanding on the accepted answer, if the input is:
1,NYC
2,ABQ
...
you will still be able to apply the same logic, like this:
#include <fstream>
std::ifstream infile("thefile.txt");
if (infile.is_open()) {
int number;
std::string str;
char c;
while (infile >> number >> c >> str && c == ',')
std::cout << number << " " << str << "\n";
}
infile.close();
Seeing that it appears you are running using the SQL syntax, try with the correct wild card.
SELECT * FROM someTable WHERE (someTable.Field NOT LIKE '%RISK%') AND (someTable.Field NOT LIKE '%Blah%') AND someTable.SomeOtherField <> 4;
Using T-SQL:
My job is executing stored procedure. You can easy change @command
to run your sql.
EXEC msdb.dbo.sp_add_job
@job_name = N'MakeDailyJob',
@enabled = 1,
@description = N'Procedure execution every day' ;
EXEC msdb.dbo.sp_add_jobstep
@job_name = N'MakeDailyJob',
@step_name = N'Run Procedure',
@subsystem = N'TSQL',
@command = 'exec BackupFromConfig';
EXEC msdb.dbo.sp_add_schedule
@schedule_name = N'Everyday schedule',
@freq_type = 4, -- daily start
@freq_interval = 1,
@active_start_time = '230000' ; -- start time 23:00:00
EXEC msdb.dbo.sp_attach_schedule
@job_name = N'MakeDailyJob',
@schedule_name = N'Everyday schedule' ;
EXEC msdb.dbo.sp_add_jobserver
@job_name = N'MakeDailyJob',
@server_name = @@servername ;
Assuming little endianness and sizeof(char) == 1, you could do that (something like this was suggested by MikeBrom).
char* txt = "B1";
int tst = *(int*)txt;
if ((tst & 0x00FFFFFF) == '1B')
printf("B1!\n");
It could be generalized for BE case.
javadocs show that the parse method is overloaded.
Create a StringStream or InputSource using your string XML and you should be set.
We should always go for equals() method for comparison for two integers.Its the recommended practice.
If we compare two integers using == that would work for certain range of integer values (Integer from -128 to 127) due to JVM's internal optimisation.
Please see examples:
Case 1:
Integer a = 100; Integer b = 100;
if (a == b) { System.out.println("a and b are equal"); } else { System.out.println("a and b are not equal"); }
In above case JVM uses value of a and b from cached pool and return the same object instance(therefore memory address) of integer object and we get both are equal.Its an optimisation JVM does for certain range values.
Case 2: In this case, a and b are not equal because it does not come with the range from -128 to 127.
Integer a = 220; Integer b = 220;
if (a == b) { System.out.println("a and b are equal"); } else { System.out.println("a and b are not equal"); }
Proper way:
Integer a = 200;
Integer b = 200;
System.out.println("a == b? " + a.equals(b)); // true
I hope this helps.
I know this question is about Linux, but in case someone stumbles on this problem on Mac like I did here is the solution for that. I had the exact same problem on Mac because ffmpeg
is not installed by default apparently, and so I could solve it using:
brew install yasm
brew install ffmpeg
Just loop over the elements in your array.
Ex:
for(int i=0; numOfElements > i; i++)
{
outputWriter.write(array[i]);
}
//finish up down here
You should use the ARG
directive in your Dockerfile which is meant for this purpose.
The
ARG
instruction defines a variable that users can pass at build-time to the builder with the docker build command using the--build-arg <varname>=<value>
flag.
So your Dockerfile will have this line:
ARG request_domain
or if you'd prefer a default value:
ARG request_domain=127.0.0.1
Now you can reference this variable inside your Dockerfile:
ENV request_domain=$request_domain
then you will build your container like so:
$ docker build --build-arg request_domain=mydomain Dockerfile
Note 1: Your image will not build if you have referenced an ARG
in your Dockerfile but excluded it in --build-arg
.
Note 2: If a user specifies a build argument that was not defined in the Dockerfile, the build outputs a warning:
[Warning] One or more build-args [foo] were not consumed.
I agree with Joachim that you should replace the hyphen with NULL
. But, if you really do want a hyphen, convert the date to a string:
(CASE WHEN B.[STAT] IS NULL
THEN convert(varchar(10), C.[EVENT DATE]+10, 121)
ELSE '-'
END) AS [DATE]
Also, the distinct
is unnecessary in your select
statement. The group by
already does this for you.
get
takes a second optional value. If the specified key does not exist in your dictionary, then this value will be returned.
dictionary = {"Name": "Harry", "Age": 17}
dictionary.get('Year', 'No available data')
>> 'No available data'
If you do not give the second parameter, None
will be returned.
If you use indexing as in dictionary['Year']
, nonexistent keys will raise KeyError
.
var payeeCountry = document.getElementById( "payeeCountry" );
alert( payeeCountry.options[ yourSelect.selectedIndex ].value );
Please refer to this for the example .The main point is to use the groupProperty()
, and the related aggregate functions provided by the Projections class.
For example :
SELECT column_name, max(column_name) , min (column_name) , count(column_name)
FROM table_name
WHERE column_name > xxxxx
GROUP BY column_name
Its equivalent criteria object is :
List result = session.createCriteria(SomeTable.class)
.add(Restrictions.ge("someColumn", xxxxx))
.setProjection(Projections.projectionList()
.add(Projections.groupProperty("someColumn"))
.add(Projections.max("someColumn"))
.add(Projections.min("someColumn"))
.add(Projections.count("someColumn"))
).list();
Here's what I get.
I'm using Visual Studio Code and its Terminal to execute the 'npm' commands.
Visual Studio Code (not as administrator)
PS g:\labs\myproject> npm install bootstrap@3
Results in scandir and/or permission errors.
Visual Studio Code (as Administrator)
Run this command after I've run something like 'ng serve'
PS g:\labs\myproject> npm install bootstrap@3
Results in scandir and/or permission errors.
Visual Studio Code (as Administrator - closing and opening the IDE)
If I have already executed other commands that would impact node modules I decided to try closing Visual Studio Code first, opening it up as Administrator then running the command:
PS g:\labs\myproject> npm install bootstrap@3
Result I get then is: + [email protected]
added 115 packages and updated 1 package in 24.685s
This is not a permanent solution since I don't want to continue closing down VS Code every time I want to execute an npm command, but it did resolve the issue to a point.
Your activity doesn't extend FragmentActivity from the support library, therefore the method is not present in the superclass
If you are targeting api 11 or above, you could use Activity.getFragmentManager instead.
Here's a cool way to do custom wildcard expression validations in a form (from: Advanced form validation with AngularJS and filters):
<form novalidate="">
<input type="text" id="name" name="name" ng-model="newPerson.name"
ensure-expression="(persons | filter:{name: newPerson.name}:true).length !== 1">
<!-- or in your case:-->
<input type="text" id="fruitName" name="fruitName" ng-model="data.fruitName"
ensure-expression="(blacklist | filter:{fruitName: data.fruitName}:true).length !== 1">
</form>
app.directive('ensureExpression', ['$http', '$parse', function($http, $parse) {
return {
require: 'ngModel',
link: function(scope, ele, attrs, ngModelController) {
scope.$watch(attrs.ngModel, function(value) {
var booleanResult = $parse(attrs.ensureExpression)(scope);
ngModelController.$setValidity('expression', booleanResult);
});
}
};
}]);
jsFiddle demo (supports expression naming and multiple expressions)
It's similar to ui-validate
, but you don't need a scope specific validation function (this works generically) and ofcourse you don't need ui.utils this way.
/^[\pL\pM\p{Zs}.-]+$/u
Explanation:
\pL
- matches any kind of letter from any language\pM
- atches a character intended to be combined with another character (e.g. accents, umlauts, enclosing boxes, etc.)\p{Zs}
- matches a whitespace character that is invisible, but does take up spaceu
- Pattern and subject strings are treated as UTF-8Unlike other proposed regex (such as [A-Za-zÀ-ÖØ-öø-ÿ]
), this will work with all language specific characters, e.g. Šš
is matched by this rule, but not matched by others on this page.
Unfortunately, natively JavaScript does not support these classes. However, you can use xregexp
, e.g.
const XRegExp = require('xregexp');
const isInputRealHumanName = (input: string): boolean => {
return XRegExp('^[\\pL\\pM-]+ [\\pL\\pM-]+$', 'u').test(input);
};
Following blog given good chained Comparator example
http://www.codejava.net/java-core/collections/sorting-a-list-by-multiple-attributes-example
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
/**
* This is a chained comparator that is used to sort a list by multiple
* attributes by chaining a sequence of comparators of individual fields
* together.
*
*/
public class EmployeeChainedComparator implements Comparator<Employee> {
private List<Comparator<Employee>> listComparators;
@SafeVarargs
public EmployeeChainedComparator(Comparator<Employee>... comparators) {
this.listComparators = Arrays.asList(comparators);
}
@Override
public int compare(Employee emp1, Employee emp2) {
for (Comparator<Employee> comparator : listComparators) {
int result = comparator.compare(emp1, emp2);
if (result != 0) {
return result;
}
}
return 0;
}
}
Calling Comparator:
Collections.sort(listEmployees, new EmployeeChainedComparator(
new EmployeeJobTitleComparator(),
new EmployeeAgeComparator(),
new EmployeeSalaryComparator())
);
There are two methods to get the mod time, os.path.getmtime() or os.stat(), but the ctime is not reliable cross-platform (see below).
getmtime(path)
Return the time of last modification of path. The return value is a number giving the
number of seconds since the epoch (see the time module). Raise os.error if the file does
not exist or is inaccessible. New in version 1.5.2. Changed in version 2.3: If
os.stat_float_times() returns True, the result is a floating point number.
stat(path)
Perform a stat() system call on the given path. The return value is an object whose
attributes correspond to the members of the stat structure, namely: st_mode (protection
bits), st_ino (inode number), st_dev (device), st_nlink (number of hard links), st_uid
(user ID of owner), st_gid (group ID of owner), st_size (size of file, in bytes),
st_atime (time of most recent access), st_mtime (time of most recent content
modification), st_ctime (platform dependent; time of most recent metadata change on Unix, or the time of creation on Windows):
>>> import os
>>> statinfo = os.stat('somefile.txt')
>>> statinfo
(33188, 422511L, 769L, 1, 1032, 100, 926L, 1105022698,1105022732, 1105022732)
>>> statinfo.st_size
926L
>>>
In the above example you would use statinfo.st_mtime or statinfo.st_ctime to get the mtime and ctime, respectively.
If you can, I strongly suggest you tar
and bzip
(or gzip
, whatever floats your boat) the directory on the remote machine—for a directory of any significant size, the bandwidth savings will probably be worth the time to zip/unzip.
If you have a list of columns you want to concatenate and maybe you'd like to use some separator, here's what you can do
def concat_columns(df, cols_to_concat, new_col_name, sep=" "):
df[new_col_name] = df[cols_to_concat[0]]
for col in cols_to_concat[1:]:
df[new_col_name] = df[new_col_name].astype(str) + sep + df[col].astype(str)
This should be faster than apply
and takes an arbitrary number of columns to concatenate.
The element that you posted looks like it's just copy-pasted from the Google Maps embed feature.
If you'd like to drop markers for the locations that you have, you'll need to write some JavaScript to do so. I'm learning how to do this as well.
Check out the following: https://developers.google.com/maps/documentation/javascript/overlays
It has several examples and code samples that can be easily re-used and adapted to fit your current problem.
As noted in several blogs, strtotime() solves the "+1 month" ("next month") issue on days that do not exist in the subsequent month differently than other implementations like for example MySQL.
$dt = date("Y-m-d");
echo date( "Y-m-d", strtotime( "$dt +1 day" ) ); // PHP: 2009-03-04
echo date( "Y-m-d", strtotime( "2009-01-31 +2 month" ) ); // PHP: 2009-03-31
Simple server reboot solved the problem for me. Try hard reboot , if dont work after soft reboot.
Assuming that onMove
is an event handler, it is likely that its context is something other than the instance of MyContainer
, i.e. this
points to something different.
You can manually bind the context of the function during the construction of the instance via Function.bind
:
class MyContainer extends Component {
constructor(props) {
super(props);
this.onMove = this.onMove.bind(this);
this.test = "this is a test";
}
onMove() {
console.log(this.test);
}
}
Also, test !== testVariable
.
You can accomplish this (if I understand what you are trying to do) using dynamic SQL.
The trick is that you need to create a string containing the SQL statement. That's because the tablename has to specified in the actual SQL text, when you execute the statement. The table references and column references can't be supplied as parameters, those have to appear in the SQL text.
So you can use something like this approach:
SET @stmt = 'INSERT INTO @tmpTbl1 SELECT ' + @KeyValue
+ ' AS fld1 FROM tbl' + @KeyValue
EXEC (@stmt)
First, we create a SQL statement as a string. Given a @KeyValue of 'Foo', that would create a string containing:
'INSERT INTO @tmpTbl1 SELECT Foo AS fld1 FROM tblFoo'
At this point, it's just a string. But we can execute the contents of the string, as a dynamic SQL statement, using EXECUTE
(or EXEC
for short).
The old-school sp_executesql
procedure is an alternative to EXEC, another way to execute dymamic SQL, which also allows you to pass parameters, rather than specifying all values as literals in the text of the statement.
FOLLOWUP
EBarr points out (correctly and importantly) that this approach is susceptible to SQL Injection.
Consider what would happen if @KeyValue
contained the string:
'1 AS foo; DROP TABLE students; -- '
The string we would produce as a SQL statement would be:
'INSERT INTO @tmpTbl1 SELECT 1 AS foo; DROP TABLE students; -- AS fld1 ...'
When we EXECUTE that string as a SQL statement:
INSERT INTO @tmpTbl1 SELECT 1 AS foo;
DROP TABLE students;
-- AS fld1 FROM tbl1 AS foo; DROP ...
And it's not just a DROP TABLE that could be injected. Any SQL could be injected, and it might be much more subtle and even more nefarious. (The first attacks can be attempts to retreive information about tables and columns, followed by attempts to retrieve data (email addresses, account numbers, etc.)
One way to address this vulnerability is to validate the contents of @KeyValue, say it should contain only alphabetic and numeric characters (e.g. check for any characters not in those ranges using LIKE '%[^A-Za-z0-9]%'
. If an illegal character is found, then reject the value, and exit without executing any SQL.
A2 Hosting permits node.js on their shared hosting accounts. I can vouch that I've had a positive experience with them.
Here are instructions in their KnowledgeBase for installing node.js using Apache/LiteSpeed as a reverse proxy: https://www.a2hosting.com/kb/installable-applications/manual-installations/installing-node-js-on-managed-hosting-accounts . It takes about 30 minutes to set up the configuration, and it'll work with npm, Express, MySQL, etc.
See a2hosting.com.
See section 5.4 and 15.18 of the Java Language specification:
String conversion applies only to the operands of the binary + operator when one of the arguments is a String. In this single special case, the other argument to the + is converted to a String, and a new String which is the concatenation of the two strings is the result of the +. String conversion is specified in detail within the description of the string concatenation + operator.
and
If only one operand expression is of type String, then string conversion is performed on the other operand to produce a string at run time. The result is a reference to a String object (newly created, unless the expression is a compile-time constant expression (§15.28))that is the concatenation of the two operand strings. The characters of the left-hand operand precede the characters of the right-hand operand in the newly created string. If an operand of type String is null, then the string "null" is used instead of that operand.
Best practice: one form per product is definitely the way to go.
Benefits:
In your specific situation
If you only ever intend to have one form element, in this case a submit
button, one form for all should work just fine.
My recommendation Do one form per product, and change your markup to something like:
<form method="post" action="">
<input type="hidden" name="product_id" value="123">
<button type="submit" name="action" value="add_to_cart">Add to Cart</button>
</form>
This will give you a much cleaner and usable POST
. No parsing. And it will allow you to add more parameters in the future (size, color, quantity, etc).
Note: There's no technical benefit to using
<button>
vs.<input>
, but as a programmer I find it cooler to work withaction=='add_to_cart'
thanaction=='Add to Cart'
. Besides, I hate mixing presentation with logic. If one day you decide that it makes more sense for the button to say "Add" or if you want to use different languages, you could do so freely without having to worry about your back-end code.
Good working example here: http://jsfiddle.net/MrTest/t4NXD/62/
Plus:
fade in / fade out
animation:hover
Tested and working!
In terms of how len()
actually works, this is its C implementation:
static PyObject *
builtin_len(PyObject *module, PyObject *obj)
/*[clinic end generated code: output=fa7a270d314dfb6c input=bc55598da9e9c9b5]*/
{
Py_ssize_t res;
res = PyObject_Size(obj);
if (res < 0) {
assert(PyErr_Occurred());
return NULL;
}
return PyLong_FromSsize_t(res);
}
Py_ssize_t
is the maximum length that the object can have. PyObject_Size()
is a function that returns the size of an object. If it cannot determine the size of an object, it returns -1. In that case, this code block will be executed:
if (res < 0) {
assert(PyErr_Occurred());
return NULL;
}
And an exception is raised as a result. Otherwise, this code block will be executed:
return PyLong_FromSsize_t(res);
res
which is a C
integer, is converted into a Python int
(which is still called a "Long" in the C code because Python 2 had two types for storing integers) and returned.
OCR which stands for Optical Character Recognition is a computer vision technique used to identify the different types of handwritten digits that are used in common mathematics. To perform OCR in OpenCV we will use the KNN algorithm which detects the nearest k neighbors of a particular data point and then classifies that data point based on the class type detected for n neighbors.
Data Used
This data contains 5000 handwritten digits where there are 500 digits for every type of digit. Each digit is of 20×20 pixel dimensions. We will split the data such that 250 digits are for training and 250 digits are for testing for every class.
Below is the implementation.
import numpy as np import cv2 # Read the image image = cv2.imread( 'digits.png' ) # gray scale conversion gray_img = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) # We will divide the image # into 5000 small dimensions # of size 20x20 divisions = list (np.hsplit(i, 100 ) for i in np.vsplit(gray_img, 50 )) # Convert into Numpy array # of size (50,100,20,20) NP_array = np.array(divisions) # Preparing train_data # and test_data. # Size will be (2500,20x20) train_data = NP_array[:,: 50 ].reshape( - 1 , 400 ).astype(np.float32) # Size will be (2500,20x20) test_data = NP_array[:, 50 : 100 ].reshape( - 1 , 400 ).astype(np.float32) # Create 10 different labels # for each type of digit k = np.arange( 10 ) train_labels = np.repeat(k, 250 )[:,np.newaxis] test_labels = np.repeat(k, 250 )[:,np.newaxis] # Initiate kNN classifier knn = cv2.ml.KNearest_create() # perform training of data knn.train(train_data, cv2.ml.ROW_SAMPLE, train_labels) # obtain the output from the # classifier by specifying the # number of neighbors. ret, output ,neighbours, distance = knn.findNearest(test_data, k = 3 ) # Check the performance and # accuracy of the classifier. # Compare the output with test_labels # to find out how many are wrong. matched = output = = test_labels correct_OP = np.count_nonzero(matched) #Calculate the accuracy. accuracy = (correct_OP * 100.0 ) / (output.size) # Display accuracy. print (accuracy) |
Output
91.64
Well, I decided to workout myself on my question to solve the above problem. What I wanted is to implement a simple OCR using KNearest or SVM features in OpenCV. And below is what I did and how. (it is just for learning how to use KNearest for simple OCR purposes).
1) My first question was about letter_recognition.data
file that comes with OpenCV samples. I wanted to know what is inside that file.
It contains a letter, along with 16 features of that letter.
And this SOF
helped me to find it. These 16 features are explained in the paper Letter Recognition Using Holland-Style Adaptive Classifiers
.
(Although I didn't understand some of the features at the end)
2) Since I knew, without understanding all those features, it is difficult to do that method. I tried some other papers, but all were a little difficult for a beginner.
So I just decided to take all the pixel values as my features. (I was not worried about accuracy or performance, I just wanted it to work, at least with the least accuracy)
I took the below image for my training data:
(I know the amount of training data is less. But, since all letters are of the same font and size, I decided to try on this).
To prepare the data for training, I made a small code in OpenCV. It does the following things:
key press manually
. This time we press the digit key ourselves corresponding to the letter in the box..txt
files.At the end of the manual classification of digits, all the digits in the training data (train.png
) are labeled manually by ourselves, image will look like below:
Below is the code I used for the above purpose (of course, not so clean):
import sys
import numpy as np
import cv2
im = cv2.imread('pitrain.png')
im3 = im.copy()
gray = cv2.cvtColor(im,cv2.COLOR_BGR2GRAY)
blur = cv2.GaussianBlur(gray,(5,5),0)
thresh = cv2.adaptiveThreshold(blur,255,1,1,11,2)
################# Now finding Contours ###################
contours,hierarchy = cv2.findContours(thresh,cv2.RETR_LIST,cv2.CHAIN_APPROX_SIMPLE)
samples = np.empty((0,100))
responses = []
keys = [i for i in range(48,58)]
for cnt in contours:
if cv2.contourArea(cnt)>50:
[x,y,w,h] = cv2.boundingRect(cnt)
if h>28:
cv2.rectangle(im,(x,y),(x+w,y+h),(0,0,255),2)
roi = thresh[y:y+h,x:x+w]
roismall = cv2.resize(roi,(10,10))
cv2.imshow('norm',im)
key = cv2.waitKey(0)
if key == 27: # (escape to quit)
sys.exit()
elif key in keys:
responses.append(int(chr(key)))
sample = roismall.reshape((1,100))
samples = np.append(samples,sample,0)
responses = np.array(responses,np.float32)
responses = responses.reshape((responses.size,1))
print "training complete"
np.savetxt('generalsamples.data',samples)
np.savetxt('generalresponses.data',responses)
Now we enter in to training and testing part.
For the testing part, I used the below image, which has the same type of letters I used for the training phase.
For training we do as follows:
.txt
files we already saved earlierFor testing purposes, we do as follows:
I included last two steps (training and testing) in single code below:
import cv2
import numpy as np
####### training part ###############
samples = np.loadtxt('generalsamples.data',np.float32)
responses = np.loadtxt('generalresponses.data',np.float32)
responses = responses.reshape((responses.size,1))
model = cv2.KNearest()
model.train(samples,responses)
############################# testing part #########################
im = cv2.imread('pi.png')
out = np.zeros(im.shape,np.uint8)
gray = cv2.cvtColor(im,cv2.COLOR_BGR2GRAY)
thresh = cv2.adaptiveThreshold(gray,255,1,1,11,2)
contours,hierarchy = cv2.findContours(thresh,cv2.RETR_LIST,cv2.CHAIN_APPROX_SIMPLE)
for cnt in contours:
if cv2.contourArea(cnt)>50:
[x,y,w,h] = cv2.boundingRect(cnt)
if h>28:
cv2.rectangle(im,(x,y),(x+w,y+h),(0,255,0),2)
roi = thresh[y:y+h,x:x+w]
roismall = cv2.resize(roi,(10,10))
roismall = roismall.reshape((1,100))
roismall = np.float32(roismall)
retval, results, neigh_resp, dists = model.find_nearest(roismall, k = 1)
string = str(int((results[0][0])))
cv2.putText(out,string,(x,y+h),0,1,(0,255,0))
cv2.imshow('im',im)
cv2.imshow('out',out)
cv2.waitKey(0)
And it worked, below is the result I got:
Here it worked with 100% accuracy. I assume this is because all the digits are of the same kind and the same size.
But anyway, this is a good start to go for beginners (I hope so).
In my case I forgot to add the google maps library
<application>
....
<uses-library android:name="com.google.android.maps" />
</application>
Also, check that you're not missing the preceding dot before the activity path
<activity android:name=".activities.MainActivity"/>
If CURLOPT_FAILONERROR
is false
, http errors will not trigger curl
errors.
<?php
if (@$_GET['curl']=="yes") {
header('HTTP/1.1 503 Service Temporarily Unavailable');
} else {
$ch=curl_init($url = "http://".$_SERVER['SERVER_NAME'].$_SERVER['PHP_SELF']."?curl=yes");
curl_setopt($ch, CURLOPT_FAILONERROR, true);
$response=curl_exec($ch);
$http_status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$curl_errno= curl_errno($ch);
if ($http_status==503)
echo "HTTP Status == 503 <br/>";
echo "Curl Errno returned $curl_errno <br/>";
}
If we get the value as int
and we set it to String
, the error occurs. PFB my solution,
Textview = tv_property_count;
int property_id;
tv_property_count.setText(String.valueOf(property_id));
This error got resolved when I tried initialising the git using git init . It worked
I think the right way to find the internal Java used by the Android Studio is to
This will not require memorising the folder or searching for java and also these steps wil take of any future changes to the java location by the Android Studio team changes I suppose
This is because h1
is a block element, so it will extend across the line (or the width you give).
You can make the border go only around the text by setting display:inline
on the h1
Sometimes you need to work with adjustments.
Don't use cast to long! Use nanoadjustment.
For example, using Oanda Java API for trading you can get datetime as UNIX format.
For example: 1592523410.590566943
System.out.println("instant with nano = " + Instant.ofEpochSecond(1592523410, 590566943));
System.out.println("instant = " + Instant.ofEpochSecond(1592523410));
you get:
instant with nano = 2020-06-18T23:36:50.590566943Z
instant = 2020-06-18T23:36:50Z
Also, use:
Date date = Date.from( Instant.ofEpochSecond(1592523410, 590566943) );
You can simplify it to
if ($user_sam -and $user_case) {
...
}
because empty strings coerce to $false
(and so does $null
, for that matter).
This actually sums it up pretty nicely.
API Levels generally mean that as a programmer, you can communicate with the devices' built in functions and functionality. As the API level increases, functionality adds up (although some of it can get deprecated).
Choosing an API level for an application development should take at least two thing into account:
Android API levels can be divided to five main groups (not scientific, but what the heck):
For method decorator declaration
with configuration "noImplicitAny": true,
you can specify type of this variable explicitly depends on @tony19's answer
function logParameter(this:any, target: Object, propertyName: string) {
//...
}
Your selector is retrieving the text box's surrounding <div class='textBoxEmployeeNumber'>
instead of the input inside it.
// Access the input inside the div with this selector:
$(function () {
$('.textBoxEmployeeNumber input').val("fgg");
});
If the ASP.NET code reliably outputs the HTML <input>
with an id attribute id='EmployeeId'
, you can more simply just use:
$(function () {
$('#EmployeeId').val("fgg");
});
Failing this, you will need to verify in your browser's error console that you don't have other script errors causing this to fail. The first example above works correctly in this demonstration.
I'm using Node.js v.6.0.0 and the fastest is the one with index (the 3rd method in Lo Sauer's answer).
The second is:
function count(s, c) {_x000D_
var n = 0;_x000D_
for (let x of s) {_x000D_
if (x == c)_x000D_
n++;_x000D_
}_x000D_
return n;_x000D_
}
_x000D_
For arrays where the elements are neither Hashable nor Comparable (e.g. complex objects, dictionaries or structs), this extension provides a generalized way to remove duplicates:
extension Array
{
func filterDuplicate<T:Hashable>(_ keyValue:(Element)->T) -> [Element]
{
var uniqueKeys = Set<T>()
return filter{uniqueKeys.insert(keyValue($0)).inserted}
}
func filterDuplicate<T>(_ keyValue:(Element)->T) -> [Element]
{
return filterDuplicate{"\(keyValue($0))"}
}
}
// example usage: (for a unique combination of attributes):
peopleArray = peopleArray.filterDuplicate{ ($0.name, $0.age, $0.sex) }
or...
peopleArray = peopleArray.filterDuplicate{ "\(($0.name, $0.age, $0.sex))" }
You don't have to bother with making values Hashable and it allows you to use different combinations of fields for uniqueness.
Note: for a more robust approach, please see the solution proposed by Coeur in the comments below.
stackoverflow.com/a/55684308/1033581
[EDIT] Swift 4 alternative
With Swift 4.2 you can use the Hasher class to build a hash much easier. The above extension could be changed to leverage this :
extension Array
{
func filterDuplicate(_ keyValue:((AnyHashable...)->AnyHashable,Element)->AnyHashable) -> [Element]
{
func makeHash(_ params:AnyHashable ...) -> AnyHashable
{
var hash = Hasher()
params.forEach{ hash.combine($0) }
return hash.finalize()
}
var uniqueKeys = Set<AnyHashable>()
return filter{uniqueKeys.insert(keyValue(makeHash,$0)).inserted}
}
}
The calling syntax is a little different because the closure receives an additional parameter containing a function to hash a variable number of values (which must be Hashable individually)
peopleArray = peopleArray.filterDuplicate{ $0($1.name, $1.age, $1.sex) }
It will also work with a single uniqueness value (using $1 and ignoring $0).
peopleArray = peopleArray.filterDuplicate{ $1.name }
Stumbled upon this one but you can get it by using the following as long as you import numpy.
import numpy as np
[y, x] = np.shape(img[:,:,0])
It works because you ignore all but one color and then the image is just 2D so shape tells you how bid it is. Still kinda new to Python but seems like a simple way to do it.
I wanted to keep the formulas in place, which the above code did not do.
Here's what I've been doing, note that this leaves one empty row in the table.
Sub DeleteTableRows(ByRef Table As ListObject, KeepFormulas as boolean)
On Error Resume Next
if not KeepFormulas then
Table.DataBodyRange.clearcontents
end if
Table.DataBodyRange.Rows.Delete
On Error GoTo 0
End Sub
(PS don't ask me why!)
For me, when typing the url, a user accidentally used a / instead of a ? to start the query parameters
e.g.:
url.com/endpoint/parameter=SomeValue&otherparameter=Another+value
which should have been:
url.com/endpoint?parameter=SomeValue&otherparameter=Another+value
The answers here, are way too complex. Here's something I've recently used:
<?php global $product; ?>
<img src="<?php echo wp_get_attachment_url( $product->get_image_id() ); ?>" />
Using wp_get_attachment_url()
to display the
To phyzome's answer (most highly voted one), it seems to me that if you put "identified by" at the end of the grant statement, the user will be created automatically. But if you don't, the user is not created. The following code works for me,
GRANT USAGE ON *.* TO 'username'@'localhost' IDENTIFIED BY 'password';
DROP USER 'username'@'localhost';
Hope this helps.
It will shift the bits by padding that many 0's
.
For ex,
10
which is digit 2
left shift by 2 is 1000
which is digit 8
10
which is digit 2
left shift by 3 is 10000
which is digit 16
With Java 8 there is this API method to accomplish your requirement.
map.putIfAbsent(key, value)
If the specified key is not already associated with a value (or is mapped to null) associates it with the given value and returns null, else returns the current value.
Other answers indicate perfectly well that --no-ff
results in a merge commit. This retains historical information about the feature branch which is useful since feature branches are regularly cleaned up and deleted.
This answer may provide context for when to use or not to use --no-ff
.
--no-ff
Worked example:
$ git checkout -b NewFeature
[work...work...work]
$ git commit -am "New feature complete!"
$ git checkout main
$ git merge --no-ff NewFeature
$ git push origin main
$ git branch -d NewFeature
--no-ff
Worked example:
$ git checkout -b NewFeature
[work...work...work]
[New changes made for HotFix in the main branch! Lets get them...]
$ git commit -am "New feature in progress"
$ git pull origin main
[shortcut for "git fetch origin main", "git merge origin main"]
It seems that you'll need two fields, a choice list for the currency and a number field for the value.
A common technique in such case is to use a div or span for the display (form fields offscreen), and on click switch to the form elements for editing.
Look into the cURL library. I've never used it in Java, but I'm sure there must be bindings for it. Basically, what you'll do is send a cURL request to whatever page you want to 'scrape'. The request will return a string with the source code to the page. From there, you will use regex to parse whatever data you want from the source code. That's generally how you are going to do it.
Found it!
SELECT username,
account_status
FROM dba_users;
Gets the value of the current TimeSpan structure expressed in whole and fractional minutes.
The problem is clearly not with the javascript. Here's a quick snippet to show you the working of the code.
document.getElementById('points').value = 100;
As you can see, the javascript perfectly assigns the new value to the input element. It would be helpful if you could elaborate more on the issue.
I just had a similar problem with Error#77 on CentOS7. I was missing the softlink /etc/pki/tls/certs/ca-bundle.crt that is installed with the ca-certificates RPM.
'curl' was attempting to open this path to get the Certificate Authorities. I discovered with:
strace curl https://example.com
and saw clearly that the open failed on that link.
My fix was:
yum reinstall ca-certificates
That should setup everything again. If you have private CAs for Corporate or self-signed use make sure they are in /etc/pki/ca-trust/source/anchors so that they are re-added.
You're not passing any credentials to sqlcmd.exe
So it's trying to authenticate you using the Windows Login credentials, but you mustn't have your SQL Server setup to accept those credentials...
When you were installing it, you would have had to supply a Server Admin password (for the sa
account)
Try...
sqlcmd.exe -U sa -P YOUR_PASSWORD -S ".\SQL2008"
for reference, theres more details here...
If you want the keys and values, you can always do this via the entrySet
:
hashMap.entrySet().toArray(); // returns a Map.Entry<K,V>[]
From each entry you can (of course) get both the key and value via the getKey
and getValue
methods
aList=[1,2,3]
i=0
for item in aList:
if i<2:
aList.remove(item)
i+=1
aList
[2]
The moral is when modifying a list in a loop driven by the list, takes two steps:
aList=[1,2,3]
i=0
for item in aList:
if i<2:
aList[i]="del"
i+=1
aList
['del', 'del', 3]
for i in range(2):
del aList[0]
aList
[3]
Send the following headers before outputting the file:
header("Content-Disposition: attachment; filename=\"" . basename($File) . "\"");
header("Content-Type: application/octet-stream");
header("Content-Length: " . filesize($File));
header("Connection: close");
@grom: Interesting about the 'application/octet-stream' MIME type. I wasn't aware of that, have always just used 'application/force-download' :)
There is nothing wrong with count() here, "trends" is the only key that is being counted in this case, you can try doing:
count($obj->trends);
Or:
count($obj->trends['2009-08-21 11:05']);
Or maybe even doing:
count($obj, COUNT_RECURSIVE);
You can use the lsof command. Let port number like here is 8090
lsof -i:8090
This command returns a list of open processes on this port.
Something like…
COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME
ssh 75782 eoin 5u IPv6 0x01c1c234 0t0 TCP localhost:8090 (LISTEN)
To free the port, kill the process using it(the process id is 75782)…
kill -9 75782
This one worked for me. here is the link from the original post: link
That's easy to do in Interface Builder:
1) make UILabel Attributed in Attributes Inspector
2) select part of phrase you want to make bold
3) change its font (or bold typeface of the same font) in font selector
That's all!
If you want it outside of loop then use the below code.
<?php
$author_id = get_post_field ('post_author', $cause_id);
$display_name = get_the_author_meta( 'display_name' , $author_id );
echo $display_name;
?>
I solved this using JNA: https://github.com/twall/jna
import com.sun.jna.Library;
import com.sun.jna.Native;
import com.sun.jna.Platform;
public class prova {
private interface CLibrary extends Library {
CLibrary INSTANCE = (CLibrary) Native.loadLibrary((Platform.isWindows() ? "msvcrt" : "c"), CLibrary.class);
int system(String cmd);
}
private static int exec(String command) {
return CLibrary.INSTANCE.system(command);
}
public static void main(String[] args) {
exec("ls");
}
}
You can also write it like this:
let elem: any;
elem = $("div.printArea");
elem.printArea();
sys .argv will display the command line args passed when running a script or you can say sys.argv will store the command line arguments passed in python while running from terminal.
Just try this:
import sys
print sys.argv
argv stores all the arguments passed in a python list. The above will print all arguments passed will running the script.
Now try this running your filename.py like this:
python filename.py example example1
this will print 3 arguments in a list.
sys.argv[0] #is the first argument passed, which is basically the filename.
Similarly, argv1 is the first argument passed, in this case 'example'
A similar question has been asked already here btw. Hope this helps!
Just use CSS to hide the content you do not want printed. When the user selects print - the page will look to the " media="print" CSS for instructions about the layout of the page.
The media="print" CSS has instructions to hide the content that we do not want printed.
<!-- CSS for the things we want to print (print view) -->
<style type="text/css" media="print">
#SCREEN_VIEW_CONTAINER{
display: none;
}
.other_print_layout{
background-color:#FFF;
}
</style>
<!-- CSS for the things we DO NOT want to print (web view) -->
<style type="text/css" media="screen">
#PRINT_VIEW{
display: none;
}
.other_web_layout{
background-color:#E0E0E0;
}
</style>
<div id="SCREEN_VIEW_CONTAINER">
the stuff I DO NOT want printed is here and will be hidden -
and not printed when the user selects print.
</div>
<div id="PRINT_VIEW">
the stuff I DO want printed is here.
</div>
In my case, I had the same issue when the name of my project contains a "&" sign.The solution is to rename the project name,from file browser, so it doesn't contain any "&" signs and then from:
I've tested it two times and it worked just fine.
Its quite a common misconception that you need a clear:both
div at the bottom, when you really don't. While foxy's answer is correct, you don't need that non-semantic, useless clearing div. All you need to do is stick an overflow:hidden
onto the container:
#sub-title { overflow:hidden; }
Using width/height on inline elements is not always a good idea.
You can use display: inline-block
instead
Install Visual Studio 2015 Community Edition from https://www.visualstudio.com, then
for Python 3.4
set VS100COMNTOOLS=%VS140COMNTOOLS% && pip install XX
100%-100px is the same
div.thediv {
width: auto;
margin-right:100px;
}
With jQuery:
$(window).resize(function(){
$('.thediv').each(function(){
$(this).css('width', $(this).parent().width()-100);
})
});
Similar way is to use jQuery resize plugin
It sounds like you have installed SQL Server 2005 Express Edition, which does not include SSIS or the Business Intelligence Development Studio.
BIDS is only provided with the (not free) Standard, Enterprise and Developer Editions.
EDIT
This information was correct for SQL Server 2005. Since SQL Server 2014, Developer Edition has been free. BIDS has been replaced by SQL Server Data Tools, a free plugin for Visual Studio (including the free Visual Studio Community Edition).
If you by writing "non letters and numbers" exclude more than [A-Za-z0-9]
(ie. considering letters like åäö
to be letters to) and want to be able to accurately handle UTF-8 strings \p{L}
and \p{N}
will be of aid.
\p{N}
will match any "Number"\p{L}
will match any "Letter Character", which includes
Documentation PHP: Unicode Character Properties
$data = "Thäre!wouldn't%bé#äny";
$new_data = str_replace ("'", "", $data);
$new_data = preg_replace ('/[^\p{L}\p{N}]/u', '_', $new_data);
var_dump (
$new_data
);
output
string(23) "Thäre_wouldnt_bé_äny"
The error is because of the sql mode which can be strict mode as per latest MYSQL 5.7 documentation.
For more information read this.
Hope it helps.
When I want to access the application file version (what is set in Assembly Information -> File version), say to set a label's text to it on form load to display the version, I have just used
versionlabel.Text = "Version " + Application.ProductVersion;
This approach requires a reference to System.Windows.Forms
.
That's really an informational message.
Likely, you're doing OPTIMIZE on an InnoDB table (table using the InnoDB storage engine, rather than the MyISAM storage engine).
InnoDB doesn't support the OPTIMIZE the way MyISAM does. It does something different. It creates an empty table, and copies all of the rows from the existing table into it, and essentially deletes the old table and renames the new table, and then runs an ANALYZE to gather statistics. That's the closest that InnoDB can get to doing an OPTIMIZE.
The message you are getting is basically MySQL server repeating what the InnoDB storage engine told MySQL server:
Table does not support optimize is the InnoDB storage engine saying...
"I (the InnoDB storage engine) don't do an OPTIMIZE operation like my friend (the MyISAM storage engine) does."
"doing recreate + analyze instead" is the InnoDB storage engine saying...
"I have decided to perform a different set of operations which will achieve an equivalent result."
open terminal and type the below command and hit enter
sudo /Library/PostgreSQL/9.X/uninstall-postgresql.app/Contents/MacOS/installbuilder.sh
If you need this solution for only few types of modals just use
style="width:90%"
attribute.
example:
div class="modal-dialog modal-lg" style="width:90%"
note: this will change only this particular modal
If you are using JDK 6 then you might want to check out ConcurrentHashMap
Note the putIfAbsent method in that class.
Use get(0)
instead of html()
. In other words, replace
doc.fromHTML($('#htmlTableId').html(), 15, 15, {
'width': 170,'elementHandlers': specialElementHandlers
});
with
doc.fromHTML($('#htmlTableId').get(0), 15, 15, {
'width': 170,'elementHandlers': specialElementHandlers
});
You cannot do this purely in Javascript. Javascript running on browsers does not have enough permission yet (there have been proposals) due to security reasons.
Instead, I would recommend using Downloadify:
A tiny javascript + Flash library that enables the creation and download of text files without server interaction.
You can see a simple demo here where you supply the content and can test out saving/cancelling/error handling functionality.
Another way besides @Nahush's answer, if you are already using Express framework in the project then you can avoid using Nginx for reverse-proxy.
A simpler way is to use express-http-proxy
run npm run build
to create the bundle.
var proxy = require('express-http-proxy');
var app = require('express')();
//define the path of build
var staticFilesPath = path.resolve(__dirname, '..', 'build');
app.use(express.static(staticFilesPath));
app.use('/api/api-server', proxy('www.api-server.com'));
Use "/api/api-server" from react code to call the API.
So, that browser will send request to the same host which will be internally redirecting the request to another server and the browser will feel that It is coming from the same origin ;)
This way I was able to call MyService
private REST_API_SERVER = 'http://localhost:4040/abc';
public sendGetRequest() {
var myFormData = { email: '[email protected]', password: '123' };
const headers = new HttpHeaders();
headers.append('Content-Type', 'application/json');
//HTTP POST REQUEST
this.httpClient
.post(this.REST_API_SERVER, myFormData, {
headers: headers,
})
.subscribe((data) => {
console.log("i'm from service............", data, myFormData, headers);
return data;
});
}
If the files are not gigantic:
with open('newfile.txt','wb') as newf:
for filename in list_of_files:
with open(filename,'rb') as hf:
newf.write(hf.read())
# newf.write('\n\n\n') if you want to introduce
# some blank lines between the contents of the copied files
If the files are too big to be entirely read and held in RAM, the algorithm must be a little different to read each file to be copied in a loop by chunks of fixed length, using read(10000)
for example.
In my case, for jboss 6.3
I had to change JAVA_OPTS
in file jboss-eap-6.3\bin\standalone.conf.bat
and set following values -Xmx8g -Xms8g -Xmn3080m
for jvm to take 8gb space.
<a href="javascript:void(0)" class="aaf" id="users_id">add as a friend</a>
on jquery
$('.aaf').on("click",function(){
var usersid = $(this).attr("id");
//post code
})
//other method is to use the data attribute
<a href="javascript:void(0)" class="aaf" data-id="102" data-username="sample_username">add as a friend</a>
on jquery
$('.aaf').on("click",function(){
var usersid = $(this).data("id");
var username = $(this).data("username");
})
Since your main aim was to convert the type of a column in a DataFrame from String to Timestamp, I think this approach would be better.
import org.apache.spark.sql.functions.{to_date, to_timestamp}
val modifiedDF = DF.withColumn("Date", to_date($"Date", "MM/dd/yyyy"))
You could also use to_timestamp
(I think this is available from Spark 2.x) if you require fine grained timestamp.
You can't.
In order to "use" the struct, i.e. to be able to declare objects of that type and to access its internals you need the full definition of the struct. So, it you want to do any of that (and you do, judging by your error messages), you have to place the full definition of the struct type into the header file.
Yes this is possible, however not convenient as Jens said. Using Next generation load balancers like Alteon, which Uses a proprietary protocol called DSSP(Distributed site state Protocol) which performs regular site checks to make sure that the service is available both Locally or Globally i.e different geographical areas. You need to however in your Master DNS to delegate the URL or Service to the device by configuring it as an Authoritative Name Server for that IP or Service. By doing this, the device answers DNS queries where it will resolve the IP that has a service by Round-Robin or is not congested according to how you have chosen from several metrics.
When you can't apply Juki's answer then after selecting the desired version of media you can use Fiddler to determine where the files are located.
SQL Server 2019 Express Edition (English):
SQL Server 2017 Express Edition (English):
SQL Server 2016 with SP2 Express Edition (English):
SQL Server 2016 with SP1 Express Edition (English):
And here is how to use Fiddler.
The necessary method is Mockito#verify:
public static <T> T verify(T mock,
VerificationMode mode)
mock
is your mocked object and mode
is the VerificationMode
that describes how the mock should be verified. Possible modes are:
verify(mock, times(5)).someMethod("was called five times");
verify(mock, never()).someMethod("was never called");
verify(mock, atLeastOnce()).someMethod("was called at least once");
verify(mock, atLeast(2)).someMethod("was called at least twice");
verify(mock, atMost(3)).someMethod("was called at most 3 times");
verify(mock, atLeast(0)).someMethod("was called any number of times"); // useful with captors
verify(mock, only()).someMethod("no other method has been called on the mock");
You'll need these static imports from the Mockito
class in order to use the verify
method and these verification modes:
import static org.mockito.Mockito.atLeast;
import static org.mockito.Mockito.atLeastOnce;
import static org.mockito.Mockito.atMost;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.only;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
So in your case the correct syntax will be:
Mockito.verify(mock, times(4)).send()
This verifies that the method send
was called 4 times on the mocked object. It will fail if it was called less or more than 4 times.
If you just want to check, if the method has been called once, then you don't need to pass a VerificationMode
. A simple
verify(mock).someMethod("was called once");
would be enough. It internally uses verify(mock, times(1)).someMethod("was called once");
.
It is possible to have multiple verification calls on the same mock to achieve a "between" verification. Mockito doesn't support something like this verify(mock, between(4,6)).someMethod("was called between 4 and 6 times");
, but we can write
verify(mock, atLeast(4)).someMethod("was called at least four times ...");
verify(mock, atMost(6)).someMethod("... and not more than six times");
instead, to get the same behaviour. The bounds are included, so the test case is green when the method was called 4, 5 or 6 times.
It can be done using:-
SELECT COUNT(COLUMN_NAME) 'NO OF COLUMN' FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = 'Address'
You can also customize the by passing the delete item along with the message. In my case using MVC and Razor, so I could do this:
@Html.ActionLink("Delete",
"DeleteTag", new { id = t.IDTag },
new { onclick = "return confirm('Do you really want to delete the tag " + @t.Tag + "?')" })
You can easily comment out the data using this:
<!--
<data>
<data-field1></data-field1>
<data-field2></data-field2>
<data-field3></data-field3>
</data>
-->
method of commenting in xml.
The other answers given here work well since you use the same renderer in every column.
However, I tend to believe that generally when using a JTable you will have different types of data in each columm and therefore you won't be using the same renderer for each column. In these cases you may find the Table Row Rendering approach helpfull.
You might encounter one of these three problems:
A blog post with the summary for all three possible problems might be found here: https://cms4j.wordpress.com/2016/11/29/0x851c0001-the-credentials-you-provided-for-the-sqlserveragent-service-is-invalid/
try using sudo apt install python3-opencv
it will install the latest package of open cv.
Or you could try reinstalling the opencv package. It might have got corrupted during installation.
ps aux|awk '{print $2,$3,$4}'|grep PID
where the first column is the PID,second column CPU usage ,third column memory usage.
You can use loop for.
var items = {1, 2, 3}
for(var i = 0; i < items.length; i++) {
if(i == items.length - 1) {
res.ok(i);
}
}
The Adjusted R-squared is close to, but different from, the value of R2. Instead of being based on the explained sum of squares SSR and the total sum of squares SSY, it is based on the overall variance (a quantity we do not typically calculate), s2T = SSY/(n - 1) and the error variance MSE (from the ANOVA table) and is worked out like this: adjusted R-squared = (s2T - MSE) / s2T.
This approach provides a better basis for judging the improvement in a fit due to adding an explanatory variable, but it does not have the simple summarizing interpretation that R2 has.
If I haven't made a mistake, you should verify the values of adjusted R-squared and R-squared as follows:
s2T <- sum(anova(v.lm)[[2]]) / sum(anova(v.lm)[[1]])
MSE <- anova(v.lm)[[3]][2]
adj.R2 <- (s2T - MSE) / s2T
On the other side, R2 is: SSR/SSY, where SSR = SSY - SSE
attach(v)
SSE <- deviance(v.lm) # or SSE <- sum((epm - predict(v.lm,list(n_days)))^2)
SSY <- deviance(lm(epm ~ 1)) # or SSY <- sum((epm-mean(epm))^2)
SSR <- (SSY - SSE) # or SSR <- sum((predict(v.lm,list(n_days)) - mean(epm))^2)
R2 <- SSR / SSY
You can alias the column names one by one, like so
SELECT col1 as `MyNameForCol1`, col2 as `MyNameForCol2`
FROM `foobar`
Edit You can access INFORMATION_SCHEMA.COLUMNS
directly to mangle a new alias like so. However, how you fit this into a query is beyond my MySql skills :(
select CONCAT('Foobar_', COLUMN_NAME)
from INFORMATION_SCHEMA.COLUMNS
where TABLE_NAME = 'Foobar'
I've had success with something like this:
var $menuscontainer = ...;
$('#trigger').click(function() {
$menuscontainer.show();
$('body').click(function(event) {
var $target = $(event.target);
if ($target.parents('#menuscontainer').length == 0) {
$menuscontainer.hide();
}
});
});
The logic is: when #menuscontainer
is shown, bind a click handler to the body that hides #menuscontainer
only if the target (of the click) isn't a child of it.
Yes, you can do this. The knack you need is the concept that there are two ways of getting tables out of the table server. One way is ..
FROM TABLE A
The other way is
FROM (SELECT col as name1, col2 as name2 FROM ...) B
Notice that the select clause and the parentheses around it are a table, a virtual table.
So, using your second code example (I am guessing at the columns you are hoping to retrieve here):
SELECT a.attr, b.id, b.trans, b.lang
FROM attribute a
JOIN (
SELECT at.id AS id, at.translation AS trans, at.language AS lang, a.attribute
FROM attributeTranslation at
) b ON (a.id = b.attribute AND b.lang = 1)
Notice that your real table attribute
is the first table in this join, and that this virtual table I've called b
is the second table.
This technique comes in especially handy when the virtual table is a summary table of some kind. e.g.
SELECT a.attr, b.id, b.trans, b.lang, c.langcount
FROM attribute a
JOIN (
SELECT at.id AS id, at.translation AS trans, at.language AS lang, at.attribute
FROM attributeTranslation at
) b ON (a.id = b.attribute AND b.lang = 1)
JOIN (
SELECT count(*) AS langcount, at.attribute
FROM attributeTranslation at
GROUP BY at.attribute
) c ON (a.id = c.attribute)
See how that goes? You've generated a virtual table c
containing two columns, joined it to the other two, used one of the columns for the ON
clause, and returned the other as a column in your result set.
Use padding to fake it since vertical-align doesn't work on text inputs.
CSS
.date-input {
width: 145px;
padding-top: 80px;
}?
PHP does not do styling. You need to use html or css. Take a look at http://www.w3schools.com/tags/tag_hr.asp
In HTML 4.01, the
In HTML 4.01, the <hr> tag represents a horizontal rule.
String str = "to";
str.replace("to", "xyz");
Just try it :)
5623125698541159
is treated as a single number (out of range of int
on most architecture). You need to write numbers in your file as
5 6 2 3 1 2 5 6 9 8 5 4 1 1 5 9
for 16 numbers.
If your file has input
5,6,2,3,1,2,5,6,9,8,5,4,1,1,5,9
then change %d
specifier in your fscanf
to %d,
.
fscanf(myFile, "%d,", &numberArray[i] );
Here is your full code after few modifications:
#include <stdio.h>
#include <stdlib.h>
int main(){
FILE *myFile;
myFile = fopen("somenumbers.txt", "r");
//read file into array
int numberArray[16];
int i;
if (myFile == NULL){
printf("Error Reading File\n");
exit (0);
}
for (i = 0; i < 16; i++){
fscanf(myFile, "%d,", &numberArray[i] );
}
for (i = 0; i < 16; i++){
printf("Number is: %d\n\n", numberArray[i]);
}
fclose(myFile);
return 0;
}
In my case, I forgot to add library jackson-core.jar, I only added jackson-annotations.jar and jackson-databind.jar. When I added jackson-core.jar, it fixed the problem.
Hi try this it will create directory + file inside it
File mediaDir = new File("/sdcard/download/media");
if (!mediaDir.exists()){
mediaDir.mkdir();
}
File resolveMeSDCard = new File("/sdcard/download/media/hello_file.txt");
resolveMeSDCard.createNewFile();
FileOutputStream fos = new FileOutputStream(resolveMeSDCard);
fos.write(string.getBytes());
fos.close();
System.out.println("Your file has been written");
An alternate I would suggest in this use case is to use the MAX(t_stamp) to get the latest row ... e.g.
select t.* from raceway_input_labo t
where t.t_stamp = (select max(t_stamp) from raceway_input_labo)
limit 1
My coding pattern preference (perhaps) - reliable, generally performs at or better than trying to select the 1st row from a sorted list - also the intent is more explicitly readable.
Hope this helps ...
SQLer
You should include <string.h>
(or its C++ equivalent, <cstring>
).
Based on the existing answers, here's a step-by-step guide to sending automated e-mails over SMTP, using a GMail account, from the command line, without disclosing the password.
First, install the following software packages:
These instructions assume a Linux operating system, but should be reasonably easy to port to Windows (via Cygwin or native equivalents), or other operating system.
Save the following shell script as authentication.sh
:
#!/bin/bash
# Asks for a username and password, then spits out the encoded value for
# use with authentication against SMTP servers.
echo -n "Email (shown): "
read email
echo -n "Password (hidden): "
read -s password
echo
TEXT="\0$email\0$password"
echo -ne $TEXT | base64
Make it executable and run it as follows:
chmod +x authentication.sh
./authentication.sh
When prompted, provide your e-mail address and password. This will look something like:
Email (shown): [email protected]
Password (hidden):
AGJvYkBnbWFpbC5jb20AYm9iaXN0aGViZXN0cGVyc29uZXZlcg==
Copy the last line (AGJ...==
), as this will be used for authentication.
Save the following expect script as notify.sh
(note the first line refers to the expect program):
#!/usr/bin/expect
set address "[lindex $argv 0]"
set subject "[lindex $argv 1]"
set ts_date "[lindex $argv 2]"
set ts_time "[lindex $argv 3]"
set timeout 10
spawn openssl s_client -connect smtp.gmail.com:465 -crlf -ign_eof
expect "220" {
send "EHLO localhost\n"
expect "250" {
send "AUTH PLAIN YOUR_AUTHENTICATION_CODE\n"
expect "235" {
send "MAIL FROM: <YOUR_EMAIL_ADDRESS>\n"
expect "250" {
send "RCPT TO: <$address>\n"
expect "250" {
send "DATA\n"
expect "354" {
send "Subject: $subject\n\n"
send "Email sent on $ts_date at $ts_time.\n"
send "\n.\n"
expect "250" {
send "quit\n"
}
}
}
}
}
}
}
Make the following changes:
YOUR_AUTHENTICATION_CODE
with the authentication code generated by the authentication script.YOUR_EMAIL_ADDRESS
with the e-mail address used to generate the authentication code.For example (note the angle brackets are retained for the e-mail address):
send "AUTH PLAIN AGJvYkBnbWFpbC5jb20AYm9iaXN0aGViZXN0cGVyc29uZXZlcg==\n"
send "MAIL FROM: <[email protected]>\n"
Lastly, make the notify script executable as follows:
chmod +x notify.sh
Send an e-mail from the command line as follows:
./notify.sh [email protected] "Command Line" "March 14" "15:52"
I don't know how good that solution is but it is definitely THE EASY ONE i just used in my app and it is working fine
you load the image like that
public void loadImage (){
Picasso picasso = Picasso.get();
picasso.setIndicatorsEnabled(true);
picasso.load(quiz.getImageUrl()).into(quizImage);
}
You can get the bimap
like that
Bitmap bitmap = Picasso.get().load(quiz.getImageUrl()).get();
Now covert that Bitmap
into a JPG
file and store in the in the cache, below is complete code for getting the bimap and caching it
Thread thread = new Thread() {
public void run() {
File file = new File(getCacheDir() + "/" +member.getMemberId() + ".jpg");
try {
Bitmap bitmap = Picasso.get().load(uri).get();
FileOutputStream fOut = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100,new FileOutputStream(file));
fOut.flush();
fOut.close();
}
catch (Exception e) {
e.printStackTrace();
}
}
};
thread.start();
})
the get()
method of Piccasso
need to be called on separate thread , i am saving that image also on that same thread.
Once the image is saved you can get all the files like that
List<File> files = new LinkedList<>(Arrays.asList(context.getExternalCacheDir().listFiles()));
now you can find the file you are looking for like below
for(File file : files){
if(file.getName().equals("fileyouarelookingfor" + ".jpg")){ // you need the name of the file, for example you are storing user image and the his image name is same as his id , you can call getId() on user to get the file name
Picasso.get() // if file found then load it
.load(file)
.into(mThumbnailImage);
return; // return
}
// fetch it over the internet here because the file is not found
}
When you develop an emulator you are interpreting the processor assembly that the system is working on (Z80, 8080, PS CPU, etc.).
You also need to emulate all peripherals that the system has (video output, controller).
You should start writing emulators for the simpe systems like the good old Game Boy (that use a Z80 processor, am I not not mistaking) OR for C64.
You have to check every ID in tableA against every ID in tableB. A fully featured RDBMS (such as Oracle) would be able to optimize that into an INDEX FULL FAST SCAN and not touch the table at all. I don't know whether H2's optimizer is as smart as that.
H2 does support the MINUS syntax so you should try this
select id from tableA
minus
select id from tableB
order by id desc
That may perform faster; it is certainly worth benchmarking.
Several choices to do this...
Set background to green:
v.setBackgroundColor(0x00FF00);
Set background to green with Alpha:
v.setBackgroundColor(0xFF00FF00);
Set background to green with Color.GREEN constant:
v.setBackgroundColor(Color.GREEN);
Set background to green defining in Colors.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="myGreen">#00FF00</color>
<color name="myGreenWithAlpha">#FF00FF00</color>
</resources>
and using:
v.setBackgroundResource(R.color.myGreen);
and:
v.setBackgroundResource(R.color.myGreenWithAlpha);
or the longer winded:
v.setBackgroundColor(ContextCompat.getColor(getContext(), R.color.myGreen));
and:
v.setBackgroundColor(ContextCompat.getColor(getContext(), R.color.myGreenWithAlpha));
An interface is a "contract" where the class that implements the contract promises to implement the methods. An example where I had to write an interface instead of a class was when I was upgrading a game from 2D to 3D. I had to create an interface to share classes between the 2D and the 3D version of the game.
package adventure;
import java.awt.*;
public interface Playable {
public void playSound(String s);
public Image loadPicture(String s);
}
Then I can implement the methods based on the environment, while still being able to call those methods from an object that doesn't know which version of the game that is loading.
public class Adventure extends JFrame implements Playable
public class Dungeon3D extends SimpleApplication implements Playable
public class Main extends SimpleApplication implements AnimEventListener,
ActionListener, Playable
Typically, in the gameworld, the world can be an abstract class that performs methods on the game:
public abstract class World...
public Playable owner;
public Playable getOwner() {
return owner;
}
public void setOwner(Playable owner) {
this.owner = owner;
}
I faced the same issue.
If you issued an api for your release version of the application. Then that api will only work for the release version not for the debug version. So make sure you are using the release version in your phone or emulator .
String.prototype.toHHMMSS = function () {
var sec_num = parseInt(this, 10); // don't forget the second param
var hours = Math.floor(sec_num / 3600);
var minutes = Math.floor((sec_num - (hours * 3600)) / 60);
var seconds = sec_num - (hours * 3600) - (minutes * 60);
if (hours < 10) {hours = "0"+hours;}
if (minutes < 10) {minutes = "0"+minutes;}
if (seconds < 10) {seconds = "0"+seconds;}
return hours+':'+minutes+':'+seconds;
}
Usage Example
alert("186".toHHMMSS());
I just encountered this.
1) Find the cygwin setup.exe file from http://cygwin.com/ and run it.
2) Click/enter preferences until you reach the "Select Packages" window. (See image)
3) Click (+) for Net
4) Click the entry for curl. (Make sure you select the checkbox for the Binary)
5) Install.
6) Open a cygwin window and type curl.exe (should be available now).
IIRC it allows you to create private properties and methods.
Going off of @Rok Kralj answer (best IMO) to check if any of needles exist in the haystack, you can use (bool)
instead of !!
which sometimes can be confusing during code review.
function in_array_any($needles, $haystack) {
return (bool)array_intersect($needles, $haystack);
}
echo in_array_any( array(3,9), array(5,8,3,1,2) ); // true, since 3 is present
echo in_array_any( array(4,9), array(5,8,3,1,2) ); // false, neither 4 nor 9 is present
It's something that "appears to the rest of the system to occur instantaneously", and falls under categorisation of Linearizability in computing processes. To quote that linked article further:
Atomicity is a guarantee of isolation from concurrent processes. Additionally, atomic operations commonly have a succeed-or-fail definition — they either successfully change the state of the system, or have no apparent effect.
So, for instance, in the context of a database system, one can have 'atomic commits', meaning that you can push a changeset of updates to a relational database and those changes will either all be submitted, or none of them at all in the event of failure, in this way data does not become corrupt, and consequential of locks and/or queues, the next operation will be a different write or a read, but only after the fact. In the context of variables and threading this is much the same, applied to memory.
Your quote highlights that this need not be expected behaviour in all instances.
In case you need possibility to hide and show scrollbars dynamically you could use
$("body").css("overflow", "hidden");
and
$("body").css("overflow", "auto");
somewhere in your code.
One difference between GUID in SQL Server and UUID in PostgreSQL is letter case; SQL Server outputs upper while PostgreSQL outputs lower.
The hexadecimal values "a" through "f" are output as lower case characters and are case insensitive on input. - rfc4122#section-3
Page should be refresh auto using meta tag
<meta http-equiv="Refresh" content="60">
content value in seconds.after one minute page should be refresh
Just write
Select id,name,age
From Student
Where age < 15
Union
Select id,name,age
From Student
Where Name like "%a%"
Order by name
the order by is applied to the complete resultset
'cacerts' is a truststore. A trust store is used to authenticate peers. A keystore is used to authenticate yourself.
For anyone who is looking for a solution to this problem in GitBook. This is how I made it work (in GitBook). You need to tag your header explicitly, like this:
# My Anchored Heading {#my-anchor}
Then link to this anchor like this
[link to my anchored heading](#my-anchor)
Solution, and additional examples, may be found here: https://seadude.gitbooks.io/learn-gitbook/
I had exactly this issue in a recent project which really is a pain in the rear. I finally found it's because the Python we used in Docker has encoding "ansi_x3.4-1968" instead of "utf-8". So if anyone out there using Docker and got this error, following these steps may thoroughly solve your problem.
create a file and name it default_locale in the same directory of your Dockerfile, put this line in it,
environment=LANG="es_ES.utf8", LC_ALL="es_ES.UTF-8", LC_LANG="es_ES.UTF-8"
add these to your Dockerfile,
RUN apt-get clean && apt-get update && apt-get install -y locales
RUN locale-gen en_CA.UTF-8
COPY ./default_locale /etc/default/locale
RUN chmod 0755 /etc/default/locale
ENV LC_ALL=en_CA.UTF-8
ENV LANG=en_CA.UTF-8
ENV LANGUAGE=en_CA.UTF-8
This thoroughly solved my issue when I built and run my Docker again, hopefully this solve your issue also.
Had the same error while using SourceTree connected to BitBucket repository.
When navigating to repository url on bitbucket.org the warning message appeared:
This repository is in read-only mode. You caught us doing some quick maintenance.
After around 2 hours repository was accessible again.
You can check status and uptime of bitbucket here: http://status.bitbucket.org/
This is my solution for your reference:
struct Foo
{
Foo(){}//used to make compiler happy!
Foo(int x){/*...*/}
};
struct Bar
{
Foo foo[3];
Bar()
{
//initialize foo array here:
for(int i=0;i<3;++i)
{
foo[i]=Foo(4+i);
}
}
};
In latest versions of mysql, at least in mine, you cannot put your pass in the command directly.
You have to run:
mysqldump -u [uname] -p db_name > db_backup.sql
and then it will ask for the password.
The way of dknaack does not work for me, I found this solution as well:
@Html.DropDownList("Chapters", ViewBag.Chapters as SelectList,
"Select chapter", new { @onchange = "location = this.value;" })
where
@Html.DropDownList(controlName, ViewBag.property + cast, "Default value", @onchange event)
In the controller you can add:
DbModel db = new DbModel(); //entity model of Entity Framework
ViewBag.Chapters = new SelectList(db.T_Chapter, "Id", "Name");
Changed blak3r his code a bit. In case you have two adapters with the same speed. Sort by MAC, so you always get the same value.
public string GetMacAddress()
{
const int MIN_MAC_ADDR_LENGTH = 12;
string macAddress = string.Empty;
Dictionary<string, long> macPlusSpeed = new Dictionary<string, long>();
try
{
foreach(NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces())
{
System.Diagnostics.Debug.WriteLine("Found MAC Address: " + nic.GetPhysicalAddress() + " Type: " + nic.NetworkInterfaceType);
string tempMac = nic.GetPhysicalAddress().ToString();
if(!string.IsNullOrEmpty(tempMac) && tempMac.Length >= MIN_MAC_ADDR_LENGTH)
macPlusSpeed.Add(tempMac, nic.Speed);
}
macAddress = macPlusSpeed.OrderByDescending(row => row.Value).ThenBy(row => row.Key).FirstOrDefault().Key;
}
catch{}
System.Diagnostics.Debug.WriteLine("Fastest MAC address: " + macAddress);
return macAddress;
}
The answer is nice, but it introduces one problem. Whenever you assign onload
or onerror
directly, it may replace the callback that was assigned earlier. That is why there's a nice method that "registers the specified listener on the EventTarget it's called on" as they say on MDN. You can register as many listeners as you want on the same event.
Let me rewrite the answer a little bit.
function testImage(url) {
var tester = new Image();
tester.addEventListener('load', imageFound);
tester.addEventListener('error', imageNotFound);
tester.src = url;
}
function imageFound() {
alert('That image is found and loaded');
}
function imageNotFound() {
alert('That image was not found.');
}
testImage("http://foo.com/bar.jpg");
Because the external resource loading process is asynchronous, it would be even nicer to use modern JavaScript with promises, such as the following.
function testImage(url) {
// Define the promise
const imgPromise = new Promise(function imgPromise(resolve, reject) {
// Create the image
const imgElement = new Image();
// When image is loaded, resolve the promise
imgElement.addEventListener('load', function imgOnLoad() {
resolve(this);
});
// When there's an error during load, reject the promise
imgElement.addEventListener('error', function imgOnError() {
reject();
})
// Assign URL
imgElement.src = url;
});
return imgPromise;
}
testImage("http://foo.com/bar.jpg").then(
function fulfilled(img) {
console.log('That image is found and loaded', img);
},
function rejected() {
console.log('That image was not found');
}
);
SELECT [name]
FROM master.dbo.sysdatabases
WHERE dbid > 4
Works on our SQL Server 2008
From the OData documentation:
The OData Protocol is an application-level protocol for interacting with data via RESTful web services.
...
The OData Protocol is different from other REST-based web service approaches in that it provides a uniform way to describe both the data and the data model.
Thank you. I use passing in an object as a parameter. My Android code is below
String oPerson= null;
if (CheckAddress("5556", oPerson))
{
Toast.makeText(this,
"It's Match! " + oPerson,
Toast.LENGTH_LONG).show();
}
private boolean CheckAddress(String iAddress, String oPerson)
{
Cursor cAddress = mDbHelper.getAllContacts();
String address = "";
if (cAddress.getCount() > 0) {
cAddress.moveToFirst();
while (cAddress.isAfterLast() == false) {
address = cAddress.getString(2).toString();
oPerson = cAddress.getString(1).toString();
if(iAddress.indexOf(address) != -1)
{
Toast.makeText(this,
"Person : " + oPerson,
Toast.LENGTH_LONG).show();
System.out.println(oPerson);
cAddress.close();
return true;
}
else cAddress.moveToNext();
}
}
cAddress.close();
return false;
}
The result is
Person : John
It's Match! null
Actually, "It's Match! John"
Please check my mistake.
Go to /xampp/mysql/bin
and find for mysql. exe
open cmd
, change the directory to mysq
after write in cmd
mysql -h localhost -u root
It could be too late. But, I encountered similar problem and in my case the project had self reference. Hence, deleting it from the References worked like a charm!!!
Using the Signum.Utilities library from SignumFramework (which you can use stand-alone), you can get it nicely and without dealing with the registry by yourself:
AboutTools.FrameworkVersions().ToConsole();
//Writes in my machine:
//v2.0.50727 SP2
//v3.0 SP2
//v3.5 SP1
for higher precision. this format:
45 11.735N,004 34.281E
and this
45 23.623, 5 38.77
To use arrow functions with function.prototype.call
, I made a helper function on the object prototype:
// Using
// @func = function() {use this here} or This => {use This here}
using(func) {
return func.call(this, this);
}
usage
var obj = {f:3, a:2}
.using(This => This.f + This.a) // 5
Edit
You don't NEED a helper. You could do:
var obj = {f:3, a:2}
(This => This.f + This.a).call(undefined, obj); // 5
FWIW, the -i option was a red herring for me. ssh-copy-id will use ~/.ssh/id_rsa.pub by default.
What was keeping it from working for me was the permissions on the ~ directory, the ~/.ssh directory, and the ~/.ssh/authorized_keys file on the remote computer.
All three need to be set with chmod 755 ~ ~/.ssh ~/.ssh/authorized_keys
, then ssh-copy-id your-remote-server.com
will work.
I had pip
referring by default to pip3, which made me download the libs for python3. On the contrary I launched the shell as python
(which opened python 2) and the library wasn't installed there obviously.
Once I matched the names pip3 -> python3, pip -> python (2) all worked.
By default, MomentJS parses in local time. If only a date string (with no time) is provided, the time defaults to midnight.
In your code, you create a local date and then convert it to the UTC timezone (in fact, it makes the moment instance switch to UTC mode), so when it is formatted, it is shifted (depending on your local time) forward or backwards.
If the local timezone is UTC+N (N being a positive number), and you parse a date-only string, you will get the previous date.
Here are some examples to illustrate it (my local time offset is UTC+3 during DST):
>>> moment('07-18-2013', 'MM-DD-YYYY').utc().format("YYYY-MM-DD HH:mm")
"2013-07-17 21:00"
>>> moment('07-18-2013 12:00', 'MM-DD-YYYY HH:mm').utc().format("YYYY-MM-DD HH:mm")
"2013-07-18 09:00"
>>> Date()
"Thu Jul 25 2013 14:28:45 GMT+0300 (Jerusalem Daylight Time)"
If you want the date-time string interpreted as UTC, you should be explicit about it:
>>> moment(new Date('07-18-2013 UTC')).utc().format("YYYY-MM-DD HH:mm")
"2013-07-18 00:00"
or, as Matt Johnson mentions in his answer, you can (and probably should) parse it as a UTC date in the first place using moment.utc()
and include the format string as a second argument to prevent ambiguity.
>>> moment.utc('07-18-2013', 'MM-DD-YYYY').format("YYYY-MM-DD HH:mm")
"2013-07-18 00:00"
To go the other way around and convert a UTC date to a local date, you can use the local()
method, as follows:
>>> moment.utc('07-18-2013', 'MM-DD-YYYY').local().format("YYYY-MM-DD HH:mm")
"2013-07-18 03:00"
A single quote is used for character, while double quotes are used for strings.
printf("%c \n",'a');
printf("%s","Hello World");
a
Hello World
If you used these in vice versa case and used a single quote for string and double quotes for a character, this will be the result:
printf("%c \n","a");
printf("%s",'Hello World');
For the first line. You will get a garbage value or unexpected value or you may get an output like this:
?
While for the second statement, you will see nothing. One more thing, if you have more statements after this, they will also give you no result.
Note: PHP language gives you the flexibility to use single and double-quotes easily.
Update: 2017-01-10
Data URIs are now supported by all major browsers. IE supports embedding images since version 8 as well.
http://caniuse.com/#feat=datauri
Data URIs are now supported by the following web browsers:
- Gecko-based, such as Firefox, SeaMonkey, XeroBank, Camino, Fennec and K-Meleon
- Konqueror, via KDE's KIO slaves input/output system
- Opera (including devices such as the Nintendo DSi or Wii)
- WebKit-based, such as Safari (including on iOS), Android's browser, Epiphany and Midori (WebKit is a derivative of Konqueror's KHTML engine, but Mac OS X does not share the KIO architecture so the implementations are different), as well as Webkit/Chromium-based, such as Chrome
- Trident
- Internet Explorer 8: Microsoft has limited its support to certain "non-navigable" content for security reasons, including concerns that JavaScript embedded in a data URI may not be interpretable by script filters such as those used by web-based email clients. Data URIs must be smaller than 32 KiB in Version 8[3].
- Data URIs are supported only for the following elements and/or attributes[4]:
- object (images only)
- img
- input type=image
- link
- CSS declarations that accept a URL, such as background-image, background, list-style-type, list-style and similar.
- Internet Explorer 9: Internet Explorer 9 does not have 32KiB limitation and allowed in broader elements.
- TheWorld Browser: An IE shell browser which has a built-in support for Data URI scheme
http://en.wikipedia.org/wiki/Data_URI_scheme#Web_browser_support
The abort
function does this. For example:
abort("Message goes here")
Note: the abort
message will be written to STDERR
as opposed to puts
which will write to STDOUT
.
Instead of passing variable to template globally, you can define a base template and render the 'global part' in it. The base template can be inherited.
Example of rendering template From the symfony Documentation:
<div id="sidebar">
{% render "AcmeArticleBundle:Article:recentArticles" with {'max': 3} %}
</div>
OK I have answered my own question (but is it the best way?)
This is how to run a method when you click or tap on some text in a TextView:
package com.textviewy;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.TextView;
public class TextyView extends Activity implements OnClickListener {
TextView t ;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
t = (TextView)findViewById(R.id.TextView01);
t.setOnClickListener(this);
}
public void onClick(View arg0) {
t.setText("My text on click");
}
}
and my main.xml is:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<LinearLayout android:id="@+id/LinearLayout01" android:layout_width="wrap_content" android:layout_height="wrap_content"></LinearLayout>
<ListView android:id="@+id/ListView01" android:layout_width="wrap_content" android:layout_height="wrap_content"></ListView>
<LinearLayout android:id="@+id/LinearLayout02" android:layout_width="wrap_content" android:layout_height="wrap_content"></LinearLayout>
<TextView android:text="This is my first text"
android:id="@+id/TextView01"
android:layout_width="wrap_content"
android:textStyle="bold"
android:textSize="28dip"
android:editable = "true"
android:clickable="true"
android:layout_height="wrap_content">
</TextView>
</LinearLayout>
You can use lscache. It handles this for you automatically, including instances where the storage size exceeds the limit. If that happens, it begins pruning items that are the closest to their specified expiration.
From the readme
:
lscache.set
Stores the value in localStorage. Expires after specified number of minutes.
Arguments
key (string)
value (Object|string)
time (number: optional)
This is the only real difference between the regular storage methods. Get, remove, etc work the same.
If you don't need that much functionality, you can simply store a time stamp with the value (via JSON) and check it for expiry.
Noteworthy, there's a good reason why local storage is left up to the user. But, things like lscache do come in handy when you need to store extremely temporary data.
You can pass the inline handler the this
keyword, obtaining the element which fired the event.
like,
onclick="confirmSubmit(this);"
There are references to the official docs (DialogFragment Reference) in other answers, but no mention of the example given there:
void showDialog() {
mStackLevel++;
// DialogFragment.show() will take care of adding the fragment
// in a transaction. We also want to remove any currently showing
// dialog, so make our own transaction and take care of that here.
FragmentTransaction ft = getFragmentManager().beginTransaction();
Fragment prev = getFragmentManager().findFragmentByTag("dialog");
if (prev != null) {
ft.remove(prev);
}
ft.addToBackStack(null);
// Create and show the dialog.
DialogFragment newFragment = MyDialogFragment.newInstance(mStackLevel);
newFragment.show(ft, "dialog");
}
This removes any currently shown dialog, creates a new DialogFragment with an argument, and shows it as a new state on the back stack. When the transaction is popped, the current DialogFragment and its Dialog will be destroyed, and the previous one (if any) re-shown. Note that in this case DialogFragment will take care of popping the transaction of the Dialog is dismissed separately from it.
For my needs I changed it to:
FragmentManager manager = getSupportFragmentManager();
Fragment prev = manager.findFragmentByTag(TAG);
if (prev != null) {
manager.beginTransaction().remove(prev).commit();
}
MyDialogFragment fragment = new MyDialogFragment();
fragment.show(manager, TAG);
If you are using Authentication, I recommend adding the following in web.config file.
In my case, users are redirected to the login page upon timing out:
<authentication mode="Forms">
<forms defaultUrl="Login.aspx" timeout="120"/>
</authentication>
Arrays.asList
is the handy function available in Java to convert an array variable to List or Collection. For better under standing consider the below example:
package com.stackoverflow.works;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class Wetland {
private String name;
private List<String> species = new ArrayList<String>();
public Wetland(String name, String[] speciesArr) {
this.name = name;
this.species = Arrays.asList(speciesArr);
}
public void display() {
System.out.println("Name: " + name);
System.out.println("Elements in the List");
System.out.println("********************");
for (String string : species) {
System.out.println(string);
}
}
/*
* @Description: Method to test your code
*/
public static void main(String[] args) {
String name = "Colors";
String speciesArr[] = new String [] {"red", "blue", "green"};
Wetland wetland = new Wetland(name, speciesArr);
wetland.display();
}
}
Output:
Is it a good practice to use try-except-else in python?
The answer to this is that it is context dependent. If you do this:
d = dict()
try:
item = d['item']
except KeyError:
item = 'default'
It demonstrates that you don't know Python very well. This functionality is encapsulated in the dict.get
method:
item = d.get('item', 'default')
The try
/except
block is a much more visually cluttered and verbose way of writing what can be efficiently executing in a single line with an atomic method. There are other cases where this is true.
However, that does not mean that we should avoid all exception handling. In some cases it is preferred to avoid race conditions. Don't check if a file exists, just attempt to open it, and catch the appropriate IOError. For the sake of simplicity and readability, try to encapsulate this or factor it out as apropos.
Read the Zen of Python, understanding that there are principles that are in tension, and be wary of dogma that relies too heavily on any one of the statements in it.
With Web API 2.2: Request.GetOwinContext().Request.RemoteIpAddress
The error is completely correct.
As it's trying to tell you, .sort()
takes a function that returns number, not boolean.
You need to return negative if the first item is smaller; positive if it it's larger, or zero if they're equal.
Or you can use unescapeHtml4:
String miCadena="GUÍA TELEFÓNICA";
System.out.println(StringEscapeUtils.unescapeHtml4(miCadena));
This code print the line: GUÍA TELEFÓNICA
In LINUX
1.Single line commenting. Ctrl + /
2.For block comment Ctrl + Shift + /
This is probably a configuration error. If you insist on using PHP mail
function, you will have to edit php.ini
.
If you are looking for an easier and more versatile option (in my opinion), you should use PHPMailer.
Not gonna happen with CSS only
Inline javascript
<a href='index.html'
onmouseover='this.style.textDecoration="none"'
onmouseout='this.style.textDecoration="underline"'>
Click Me
</a>
In a working draft of the CSS2 spec it was declared that you could use pseudo-classes inline like this:
<a href="http://www.w3.org/Style/CSS"
style="{color: blue; background: white} /* a+=0 b+=0 c+=0 */
:visited {color: green} /* a+=0 b+=1 c+=0 */
:hover {background: yellow} /* a+=0 b+=1 c+=0 */
:visited:hover {color: purple} /* a+=0 b+=2 c+=0 */
">
</a>
but it was never implemented in the release of the spec as far as I know.
http://www.w3.org/TR/2002/WD-css-style-attr-20020515#pseudo-rules
After two dozens of comments to understand the situation, it was found that the libhdf5.so.7
was actually a symlink (with several levels of indirection) to a file that was not shared between the queued processes and the interactive processes. This means even though the symlink itself lies on a shared filesystem, the contents of the file do not and as a result the process was seeing different versions of the library.
For future reference: other than checking LD_LIBRARY_PATH
, it's always a good idea to check a library with nm -D
to see if the symbols actually exist. In this case it was found that they do exist in interactive mode but not when run in the queue. A quick md5sum
revealed that the files were actually different.
curl will encode the data for you, just drop your raw field data into the fields array and tell it to "go".
SELECT * FROM `orders` WHERE `order_date_time` BETWEEN 1534809600 AND 1536718364
Open project.properties file and change the line with target=android-22 to the desired value.
For example:
target=android-19
Having just struggled with this - I'll explain my situation.
I have my tabs within a bootstrap modal and set the following on load (pre the modal being triggered):
$('#subMenu li:first-child a').tab('show');
Whilst the tab was selected the actual pane wasn't visible. As such you need to add active
class to the pane as well:
$('#profile').addClass('active');
In my case the pane had #profile
(but this could have easily been .pane:first-child
) which then displayed the correct pane.
Try this: edited
@echo off
set "comd=dir /b /s *.zip"
set "pathName="
set /p "pathName=Enter The Value: "
cd /d "%pathName%"
%comd%
pause
Without INDIRECT(): =CELL("width", OFFSET($A$1,ROW()-1,COLUMN()-1) )
I deleted my project (root folder) and created it again. It was the fastest and simplest way in my case.
Do not forget to save all you changes, before you delete you project!
Request.Headers["Referer"]
Request.UrlReferer
property will throw a System.UriFormatException
if the referer HTTP header is malformed (which can happen since it is not usually under your control).Therefore, the Request.UrlReferer
property is not 100% reliable - it may contain data that cannot be parsed into a Uri
class. To ensure the value is always readable, use Request.Headers["Referrer"]
instead.
As for using Request.ServerVariables
as others here have suggested, per MSDN:
Request.ServerVariables Collection
The ServerVariables collection retrieves the values of predetermined environment variables and request header information.
Request.Headers Property
Gets a collection of HTTP headers.
Request.Headers
is a better choice than Request.ServerVariables
, since Request.ServerVariables
contains all of the environment variables as well as the headers, where Request.Headers
is a much shorter list that only contains the headers.
So the most reliable solution is to use the Request.Headers
collection to read the value directly. Do heed Microsoft's warnings about HTML encoding the value if you are going to display it on a form, though.
See the image for reference :- (Soruce :- Android Studio-Image Assets option and Android Office Site )
Alternative to sp_defaultdb (which will be removed in a future version of Microsoft SQL Server) could be ALTER LOGIN
:
ALTER LOGIN [my_user_name] WITH DEFAULT_DATABASE = [new_default_database]
Note: unlike the sp_defaultdb
solution user and database names are provided without quotes. Brackets are needed if name had special chars (most common example will be domain user which is domain\username
and won't work without brackets).
There are three parts to this:
Keep in mind that a cookie is actually defined by the tuple of it's name, path, and domain. If any one of those three is different, or there is more than one cookie of the same name, but defined with paths/domains that may still be visible for the URL in question, you'll still see that cookie passed on the request. E.g. if the url is "http://foo.bar.com/baz/index.html", you'll see any cookies defined on bar.com or foo.bar.com, or with a path of "/" or "/baz".
Thus, what you have looks like it should work, as long as there's only one cookie defined in the client, with the name "SSO_COOKIE_NAME", domain "SSO_DOMAIN", and path "/". If there are any cookies with different path or domain, you'll still see the cookie sent to the client.
To debug this, go into Firefox's preferences -> Security tab, and search for all cookies with the SSO_COOKIE_NAME. Click on each to see the domain and path. I'm betting you'll find one in there that's not quite what you're expecting.
Actually its pretty easy to make integration between Csharp (VS) and Python with IronPython. It's not that much complex... As Chris Dunaway already said in answer section I started to build this inegration for my own project. N its pretty simple. Just follow these steps N you will get your results.
step 1 : Open VS and create new empty ConsoleApp project.
step 2 : Go to tools --> NuGet Package Manager --> Package Manager Console.
step 3 : After this open this link in your browser and copy the NuGet Command. Link: https://www.nuget.org/packages/IronPython/2.7.9
step 4 : After opening the above link copy the PM>Install-Package IronPython -Version 2.7.9 command and paste it in NuGet Console in VS. It will install the supportive packages.
step 5 : This is my code that I have used to run a .py file stored in my Python.exe directory.
using IronPython.Hosting;//for DLHE
using Microsoft.Scripting.Hosting;//provides scripting abilities comparable to batch files
using System;
using System.Diagnostics;
using System.IO;
using System.Net;
using System.Net.Sockets;
class Hi
{
private static void Main(string []args)
{
Process process = new Process(); //to make a process call
ScriptEngine engine = Python.CreateEngine(); //For Engine to initiate the script
engine.ExecuteFile(@"C:\Users\daulmalik\AppData\Local\Programs\Python\Python37\p1.py");//Path of my .py file that I would like to see running in console after running my .cs file from VS.//process.StandardInput.Flush();
process.StandardInput.Close();//to close
process.WaitForExit();//to hold the process i.e. cmd screen as output
}
}
step 6 : save and execute the code
I got this when I did composer update
instead of composer install
.
Always use
//Super Fast
$('#my_id').find('.my_class');
instead of
// Fast:
$('#my_id .my_class');
Have look at JQuery Performance Rules.
Also at Jquery Doc
public static void main(String arg[])
{
HashMap<String, ArrayList<String>> hashmap =
new HashMap<String, ArrayList<String>>();
ArrayList<String> arraylist = new ArrayList<String>();
arraylist.add("Hello");
arraylist.add("World.");
hashmap.put("my key", arraylist);
arraylist = hashmap.get("not inserted");
System.out.println(arraylist);
arraylist = hashmap.get("my key");
System.out.println(arraylist);
}
null
[Hello, World.]
Works fine... maybe you find your mistake in my code.
How about this?
puts "ok" if hash_variable["key"] == "X"
You can access hash values with the [] operator
Select 'Shambhu' as ShambhuNewsFeed,Note as [News Fedd],NotificationId
from Notification with(nolock) where DesignationId=@Designation
Union All
Select 'Shambhu' as ShambhuNewsFeed,Note as [Notification],NotificationId
from Notification with(nolock)
where DesignationId=@Designation
order by NotificationId desc
There are no data-validation attributes on your input. Make sure you have generated it with a server side helper such as Html.TextBoxFor and that it is inside a form:
@using (Html.BeginForm())
{
...
@Html.TextBoxFor(x => x.AgreementNumber)
}
Also I don't know what the jquery.validate.inline.js
script is but if it somehow depends on the jquery.validate.js
plugin make sure that it is referenced after it.
In all cases look at your javascript console in the browser for potential errors or missing scripts.
Use the ArrayList copy constructor, then sort that.
List oldList;
List newList = new ArrayList(oldList);
Collections.sort(newList);
After making the copy, any changes to newList do not affect oldList.
Note however that only the references are copied, so the two lists share the same objects, so changes made to elements of one list affect the elements of the other.
try this... obviously you need to set each div to 25%. You then will need to add your content as needed :) Hope that helps.
<html>
<head>
<title>CSS devide window by 25% horizontally</title>
<meta http-equiv="content-type" content="text/html; charset=iso-8859-1" />
<style type="text/css" media="screen">
body {
margin:0;
padding:0;
height:100%;
}
#top_div
{
height:25%;
width:100%;
background-color:#009900;
margin:auto;
text-align:center;
}
#mid1_div
{
height:25%;
width:100%;
background-color:#990000;
margin:auto;
text-align:center;
color:#FFFFFF;
}
#mid2_div
{
height:25%;
width:100%;
background-color:#000000;
margin:auto;
text-align:center;
color:#FFFFFF;
}
#bottom_div
{
height:25%;
width:100%;
background-color:#990000;
margin:auto;
text-align:center;
color:#FFFFFF;
}
</style>
</head>
<body>
<div id="top_div">Top- height is 25% of window height</div>
<div id="mid1_div">Middle 1 - height is 25% of window height</div>
<div id="mid2_div">Middle 2 - height is 25% of window height</div>
<div id="bottom_div">Bottom - height is 25% of window height</div>
</body>
</html>
Tested and works fine, copy the code above into a HTML file, and open with your browser.
All you have to do is use the value attribute of input tags:
<input type="text" value="Your Value" />
Or, in the case of a textarea:
<textarea>Your Value</textarea>
Add /Y to the command line
It's a reserved keyword (like return, filter, function, break).
Also, as per Section 7.6.4 of Bruce Payette's Powershell in Action:
But what happens when you want a script to exit from within a function defined in that script? ... To make this easier, Powershell has the exit keyword.
Of course, as other have pointed out, it's not hard to do what you want by wrapping exit in a function:
PS C:\> function ex{exit}
PS C:\> new-alias ^D ex
As is defined in RFC 1341:
In the Extended BNF notation of RFC 822, a Content-Type header field value is defined as follows:
Content-Type := type "/" subtype *[";" parameter]
type := "application" / "audio" / "image" / "message" / "multipart" / "text" / "video" / x-token
x-token := < The two characters "X-" followed, with no intervening white space, by any token >
subtype := token
parameter := attribute "=" value
attribute := token
value := token / quoted-string
token := 1*
tspecials := "(" / ")" / "<" / ">" / "@" ; Must be in / "," / ";" / ":" / "\" / <"> ; quoted-string, / "/" / "[" / "]" / "?" / "." ; to use within / "=" ; parameter values
And a list of known MIME types that can follow it (or, as Joe remarks, the IANA source).
As you can see the list is way too big for you to validate against all of them. What you can do is validate against the general format and the type
attribute to make sure that is correct (the set of options is small) and just assume that what follows it is correct (and of course catch any exceptions you might encounter when you put it to actual use).
Also note the comment above:
If another primary type is to be used for any reason, it must be given a name starting with "X-" to indicate its non-standard status and to avoid any potential conflict with a future official name.
You'll notice that a lot of HTTP requests/responses include an X-
header of some sort which are self defined, keep this in mind when validating the types.
You can turn Dark Mode off in entire application in Xcode 11:
Add bellow like
<key>UIUserInterfaceStyle</key>
<string>Light</string>
Info.plist will be look like below...
Another option:
$ cat << EOF > ~/.ipython/profile_default/startup/50-autoreload.ipy
%load_ext autoreload
%autoreload 2
EOF
Verified on ipython and ipython3 v5.1.0 on Ubuntu 14.04.